public void testUpdateGuestConfiguration() throws SecurityException, NoSuchMethodException, IOException { Method method = VCloudAsyncClient.class.getMethod( "updateGuestCustomizationOfVm", URI.class, GuestCustomizationSection.class); GuestCustomizationSection guest = new GuestCustomizationSection( URI.create("http://vcloud.example.com/api/v1.0/vApp/vm-12/guestCustomizationSection")); guest.setCustomizationScript("cat > /tmp/foo.txt<<EOF\nI love candy\nEOF"); HttpRequest request = processor.createRequest( method, URI.create("http://vcloud.example.com/api/v1.0/vApp/vm-12"), guest); assertRequestLineEquals( request, "PUT http://vcloud.example.com/api/v1.0/vApp/vm-12/guestCustomizationSection HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.task+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose(getClass().getResourceAsStream("/guestCustomizationSection.xml")), "application/vnd.vmware.vcloud.guestCustomizationSection+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, TaskHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testInstantiateVAppTemplateInVDCURI() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkVCloudExpressAsyncClient.class.getMethod( "instantiateVAppTemplateInVDC", URI.class, URI.class, String.class, InstantiateVAppTemplateOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), URI.create("https://vcloud/vAppTemplate/3"), "name"); assertRequestLineEquals( request, "POST https://vcloud.safesecureweb.com/api/v0.8/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vApp+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose( getClass().getResourceAsStream("/InstantiateVAppTemplateParams-test.xml")), "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, VAppHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testCaptureVAppInVDCOptions() throws SecurityException, NoSuchMethodException, IOException { Method method = VCloudAsyncClient.class.getMethod( "captureVAppInVDC", URI.class, URI.class, String.class, CaptureVAppOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcenterprise.bluelock.com/api/v1.0/vdc/1"), URI.create("https://vcenterprise.bluelock.com/api/v1.0/vapp/201"), "my-template", new CaptureVAppOptions().withDescription("The description of the new vApp Template")); assertRequestLineEquals( request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/captureVApp HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Accept: application/vnd.vmware.vcloud.vAppTemplate+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose(getClass().getResourceAsStream("/captureVApp.xml")), "application/vnd.vmware.vcloud.captureVAppParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, VAppTemplateHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testAddInternetServiceOptions() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkVCloudExpressAsyncClient.class.getMethod( "addInternetServiceToVDC", URI.class, String.class, Protocol.class, int.class, AddInternetServiceOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), "name", Protocol.TCP, 22, disabled().withDescription("yahoo")); assertRequestLineEquals( request, "POST https://vcloud.safesecureweb.com/api/v0.8/internetServices/1 HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Accept: application/vnd.tmrk.vCloud.internetService+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose( getClass().getResourceAsStream("/CreateInternetService-options-test.xml")), "application/vnd.tmrk.vCloud.internetService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testAddInternetServiceToExistingIp() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkVCloudExpressAsyncClient.class.getMethod( "addInternetServiceToExistingIp", URI.class, String.class, Protocol.class, int.class, AddInternetServiceOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcloud/extensions/publicIp/12"), "name", Protocol.TCP, 22); assertRequestLineEquals( request, "POST https://vcloud/extensions/publicIp/12/internetServices HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Accept: application/vnd.tmrk.vCloud.internetService+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose( getClass().getResourceAsStream("/CreateInternetService-test2.xml")), "application/vnd.tmrk.vCloud.internetService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testAddNodeOptions() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkVCloudExpressAsyncClient.class.getMethod( "addNode", URI.class, String.class, String.class, int.class, AddNodeOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcloud/extensions/internetService/12"), "10.2.2.2", "name", 22, AddNodeOptions.Builder.disabled().withDescription("yahoo")); assertRequestLineEquals( request, "POST https://vcloud/extensions/internetService/12/nodeServices HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose( getClass().getResourceAsStream("/CreateNodeService-options-test.xml")), "application/vnd.tmrk.vCloud.nodeService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testAllOptions() throws IOException { String expected = Strings2.toStringAndClose( getClass().getResourceAsStream("/InstantiateVAppTemplateParams-options-test.xml")); Multimap<String, String> headers = Multimaps.synchronizedMultimap(HashMultimap.<String, String>create()); GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); expect(request.getArgs()) .andReturn( ImmutableList.<Object>of( InstantiateVAppTemplateOptions.Builder.processorCount(2) .memory(512) .inGroup("group") .withPassword("password") .inRow("row") .addNetworkConfig(new NetworkConfig(URI.create("http://network"))))) .atLeastOnce(); expect(request.getFirstHeaderOrNull("Content-Type")) .andReturn("application/unknown") .atLeastOnce(); expect(request.getHeaders()).andReturn(headers).atLeastOnce(); request.setPayload(expected); replay(request); BindInstantiateVAppTemplateParamsToXmlPayload binder = injector.getInstance(BindInstantiateVAppTemplateParamsToXmlPayload.class); Map<String, String> map = Maps.newHashMap(); map.put("name", "name"); map.put("template", "https://vcloud/vAppTemplate/3"); binder.bindToRequest(request, map); }
@Deprecated public void testCloneVAppInVDC() throws SecurityException, NoSuchMethodException, IOException { Method method = VCloudAsyncClient.class.getMethod( "cloneVAppInVDC", URI.class, URI.class, String.class, CloneVAppOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcenterprise.bluelock.com/api/v1.0/vdc/1"), URI.create("https://vcenterprise.bluelock.com/api/v1.0/vapp/4181"), "my-vapp"); assertRequestLineEquals( request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/cloneVApp HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.task+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose(getClass().getResourceAsStream("/copyVApp-default.xml")), "application/vnd.vmware.vcloud.cloneVAppParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, TaskHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testPutAndGet() throws IOException { temp = File.createTempFile("foo", "bar"); temp.deleteOnExit(); SshClient client = setupClient(); client.put(temp.getAbsolutePath(), Payloads.newStringPayload("rabbit")); Payload input = setupClient().get(temp.getAbsolutePath()); String contents = Strings2.toStringAndClose(input.getInput()); assertEquals(contents, "rabbit"); }
public String parseMessage(final HttpResponse response) { if (response.getPayload() == null) { return null; } try { return Strings2.toStringAndClose(response.getPayload().openStream()); } catch (IOException e) { throw new RuntimeException(e); } }
@Override public ExecResponse create() throws Exception { try { ConnectionWithStreams<ChannelExec> connection = execConnection(command); executor = acquire(connection); String outputString = Strings2.toStringAndClose(connection.getInputStream()); String errorString = Strings2.toStringAndClose(connection.getErrStream()); int errorStatus = executor.getExitStatus(); int i = 0; String message = String.format("bad status -1 %s", toString()); while ((errorStatus = executor.getExitStatus()) == -1 && i < JschSshClient.this.sshRetries) { logger.warn("<< " + message); backoffForAttempt(++i, message); } if (errorStatus == -1) throw new SshException(message); return new ExecResponse(outputString, errorString, errorStatus); } finally { clear(); } }
public void testDefault() throws Exception { String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml")); GeneratedHttpRequest request = requestForArgs(ImmutableList.<Object>of()); BindCloneVAppParamsToXmlPayload binder = injector.getInstance(BindCloneVAppParamsToXmlPayload.class); Map<String, Object> map = Maps.newHashMap(); map.put("newName", "my-vapp"); map.put("vApp", "https://vcloud.safesecureweb.com/api/v0.8/vapp/4181"); assertEquals(binder.bindToRequest(request, map).getPayload().getRawContent(), expected); }
public void testWithDescriptionDeployOn() throws Exception { String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml")); CloneVAppOptions options = new CloneVAppOptions() .deploy() .powerOn() .withDescription("The description of the new vApp"); GeneratedHttpRequest request = requestForArgs(ImmutableList.<Object>of(options)); BindCloneVAppParamsToXmlPayload binder = injector.getInstance(BindCloneVAppParamsToXmlPayload.class); Map<String, Object> map = Maps.newHashMap(); map.put("newName", "new-linux-server"); map.put("vApp", "https://vcloud.safesecureweb.com/api/v0.8/vapp/201"); assertEquals(binder.bindToRequest(request, map).getPayload().getRawContent(), expected); }
public void testDefault() throws IOException { String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml")); GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); expect(request.getArgs()).andReturn(ImmutableList.<Object>of()).atLeastOnce(); request.setPayload(expected); replay(request); BindCloneVCloudExpressVAppParamsToXmlPayload binder = injector.getInstance(BindCloneVCloudExpressVAppParamsToXmlPayload.class); Map<String, String> map = Maps.newHashMap(); map.put("newName", "my-vapp"); map.put("vApp", "https://vcloud.safesecureweb.com/api/v0.8/vapp/4181"); binder.bindToRequest(request, map); verify(request); }
@DataProvider(name = "data") public Object[][] createData() throws IOException { InputStream is = ParseOsFamilyVersion64BitFromImageNameTest.class.getResourceAsStream("/osmatches.json"); Map<String, OsFamilyVersion64Bit> values = json.fromJson( Strings2.toStringAndClose(is), new TypeLiteral<Map<String, OsFamilyVersion64Bit>>() {}.getType()); return newArrayList( transform( values.entrySet(), new Function<Map.Entry<String, OsFamilyVersion64Bit>, Object[]>() { @Override public Object[] apply(Entry<String, OsFamilyVersion64Bit> input) { return new Object[] {input.getKey(), input.getValue()}; } })) .toArray(new Object[][] {}); }
public void testInstantiateVAppTemplateInVDCURIOptions() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkVCloudExpressAsyncClient.class.getMethod( "instantiateVAppTemplateInVDC", URI.class, URI.class, String.class, InstantiateVAppTemplateOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), URI.create("https://vcloud/vAppTemplate/3"), "name", TerremarkInstantiateVAppTemplateOptions.Builder.processorCount(2) .memory(512) .inGroup("group") .withPassword("password") .inRow("row") .addNetworkConfig(new NetworkConfig(URI.create("http://network")))); assertRequestLineEquals( request, "POST https://vcloud.safesecureweb.com/api/v0.8/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vApp+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose( getClass() .getResourceAsStream("/terremark/InstantiateVAppTemplateParams-options-test.xml")), "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, VCloudExpressVAppHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testComplete() throws IOException { CreateDriveRequest input = new CreateDriveRequest.Builder() .name("Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System") // .size(8589934592l) // .claimType(ClaimType.SHARED) // .readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff")) // .tags(ImmutableSet.of("tag1", "tag2")) .userMetadata(ImmutableMap.of("foo", "bar", "baz", "raz")) // .encryptionCipher("aes-xts-plain") .avoid(ImmutableSet.of("avoid1")) .build(); HttpRequest request = new HttpRequest("POST", URI.create("https://host/drives/create")); FN.bindToRequest(request, input); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); assertEquals( request.getPayload().getRawContent(), Strings2.toStringAndClose( BindDriveToPlainTextStringTest.class.getResourceAsStream("/create_drive.txt"))); }
public void testInstantiateVAppTemplateInVDCURIOptions() throws SecurityException, NoSuchMethodException, IOException { Method method = VCloudAsyncClient.class.getMethod( "instantiateVAppTemplateInVDC", URI.class, URI.class, String.class, InstantiateVAppTemplateOptions[].class); HttpRequest request = processor.createRequest( method, URI.create("https://vcenterprise.bluelock.com/api/v1.0/vdc/1"), URI.create("https://vcenterprise.bluelock.com/api/v1.0/vAppTemplate/3"), "my-vapp", addNetworkConfig( new NetworkConfig( "aloha", URI.create("https://vcenterprise.bluelock.com/api/v1.0/network/1991"), FenceMode.NAT_ROUTED))); assertRequestLineEquals( request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vApp+xml\n"); assertPayloadEquals( request, Strings2.toStringAndClose( getClass().getResourceAsStream("/instantiationparams-network.xml")), "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, VAppHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(request); }
public void testWithDescriptionDeployOn() throws IOException { String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml")); CloneVAppOptions options = new CloneVAppOptions() .deploy() .powerOn() .withDescription("The description of the new vApp"); GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); expect(request.getArgs()).andReturn(ImmutableList.<Object>of(options)).atLeastOnce(); request.setPayload(expected); replay(request); BindCloneVCloudExpressVAppParamsToXmlPayload binder = injector.getInstance(BindCloneVCloudExpressVAppParamsToXmlPayload.class); Map<String, String> map = Maps.newHashMap(); map.put("newName", "new-linux-server"); map.put("vApp", "https://vcloud.safesecureweb.com/api/v0.8/vapp/201"); binder.bindToRequest(request, map); verify(request); }
public ExecResponse exec(String command) { checkConnected(); ChannelExec executor = null; try { try { executor = (ChannelExec) session.openChannel("exec"); executor.setPty(true); } catch (JSchException e) { throw new SshException( String.format("%s@%s:%d: Error connecting to exec.", username, host, port), e); } executor.setCommand(command); ByteArrayOutputStream error = new ByteArrayOutputStream(); executor.setErrStream(error); try { executor.connect(); String outputString = Strings2.toStringAndClose(executor.getInputStream()); String errorString = error.toString(); int errorStatus = executor.getExitStatus(); int i = 0; while ((errorStatus = executor.getExitStatus()) == -1 && i < this.sshRetries) backoffForAttempt(++i, String.format("%s@%s:%d: bad status: -1", username, host, port)); if (errorStatus == -1) throw new SshException( String.format( "%s@%s:%d: received exit status %d executing %s", username, host, port, executor.getExitStatus(), command)); return new ExecResponse(outputString, errorString, errorStatus); } catch (Exception e) { throw new SshException( String.format("%s@%s:%d: Error executing command: %s", username, host, port, command), e); } } finally { if (executor != null) executor.disconnect(); } }
@Singleton @Provides @Named("CreateKey") String provideCreateKey() throws IOException { return Strings2.toStringAndClose(getClass().getResourceAsStream("/CreateKey.xml")); }
public void testGetEtcPassword() throws IOException { Payload input = setupClient().get("/etc/passwd"); String contents = Strings2.toStringAndClose(input.getInput()); assert contents.indexOf("root") >= 0 : "no root in " + contents; }
public static String getCurrentCIDR() throws IOException { URL url = new URL("http://checkip.amazonaws.com/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); return Strings2.toStringAndClose(connection.getInputStream()).trim() + "/32"; }
public void handleError(HttpCommand command, HttpResponse response) { HttpRequest request = command.getCurrentRequest(); Exception exception = new HttpResponseException(command, response); try { VCloudError error = null; String message = null; if (response.getPayload() != null) { try { error = utils.parseErrorFromContent(request, response); if (error != null) { message = error.getMessage(); exception = new VCloudResponseException(command, response, error); } else { message = Strings2.toStringAndClose(response.getPayload().getInput()); exception = message != null ? new HttpResponseException(command, response, message) : exception; } } catch (IOException e) { } finally { response.getPayload().release(); } } message = message != null ? message : String.format("%s -> %s", request.getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (error != null && ((error.getMinorErrorCode() != null && error.getMinorErrorCode() == MinorCode.BUSY_ENTITY) || (error.getMessage() != null && error.getMessage().indexOf("is not running") != -1))) exception = new IllegalStateException(message, exception); else exception = new IllegalArgumentException(message, exception); break; case 401: case 403: if (error != null && ((error.getMinorErrorCode() != null && error.getMinorErrorCode() == MinorCode.ACCESS_TO_RESOURCE_IS_FORBIDDEN) || (error.getMessage() != null && error.getMessage().indexOf("No access to entity") != -1))) exception = new ResourceNotFoundException(message, exception); else exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = RESOURCE_PATTERN.matcher(path); if (matcher.find()) { message = String.format("%s %s not found", matcher.group(1), matcher.group(2)); } else { message = path; } exception = new ResourceNotFoundException(message); } break; } } finally { releasePayload(response); command.setException(exception); } }
@BeforeGroups(groups = {"live"}) public SshClient setupClient() throws NumberFormatException, FileNotFoundException, IOException { int port = Integer.parseInt(sshPort); if (sshUser == null || ((sshPass == null || sshPass.trim().equals("")) && (sshKeyFile == null || sshKeyFile.trim().equals(""))) || sshUser.trim().equals("")) { System.err.println("ssh credentials not present. Tests will be lame"); return new SshClient() { public void connect() {} public void disconnect() {} public Payload get(String path) { if (path.equals("/etc/passwd")) { return Payloads.newStringPayload("root"); } else if (path.equals(temp.getAbsolutePath())) { return Payloads.newStringPayload("rabbit"); } throw new RuntimeException("path " + path + " not stubbed"); } public ExecResponse exec(String command) { if (command.equals("hostname")) { return new ExecResponse(sshHost, "", 0); } throw new RuntimeException("command " + command + " not stubbed"); } @Override public void put(String path, Payload contents) {} @Override public String getHostAddress() { return null; } @Override public String getUsername() { return null; } @Override public void put(String path, String contents) {} }; } else { Injector i = Guice.createInjector(new JschSshClientModule(), new SLF4JLoggingModule()); SshClient.Factory factory = i.getInstance(SshClient.Factory.class); SshClient connection; if (Strings.emptyToNull(sshKeyFile) != null) { connection = factory.create( new IPSocket(sshHost, port), LoginCredentials.builder() .user(sshUser) .privateKey(Strings2.toStringAndClose(new FileInputStream(sshKeyFile))) .build()); } else { connection = factory.create( new IPSocket(sshHost, port), LoginCredentials.builder().user(sshUser).password(sshPass).build()); } connection.connect(); return connection; } }
protected void checkToYaml(Map<String, InputStream> map, String key, String id, String name) throws IOException { assertEquals( Strings2.toStringAndClose(map.get(key)), String.format("id: %s\nname: %s\n", id, name)); }