I am trying to create mocks from the services needed for a system under test. I am using MockServer (mock-server.com) for that purpose. Here is code to mock the a service.
ClientAndServer mockServer = startClientAndServer(1080);
QueryResultResponse response = new QueryResultResponse();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String jsonStr = ow.writeValueAsString(response);
new MockServerClient("127.0.0.1", 1080)
.when(
request()
.withMethod("POST"),
Times.unlimited()
)
.respond(
response()
.withStatusCode(200)
.withBody(jsonStr)
.withHeader(new Header("Content-Type", "application/json"))
);
When I try to execute this piece of code from a JUnit rule, the thread gets blocked on java.net.SocketInputStream.socketRead0 and thus not able to execute the unit tests that would use this mock. Here is stack for the block call.
(SocketInputStream.java) java.net.SocketInputStream.socketRead0
(SocketInputStream.java:152) java.net.SocketInputStream.read
(SocketInputStream.java:122) java.net.SocketInputStream.read
(LoggingInputStream.java:72) org.apache.http.impl.conn.LoggingInputStream.read
(SessionInputBufferImpl.java:136) org.apache.http.impl.io.SessionInputBufferImpl.streamRead
(SessionInputBufferImpl.java:152) org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer
(SessionInputBufferImpl.java:270) org.apache.http.impl.io.SessionInputBufferImpl.readLine
(DefaultHttpResponseParser.java:140) org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead
(DefaultHttpResponseParser.java:57) org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead
(AbstractMessageParser.java:260) org.apache.http.impl.io.AbstractMessageParser.parse
(DefaultBHttpClientConnection.java:161) org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader
(NativeMethodAccessorImpl.java) sun.reflect.NativeMethodAccessorImpl.invoke0
(NativeMethodAccessorImpl.java:57) sun.reflect.NativeMethodAccessorImpl.invoke
(DelegatingMethodAccessorImpl.java:43) sun.reflect.DelegatingMethodAccessorImpl.invoke
(Method.java:606) java.lang.reflect.Method.invoke
(CPoolProxy.java:138) org.apache.http.impl.conn.CPoolProxy.invoke
() com.sun.proxy.$Proxy73.receiveResponseHeader
(HttpRequestExecutor.java:271) org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse
(HttpRequestExecutor.java:123) org.apache.http.protocol.HttpRequestExecutor.execute
(MainClientExec.java:253) org.apache.http.impl.execchain.MainClientExec.execute
(ProtocolExec.java:194) org.apache.http.impl.execchain.ProtocolExec.execute
(RetryExec.java:85) org.apache.http.impl.execchain.RetryExec.execute
(RedirectExec.java:108) org.apache.http.impl.execchain.RedirectExec.execute
(InternalHttpClient.java:186) org.apache.http.impl.client.InternalHttpClient.doExecute
(CloseableHttpClient.java:82) org.apache.http.impl.client.CloseableHttpClient.execute
(CloseableHttpClient.java:106) org.apache.http.impl.client.CloseableHttpClient.execute
(ApacheHttpClient.java:103) org.mockserver.client.http.ApacheHttpClient.sendPUTRequest
(MockServerClient.java:155) org.mockserver.client.server.MockServerClient.sendExpectation
(ForwardChainExpectation.java:23) org.mockserver.client.server.ForwardChainExpectation.respond
(TestMockService.java:74) oracle.sysman.test.unit.TestMockService.call
(TestLoganUploadServiceUnit.java:99) oracle.sysman.test.unit.ws.TestLoganUploadServiceUnit.startMockServer
(NativeMethodAccessorImpl.java) sun.reflect.NativeMethodAccessorImpl.invoke0
(NativeMethodAccessorImpl.java:57) sun.reflect.NativeMethodAccessorImpl.invoke
(DelegatingMethodAccessorImpl.java:43) sun.reflect.DelegatingMethodAccessorImpl.invoke
(Method.java:606) java.lang.reflect.Method.invoke
(FrameworkMethod.java:47) org.junit.runners.model.FrameworkMethod$1.runReflectiveCall
(ReflectiveCallable.java:12) org.junit.internal.runners.model.ReflectiveCallable.run
(FrameworkMethod.java:44) org.junit.runners.model.FrameworkMethod.invokeExplosively
(RunBefores.java:24) org.junit.internal.runners.statements.RunBefores.evaluate
(MockServerRule.java:107) org.mockserver.junit.MockServerRule$1.evaluate
(RunRules.java:20) org.junit.rules.RunRules.evaluate
(ParentRunner.java:271) org.junit.runners.ParentRunner.runLeaf
(BlockJUnit4ClassRunner.java:70) org.junit.runners.BlockJUnit4ClassRunner.runChild
(BlockJUnit4ClassRunner.java:50) org.junit.runners.BlockJUnit4ClassRunner.runChild
(ParentRunner.java:238) org.junit.runners.ParentRunner$3.run
(ParentRunner.java:63) org.junit.runners.ParentRunner$1.schedule
(ParentRunner.java:236) org.junit.runners.ParentRunner.runChildren
(ParentRunner.java:53) org.junit.runners.ParentRunner.access$000
(ParentRunner.java:229) org.junit.runners.ParentRunner$2.evaluate
(ParentRunner.java:309) org.junit.runners.ParentRunner.run
(Suite.java:127) org.junit.runners.Suite.runChild
(Suite.java:26) org.junit.runners.Suite.runChild
(ParentRunner.java:238) org.junit.runners.ParentRunner$3.run
(ParentRunner.java:63) org.junit.runners.ParentRunner$1.schedule
(ParentRunner.java:236) org.junit.runners.ParentRunner.runChildren
(ParentRunner.java:53) org.junit.runners.ParentRunner.access$000
(ParentRunner.java:229) org.junit.runners.ParentRunner$2.evaluate
(RunBefores.java:26) org.junit.internal.runners.statements.RunBefores.evaluate
(RunAfters.java:27) org.junit.internal.runners.statements.RunAfters.evaluate
(ParentRunner.java:309) org.junit.runners.ParentRunner.run
(JUnit4Testable.java:24) oracle.jdevimpl.junit.runner.junit4.JUnit4Testable.run
(TestExecution.java:27) oracle.jdevimpl.junit.runner.TestExecution.run
(JUnitTestRunner.java:93) oracle.jdevimpl.junit.runner.JUnitTestRunner.main
Related
I am trying to sign a UBL document and I want to append the signature generated by xades4j within Extensions element tree like this :
<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionURI>urn:oasis:names:specification:ubl:dsig:enveloped:xades</ext:ExtensionURI>
<ext:ExtensionContent>
<sig:UBLDocumentSignatures xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:sbc="urn:oasis:names:specification:ubl:schema:xsd:SignatureBasicComponents-2">
<sac:SignatureInformation>
<cbc:ID>urn:oasis:names:specification:ubl:signature:1</cbc:ID>
<sbc:ReferencedSignatureID>
urn:oasis:names:specification:ubl:signature:Invoice
</sbc:ReferencedSignatureID>
*ds:Signature element goes here...*
</sac:SignatureInformation>
</sig:UBLDocumentSignatures>
</sig:UBLDocumentSignatures>
</ext:ExtensionContent>
</ext:UBLExtension>
</ext:UBLExtensions>
rest of Invoice children ...
</Invoice>
Code to generate signature :
org.w3c.dom.Document w3cDoc = ...;
KeyingDataProvider keyingDataProvider = new AppxKeyDataProvider();
SignatureAlgorithms signatureAlgorithms = new
SignatureAlgorithms().withSignatureAlgorithm("ECDSA", XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256);
XadesSigningProfile profile = new XadesBesSigningProfile(keyingDataProvider).withSignatureAlgorithms(signatureAlgorithms);
XadesSigner signer = profile.newSigner();
DataObjectDesc desc = new DataObjectReference("")
.withTransform(new XPathTransform("not(//ancestor-or-self::ext:UBLExtensions)"))
.withTransform(new XPathTransform("not(//ancestor-or-self::cac:Signature)"))
.withTransform(new XPathTransform("not(//ancestor-or-self::cac:AdditionalDocumentReference[cbc:ID='QR'])"))
.withTransform(new xades4j.algorithms.CanonicalXMLWithoutComments());
XadesSignatureResult result = signer.sign(new SignedDataObjects(desc), w3cDoc.getDocumentElement(),signatureAppendingStrategy);
Custom SignatureAppendingStrategy.append() method implementation
#Override
public void append(Element signatureElement, Node referenceNode) {
Element ublExtensions = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2","UBLExtensions");
ublExtensions.setPrefix("ext");
Element ublExtension = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2","UBLExtension");
ublExtension.setPrefix("ext");
ublExtensions.appendChild(ublExtension);
Element extensionURL = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2","ExtensionURI");
extensionURL.setPrefix("ext");
Node urlValue = w3cDoc.createTextNode("urn:oasis:names:specification:ubl:dsig:enveloped:xades");
extensionURL.appendChild(urlValue);
ublExtension.appendChild(extensionURL);
Element extensionContent = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2","ExtensionContent");
extensionContent.setPrefix("ext");
ublExtension.appendChild(extensionContent);
Element ublDocumentSignatures = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2","sig:UBLDocumentSignatures");
ublDocumentSignatures.setAttribute("xmlns:sac", "urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2");
ublDocumentSignatures.setAttribute("xmlns:sbc", "urn:oasis:names:specification:ubl:schema:xsd:SignatureBasicComponents-2");
extensionContent.appendChild(ublDocumentSignatures);
Element signatureInformation = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2","SignatureInformation");
signatureInformation.setPrefix("sac");
ublDocumentSignatures.appendChild(signatureInformation);
Element cbcId = w3cDoc.createElementNS("urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2","ID");
cbcId.setPrefix("cbc");
Node idValue = w3cDoc.createTextNode("urn:oasis:names:specification:ubl:signature:1");
cbcId.appendChild(idValue);
signatureInformation.appendChild(cbcId);
signatureInformation.appendChild(signatureElement);
referenceNode.insertBefore(ublExtensions, referenceNode.getFirstChild());
}
Exception :
Exception in thread "main" java.lang.RuntimeException: Could not resolve the node to a handle
at org.apache.xml.dtm.ref.DTMManagerDefault.getDTMHandleFromNode(DTMManagerDefault.java:576)
at org.apache.xpath.XPathContext.getDTMHandleFromNode(XPathContext.java:184)
at org.apache.xpath.XPath.execute(XPath.java:303)
at org.apache.xpath.jaxp.XPathExpressionImpl.eval(XPathExpressionImpl.java:121)
at org.apache.xpath.jaxp.XPathExpressionImpl.eval(XPathExpressionImpl.java:91)
at org.apache.xpath.jaxp.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:176)
at org.apache.xml.security.utils.JDKXPathAPI.evaluate(JDKXPathAPI.java:112)
at org.apache.xml.security.transforms.implementations.TransformXPath$XPathNodeFilter.isNodeInclude(TransformXPath.java:138)
at org.apache.xml.security.c14n.implementations.CanonicalizerBase.isVisible(CanonicalizerBase.java:489)
at org.apache.xml.security.c14n.implementations.CanonicalizerBase.canonicalizeXPathNodeSet(CanonicalizerBase.java:366)
at org.apache.xml.security.c14n.implementations.CanonicalizerBase.engineCanonicalizeXPathNodeSetInternal(CanonicalizerBase.java:302)
at org.apache.xml.security.c14n.implementations.CanonicalizerBase.engineCanonicalize(CanonicalizerBase.java:147)
at org.apache.xml.security.transforms.implementations.TransformC14N.enginePerformTransform(TransformC14N.java:70)
at org.apache.xml.security.transforms.Transform.performTransform(Transform.java:326)
at org.apache.xml.security.transforms.Transforms.performTransforms(Transforms.java:267)
at org.apache.xml.security.signature.Reference.getContentsAfterTransformation(Reference.java:450)
at org.apache.xml.security.signature.Reference.calculateDigest(Reference.java:708)
at org.apache.xml.security.signature.Reference.generateDigestValue(Reference.java:417)
at org.apache.xml.security.signature.Manifest.generateDigestValues(Manifest.java:209)
at org.apache.xml.security.signature.XMLSignature.sign(XMLSignature.java:782)
at xades4j.production.SignerBES.sign(SignerBES.java:270)
at testx.TestXades.main(TestXades.java:276)
Actually the exception occurs while I apply the XPath transform "not(//ancestor-or-self::ext:UBLExtensions)".
I'm trying to implement the Fast Gradient Sign Method (FGSM) on MobileNet with tensorflow.js, however I'm having problems on the latest version (1.0.1) when computing the gradient using tf.grad().
The code is working fine with tfjs version 0.13.0 and below, however updating to any of the later versions results in the following error:
core.js:15723 ERROR Error: Uncaught (in promise): Error: Tensor is disposed. Error: Tensor is disposed.
at e.throwIfDisposed (tf-core.esm.js:17)
at e.greaterEqual (tf-core.esm.js:17)
at Object.$x (tf-core.esm.js:17)
at n (tf-core.esm.js:17)
at backpropagateGradients (tf-core.esm.js:17)
at tf-core.esm.js:17
at tf-core.esm.js:17
at e.scopedRun (tf-core.esm.js:17)
at e.tidy (tf-core.esm.js:17)
at e.gradients (tf-core.esm.js:17)
at resolvePromise (zone.js:831)
at zone.js:896
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:17289)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at drainMicroTaskQueue (zone.js:601)
at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:502)
at ZoneTask.invoke (zone.js:487)
at timer (zone.js:2281)
The error occurs when calling tf.grad(lossFunction):
Any help/insight is appreciated!
Full code:
let canvas = <HTMLCanvasElement> document.getElementById('canvas')
let img = tf.browser.fromPixels(canvas, 3) //let img = tf.fromPixels(canvas, 3)
let img4 = tf.browser.fromPixels(canvas, 4) //let img4 = tf.fromPixels(canvas, 4)
let model = mobilenet.load().then(model =>
{
var output = model.classify(img, 3).then(predictions =>
{
let tbuffer = tf.buffer([1000])
var labelClasses = IMAGENET_CLASSES
let targetClass = predictions[0].className
Object.keys(labelClasses).forEach(function(key)
{
if (labelClasses[key].valueOf() == targetClass.valueOf())
{
tbuffer.set(1, parseInt(key));
}
})
const oneHotLabels = tbuffer.toTensor()
const getModelLogits = x => model.infer(x)
const lossFunction = x => tf.losses.softmaxCrossEntropy(oneHotLabels, getModelLogits(x).as1D())
const gradientFunction = tf.grad(lossFunction)
var gradient = gradientFunction(img)
// scale the gradient and apply to original image
var perturbation = this.scaleGradient(gradient, 50)
const zeroes = new Uint8Array(224*224).fill(0)
let alphaChannel = tf.tensor3d(zeroes, [224, 224, 1])
let perturbationWithAlpha = tf.concat([perturbation, alphaChannel], 2)
var adversarialImage = tf.add(tf.cast(img4,'float32'), perturbationWithAlpha)
// Draw adversarial image to canvas
var context = canvas.getContext("2d")
let imgArray = Uint8ClampedArray.from(adversarialImage.dataSync());
let imgData = context.createImageData(this.imgHeight, this.imgWidth);
imgData.data.set(imgArray);
context.putImageData(imgData, 0, 0);
})
})
Full repo available here: https://github.com/BenMcFadyen/tfjsFGSM
https://github.com/BenMcFadyen/tfjsFGSM/blob/master/src/app/app.component.ts
FGSM code originally from: https://github.com/jaxball/advis.js
full trace
successful execution on tensorflow/tfjs#0.13.0, tensorflow-models/mobilenet#0.2.2
tensorflow-models/mobilenet#0.2.2 was a tf.LayersModel, which provides gradients and thus is retrainable. However tensorflow-models/mobilenet#1.0.0 was changed to be a tf.GraphModel in https://github.com/tensorflow/tfjs-models/pull/161, in order to provide MobileNet V2 from TF-Hub. GraphModels do not provide gradients, and thus your code no longer works.
I think you have several possible paths forward:
Stick with working versions if they serve your needs (tensorflow-models/mobilenet#0.2.2 should work with tfjs up to 0.15.3, though that will produce deprecation warnings).
Fork tensorflow/tfjs-models at PR #156 and build the mobilenet package there.
That's the same as 0.2.2, except that it can be used with tfjs >1.0.0.
Fork tensorflow/tfjs-models from head, and revert the model-loading part to use tf.loadLayersModel() with the BASE_PATH that was removed in #161. (This gets you V1 only).
Obtain a MobileNet V2 in Keras .h5 format (e.g., from here) and use the TF.js converter to get a tf.LayersModel.
I reproduced the error and verified manually that https://github.com/tensorflow/tfjs-core/pull/1604 fixes it. The fix will be out in the next TF.js release (1.0.2), which we plan to get out by end of this week.
The gradients are working even though MobileNet is now a tf.GraphModel instead of tf.LayersModel, because the library is eager and can compute gradients on-the-fly.
Using the code below to validate DANE records on different mail servers i sometimes (close to 50% of the servers tested) get a "System.AggregateException" with the inner exception "Response records could not be validated".
var resolver = new SelfValidatingInternalDnsSecStubResolver();
string mx = "mail2.amedia.nu.";
DnsSecResult<TlsaRecord> result = resolver.ResolveSecure<TlsaRecord>("_25._tcp." + mx, RecordType.Tlsa);
Console.WriteLine(result.ValidationResult.ToString());
I pasted the first 1000 failed mx servers here for testing: https://pastebin.com/14kqQT06
Any idea why this exception is thrown?
I need to make signed requests to AWS ES, but am stuck at the first hurdle in that I cannot seem to be able to use CurlHttpClient. Here is my code (verb, path, and body defined elsewhere):
Aws::Client::ClientConfiguration clientConfiguration;
clientConfiguration.scheme = Aws::Http::Scheme::HTTPS;
clientConfiguration.region = Aws::Region::US_EAST_1;
auto client = Aws::MakeShared<Aws::Http::CurlHttpClient>(ALLOCATION_TAG, clientConfiguration);
Aws::Http::URI uri;
uri.SetScheme(Aws::Http::Scheme::HTTPS);
uri.SetAuthority(ELASTIC_SEARCH_DOMAIN);
uri.SetPath(path);
Aws::Http::Standard::StandardHttpRequest req(uri, verb);
req.AddContentBody(body);
auto res = client->MakeRequest(req);
Aws::Http::HttpResponseCode resCode = res->GetResponseCode();
if (resCode == Aws::Http::HttpResponseCode::OK) {
Aws::IOStream &body = res->GetResponseBody();
rejoiceAndBeMerry();
}
else {
gotoPanicStations();
}
When executed, the code throws a bad_function_call deep from within the sdk mixed up with a lot of shared_ptr this and allocate that. My guess is that I am just using the SDK wrong, but I've been unable to find any examples that use the CurlHttpClient directly such as I need to do here.
How can I use CurlHttpClient?
You shouldn't be using the HTTP client directly, but the supplied wrappers with the aws-cpp-sdk-es package. Like previous answer(s), I would recommend evaluating the test cases shipped with the library to see how the original authors intended to implement the API (at least until the documents catch-up).
How can I use CurlHttpClient?
Your on the right track with managed shared resources and helper functions. Just need to create a static factory/client to reference. Here's a generic example.
using namespace Aws::Client;
using namespace Aws::Http;
static std::shared_ptr<HttpClientFactory> MyClientFactory; // My not be needed
static std::shared_ptr<HttpClient> MyHttpClient;
// ... jump ahead to method body ...
ClientConfiguration clientConfiguration;
MyHttpClient = CreateHttpClient(clientConfiguration);
Aws::String uri("https://example.org");
std::shared_ptr<HttpRequest> req(
CreateHttpRequest(uri,
verb, // i.e. HttpMethod::HTTP_POST
Utils::Stream::DefaultResponseStreamFactoryMethod));
req.AddContentBody(body); //<= remember `body' should be `std::shared_ptr<Aws::IOStream>',
// and can be created with `Aws::MakeShared<Aws::StringStream>("")';
req.SetContentLength(body_size);
req.SetContentType(body_content_type);
std::shared_ptr<HttpResponse> res = MyHttpClient->MakeRequest(*req);
HttpResponseCode resCode = res->GetResponseCode();
if (resCode == HttpResponseCode::OK) {
Aws::StringStream resBody;
resBody << res->GetResponseBody().rdbuf();
rejoiceAndBeMerry();
} else {
gotoPanicStations();
}
I encountered exactly the same error when trying to download from S3 using CurlHttpClient.
I fixed it by instead modelling my code after the integration test found in the cpp sdk:
aws-sdk-cpp/aws-cpp-sdk-s3-integration-tests/BucketAndObjectOperationTest.cpp
Search for the test called TestObjectOperationsWithPresignedUrls.
I have a problem with my vm on Google cloud.
I try to start a vm in java but i dont know how can I start a vm from an image. I mean how can I set to source image.
my code is:
Instance instance = new Instance();
compute.machineTypes();
String machine = "https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/machineTypes/g1-small";
instance.setMachineType(machine);
String name = "newinstance";
instance.setName(name);
List<NetworkInterface> networkInterfaces = new ArrayList<NetworkInterface>();
NetworkInterface iface = new NetworkInterface();
iface.setName("eth0");
iface.setNetwork("https://www.googleapis.com/compute/v1/projects/myproject/global/networks/default");
networkInterfaces.add(iface);
instance.setNetworkInterfaces(networkInterfaces);
Disk disk = new Disk();
disk.setSizeGb(10L);
disk.setName("mydisk");
Compute.Disks.Insert insDisk = compute.disks().insert(projectId, zoneName, disk);
insDisk.execute();
AttachedDisk diskToInsert = new AttachedDisk();
diskToInsert.setBoot(true);
diskToInsert.setType("PERSISTENT");
diskToInsert.setMode("READ_WRITE");
diskToInsert.setDeviceName("newinstancedisk");
diskToInsert.setSource("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/disks/" + disk.getName());
List<AttachedDisk> listOfDisks = new ArrayList<AttachedDisk>();
listOfDisks.add(diskToInsert);
instance.setDisks(listOfDisks);
Compute.Instances.Insert ins = compute.instances().insert(projectId, zoneName, instance);
Operation op = ins.execute();
System.out.println(op.toPrettyString());
System.out.println(instance.toPrettyString());
You need to use the option 'disks[].initializeParams.sourceImage' where you can provide the full URL to the image used to create the root disk.
Take a look at these links instances, starting an instance in the API and startin an instance from an image and Instances. In the last link you can see the value you can provide for disks[].initializeParams.