List of usage examples for javax.xml.bind JAXBElement getName
public QName getName()
From source file:be.fedict.eid.tsl.TrustService.java
public void addOIDForQCForLegalPerson(String oid, boolean noRoot) { TSPServiceInformationType tspServiceInformation = this.tspService.getServiceInformation(); ExtensionsListType extensionsList = tspServiceInformation.getServiceInformationExtensions(); if (null == extensionsList) { extensionsList = this.objectFactory.createExtensionsListType(); tspServiceInformation.setServiceInformationExtensions(extensionsList); }/*www. j a v a 2 s. c om*/ List<ExtensionType> extensions = extensionsList.getExtension(); for (ExtensionType extension : extensions) { if (false == extension.isCritical()) { continue; } List<Object> extensionContent = extension.getContent(); for (Object extensionObject : extensionContent) { JAXBElement<?> extensionElement = (JAXBElement<?>) extensionObject; QName extensionName = extensionElement.getName(); LOG.debug("extension name: " + extensionName); if (qualifiersName.equals(extensionName)) { LOG.debug("extension found"); QualificationsType qualifications = (QualificationsType) extensionElement.getValue(); List<QualificationElementType> qualificationElements = qualifications.getQualificationElement(); for (QualificationElementType qualificationElement : qualificationElements) { QualifiersType qualifiers = qualificationElement.getQualifiers(); List<QualifierType> qualifierList = qualifiers.getQualifier(); for (QualifierType qualifier : qualifierList) { if (QC_FOR_LEGAL_PERSON_QUALIFIER_URI.equals(qualifier.getUri())) { CriteriaListType criteriaList = qualificationElement.getCriteriaList(); List<PoliciesListType> policySet = criteriaList.getPolicySet(); PoliciesListType policiesList = this.eccObjectFactory.createPoliciesListType(); policySet.add(policiesList); ObjectIdentifierType objectIdentifier = this.xadesObjectFactory .createObjectIdentifierType(); IdentifierType identifier = this.xadesObjectFactory.createIdentifierType(); identifier.setValue(oid); objectIdentifier.setIdentifier(identifier); policiesList.getPolicyIdentifier().add(objectIdentifier); return; } } } } } } ExtensionType extension = this.objectFactory.createExtensionType(); extension.setCritical(true); extensions.add(extension); QualificationsType qualifications = this.eccObjectFactory.createQualificationsType(); extension.getContent().add(this.eccObjectFactory.createQualifications(qualifications)); List<QualificationElementType> qualificationElements = qualifications.getQualificationElement(); QualificationElementType qualificationElement = this.eccObjectFactory.createQualificationElementType(); qualificationElements.add(qualificationElement); QualifiersType qualifiers = this.eccObjectFactory.createQualifiersType(); List<QualifierType> qualifierList = qualifiers.getQualifier(); QualifierType qcForLegalPersonqualifier = this.eccObjectFactory.createQualifierType(); qualifierList.add(qcForLegalPersonqualifier); qcForLegalPersonqualifier.setUri(QC_FOR_LEGAL_PERSON_QUALIFIER_URI); qualificationElement.setQualifiers(qualifiers); CriteriaListType criteriaList = this.eccObjectFactory.createCriteriaListType(); qualificationElement.setCriteriaList(criteriaList); criteriaList.setAssert("atLeastOne"); List<PoliciesListType> policySet = criteriaList.getPolicySet(); PoliciesListType policiesList = this.eccObjectFactory.createPoliciesListType(); policySet.add(policiesList); ObjectIdentifierType objectIdentifier = this.xadesObjectFactory.createObjectIdentifierType(); IdentifierType identifier = this.xadesObjectFactory.createIdentifierType(); identifier.setValue(oid); objectIdentifier.setIdentifier(identifier); policiesList.getPolicyIdentifier().add(objectIdentifier); /*if (noRoot == false) { AdditionalServiceInformationType additionalServiceInformation = this.objectFactory .createAdditionalServiceInformationType(); NonEmptyMultiLangURIType additionalServiceInformationUri = this.objectFactory .createNonEmptyMultiLangURIType(); additionalServiceInformationUri.setLang("en"); additionalServiceInformationUri .setValue("http://uri.etsi.org/TrstSvc/TrustedList/SvcInfoExt/RootCA-QC"); additionalServiceInformation .setURI(additionalServiceInformationUri); extension .getContent() .add(this.objectFactory .createAdditionalServiceInformation(additionalServiceInformation)); }*/ }
From source file:com.evolveum.midpoint.testing.wstest.AbstractWebserviceTest.java
protected void assertAttribute(ShadowType shadow, QName attrName, String attrVal) { ShadowAttributesType attributes = shadow.getAttributes(); for (Object any : attributes.getAny()) { if (any instanceof Element) { Element element = (Element) any; if (DOMUtil.getQName(element).equals(attrName)) { assertEquals("Wrong attribute " + attrName + " in shadow " + ModelClientUtil.toString(shadow), attrVal, element.getTextContent()); }//from w w w . j a va 2 s .c o m } else if (any instanceof JAXBElement<?>) { JAXBElement<?> jaxbElement = (JAXBElement<?>) any; if (jaxbElement.getName().equals(attrName)) { assertEquals("Wrong attribute " + attrName + " in shadow " + ModelClientUtil.toString(shadow), attrVal, jaxbElement.getValue().toString()); } } else { AssertJUnit.fail("Unexpected thing " + any + " in shadow attributes"); } } }
From source file:com.evolveum.midpoint.testing.wstest.AbstractWebserviceTest.java
protected void assertNoAttribute(ShadowType shadow, QName attrName) { ShadowAttributesType attributes = shadow.getAttributes(); for (Object any : attributes.getAny()) { if (any instanceof Element) { Element element = (Element) any; if (DOMUtil.getQName(element).equals(attrName)) { AssertJUnit.fail("Unexpected attribute " + attrName + " in shadow " + ModelClientUtil.toString(shadow) + ": " + element.getTextContent()); }//from w ww .ja v a 2 s .co m } else if (any instanceof JAXBElement<?>) { JAXBElement<?> jaxbElement = (JAXBElement<?>) any; if (jaxbElement.getName().equals(attrName)) { AssertJUnit.fail("Unexpected attribute " + attrName + " in shadow " + ModelClientUtil.toString(shadow) + ": " + jaxbElement.getValue()); } } else { AssertJUnit.fail("Unexpected thing " + any + " in shadow attributes"); } } }
From source file:be.e_contract.dssp.client.DigitalSignatureServiceClient.java
/** * Uploads a given document to the DSS in preparation of a signing ceremony. * //from www. j a v a 2s.c o m * @param mimetype * the mime-type of the document. * @param signatureType * the optional signature type. If none is provided, the DSS will * select the most appropriate. * @param data * the data bytes of the document. * @param useAttachments * set to <code>true</code> to use SOAP attachments. * @return a session object. Should be saved within the HTTP session for * later usage. * @throws UnsupportedDocumentTypeException * @throws UnsupportedSignatureTypeException * @throws IncorrectSignatureTypeException * @throws AuthenticationRequiredException */ public DigitalSignatureServiceSession uploadDocument(String mimetype, SignatureType signatureType, byte[] data, boolean useAttachments) throws UnsupportedDocumentTypeException, UnsupportedSignatureTypeException, IncorrectSignatureTypeException, AuthenticationRequiredException { SignRequest signRequest = this.objectFactory.createSignRequest(); signRequest.setProfile(DigitalSignatureServiceConstants.PROFILE); InputDocuments inputDocuments = this.objectFactory.createInputDocuments(); signRequest.setInputDocuments(inputDocuments); DocumentType document = addDocument(mimetype, data, useAttachments, inputDocuments); AnyType optionalInputs = this.objectFactory.createAnyType(); signRequest.setOptionalInputs(optionalInputs); optionalInputs.getAny().add( this.objectFactory.createAdditionalProfile(DigitalSignatureServiceConstants.DSS_ASYNC_PROFILE)); RequestSecurityTokenType requestSecurityToken = this.wstObjectFactory.createRequestSecurityTokenType(); optionalInputs.getAny().add(this.wstObjectFactory.createRequestSecurityToken(requestSecurityToken)); requestSecurityToken.getAny().add( this.wstObjectFactory.createTokenType(DigitalSignatureServiceConstants.WS_SEC_CONV_TOKEN_TYPE)); requestSecurityToken.getAny().add(this.wstObjectFactory .createRequestType(DigitalSignatureServiceConstants.WS_TRUST_ISSUE_REQUEST_TYPE)); EntropyType entropy = this.wstObjectFactory.createEntropyType(); BinarySecretType binarySecret = this.wstObjectFactory.createBinarySecretType(); binarySecret.setType(DigitalSignatureServiceConstants.WS_TRUST_BINARY_SECRET_NONCE_TYPE); byte[] nonce = new byte[256 / 8]; this.secureRandom.setSeed(System.currentTimeMillis()); this.secureRandom.nextBytes(nonce); binarySecret.setValue(nonce); entropy.getAny().add(this.wstObjectFactory.createBinarySecret(binarySecret)); requestSecurityToken.getAny().add(this.wstObjectFactory.createEntropy(entropy)); requestSecurityToken.getAny().add(this.wstObjectFactory.createKeySize(256L)); SignaturePlacement signaturePlacement = this.objectFactory.createSignaturePlacement(); optionalInputs.getAny().add(signaturePlacement); signaturePlacement.setCreateEnvelopedSignature(true); signaturePlacement.setWhichDocument(document); if (null != signatureType) { optionalInputs.getAny().add(this.objectFactory.createSignatureType(signatureType.getUri())); } String responseId = null; String securityTokenId = null; byte[] serverNonce = null; this.wsSecuritySOAPHandler.setCredentials(this.username, this.password); SignResponse signResponse = this.dssPort.sign(signRequest); Result result = signResponse.getResult(); String resultMajor = result.getResultMajor(); String resultMinor = result.getResultMinor(); if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(resultMajor)) { if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(resultMajor)) { if (DigitalSignatureServiceConstants.UNSUPPORTED_MIME_TYPE_RESULT_MINOR.equals(resultMinor)) { throw new UnsupportedDocumentTypeException(); } else if (DigitalSignatureServiceConstants.UNSUPPORTED_SIGNATURE_TYPE_RESULT_MINOR .equals(resultMinor)) { throw new UnsupportedSignatureTypeException(); } else if (DigitalSignatureServiceConstants.INCORRECT_SIGNATURE_TYPE_RESULT_MINOR .equals(resultMinor)) { throw new IncorrectSignatureTypeException(); } else if (DigitalSignatureServiceConstants.AUTHENTICATION_REQUIRED_RESULT_MINOR .equals(resultMinor)) { throw new AuthenticationRequiredException(); } } throw new RuntimeException("not successfull: " + resultMajor + " " + resultMinor); } AnyType optionalOutputs = signResponse.getOptionalOutputs(); List<Object> optionalOutputsList = optionalOutputs.getAny(); for (Object optionalOutputsObject : optionalOutputsList) { LOG.debug("optional outputs object type: " + optionalOutputsObject.getClass().getName()); if (optionalOutputsObject instanceof JAXBElement) { JAXBElement jaxbElement = (JAXBElement) optionalOutputsObject; QName name = jaxbElement.getName(); LOG.debug("value name: " + name); if (DigitalSignatureServiceConstants.ASYNC_RESPONSEID_QNAME.equals(name)) { responseId = (String) jaxbElement.getValue(); LOG.debug("async:ResponseID = " + responseId); } else if (jaxbElement.getValue() instanceof RequestSecurityTokenResponseCollectionType) { RequestSecurityTokenResponseCollectionType requestSecurityTokenResponseCollection = (RequestSecurityTokenResponseCollectionType) jaxbElement .getValue(); List<RequestSecurityTokenResponseType> rstsList = requestSecurityTokenResponseCollection .getRequestSecurityTokenResponse(); if (rstsList.size() == 1) { RequestSecurityTokenResponseType rstr = rstsList.get(0); for (Object rstrObject : rstr.getAny()) { JAXBElement rstrElement = (JAXBElement) rstrObject; if (rstrElement.getValue() instanceof RequestedSecurityTokenType) { RequestedSecurityTokenType requestedSecurityToken = (RequestedSecurityTokenType) rstrElement .getValue(); SecurityContextTokenType securityContextToken = ((JAXBElement<SecurityContextTokenType>) requestedSecurityToken .getAny()).getValue(); securityTokenId = ((JAXBElement<String>) securityContextToken.getAny().get(0)) .getValue(); LOG.debug("security token id: " + securityTokenId); } else if (rstrElement.getValue() instanceof EntropyType) { EntropyType serverEntropy = (EntropyType) rstrElement.getValue(); BinarySecretType serverBinarySecret = ((JAXBElement<BinarySecretType>) serverEntropy .getAny().get(0)).getValue(); serverNonce = serverBinarySecret.getValue(); } } } } } } if (null == responseId) { throw new RuntimeException("missing async:ResponseID in response"); } if (null == securityTokenId) { throw new RuntimeException("missing WS-SecureConversation token identifier"); } if (null == serverNonce) { throw new RuntimeException("missing Nonce in response"); } P_SHA1 p_SHA1 = new P_SHA1(); byte[] key; try { key = p_SHA1.createKey(nonce, serverNonce, 0, 256 / 8); } catch (ConversationException e) { throw new RuntimeException("error generating P_SHA1 key"); } Element securityTokenElement = this.wsTrustSOAPHandler.getRequestedSecurityToken(); DigitalSignatureServiceSession digitalSignatureServiceSession = new DigitalSignatureServiceSession( responseId, securityTokenId, key, securityTokenElement); return digitalSignatureServiceSession; }
From source file:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet.java
private X509Certificate getSignerCertificate(String citizenSignature) throws CertificateException, JAXBException, UnsupportedEncodingException { JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName()); SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller() .unmarshal(IOUtils.toInputStream(citizenSignature))).getValue(); // extract certificate for (Object current : root.getKeyInfo().getContent()) if (((JAXBElement<?>) current).getValue() instanceof X509DataType) { for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue() .getX509IssuerSerialOrX509SKIOrX509SubjectName()) { JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data); if (casted.getName().getLocalPart().equals("X509Certificate")) { return new X509Certificate(((String) casted.getValue()).getBytes("UTF-8")); }//from w ww . ja va2 s . co m } } return null; }
From source file:be.fedict.eid.dss.client.DigitalSignatureServiceClient.java
/** * Verifies whether the given document has been signed and reports back on * the signing parties./*w w w . j av a2 s. c o m*/ * * @param signedDocument * signed document to verify * @param mimeType * optional mime-type, default is "text/xml". * @param originalDocument * the optional original document. * @return a list of signature information objects detailing on the signing * parties. * @throws NotParseableXMLDocumentException * XML document was not parseable. */ public List<SignatureInfo> verifyWithSigners(byte[] signedDocument, String mimeType, byte[] originalDocument) throws NotParseableXMLDocumentException { ResponseBaseType responseBase = doVerification(signedDocument, mimeType, false, true, originalDocument); validateResult(responseBase); // parse VerificationReport List<SignatureInfo> signers = new LinkedList<SignatureInfo>(); VerificationReportType verificationReport = findVerificationReport(responseBase); if (null == verificationReport) { return signers; } List<IndividualReportType> individualReports = verificationReport.getIndividualReport(); for (IndividualReportType individualReport : individualReports) { if (!DSSConstants.RESULT_MAJOR_SUCCESS.equals(individualReport.getResult().getResultMajor())) { LOG.warn("some invalid VR result reported: " + individualReport.getResult().getResultMajor()); continue; } SignedObjectIdentifierType signedObjectIdentifier = individualReport.getSignedObjectIdentifier(); Date signingTime = signedObjectIdentifier.getSignedProperties().getSignedSignatureProperties() .getSigningTime().toGregorianCalendar().getTime(); List<Object> details = individualReport.getDetails().getAny(); X509Certificate signer = null; String role = null; for (Object detail : details) { if (detail instanceof JAXBElement<?>) { JAXBElement<?> detailElement = (JAXBElement<?>) detail; if (detailedSignatureReportQName.equals(detailElement.getName())) { DetailedSignatureReportType detailedSignatureReport = (DetailedSignatureReportType) detailElement .getValue(); List<CertificateValidityType> certificateValidities = detailedSignatureReport .getCertificatePathValidity().getPathValidityDetail().getCertificateValidity(); CertificateValidityType certificateValidity = certificateValidities.get(0); byte[] encodedSigner = certificateValidity.getCertificateValue(); try { signer = (X509Certificate) this.certificateFactory .generateCertificate(new ByteArrayInputStream(encodedSigner)); } catch (CertificateException e) { throw new RuntimeException("cert decoding error: " + e.getMessage(), e); } PropertiesType properties = detailedSignatureReport.getProperties(); if (null != properties) { SignerRoleType signerRole = properties.getSignedProperties() .getSignedSignatureProperties().getSignerRole(); if (null != signerRole) { role = (String) signerRole.getClaimedRoles().getClaimedRole().get(0).getContent() .get(0); } } } } } if (null == signer) { throw new RuntimeException("no signer certificate present in verification report"); } SignatureInfo signatureInfo = new SignatureInfo(signer, signingTime, role); signers.add(signatureInfo); } return signers; }
From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java
private void printExtension(ExtensionType extension, Document document) throws DocumentException { List<Object> contentList = extension.getContent(); for (Object content : contentList) { LOG.debug("extension content: " + content.getClass().getName()); if (content instanceof JAXBElement<?>) { JAXBElement<?> element = (JAXBElement<?>) content; LOG.debug("QName: " + element.getName()); if (true == ADDITIONAL_SERVICE_INFORMATION_QNAME.equals(element.getName())) { addTitle("Extension (critical: " + extension.isCritical() + ")", title3Font, Paragraph.ALIGN_LEFT, 0, 0, document); addTitle("Additional service information", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document); AdditionalServiceInformationType additionalServiceInformation = (AdditionalServiceInformationType) element .getValue();// w ww .j a v a 2 s. c o m LOG.debug("information value: " + additionalServiceInformation.getInformationValue()); NonEmptyMultiLangURIType multiLangUri = additionalServiceInformation.getURI(); LOG.debug("URI : " + multiLangUri.getValue() + " (language: " + multiLangUri.getLang() + ")"); document.add(new Paragraph( multiLangUri.getValue().substring( multiLangUri.getValue().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()), this.valueFont)); } else { addTitle("Extension (critical: " + extension.isCritical() + ")", title3Font, Paragraph.ALIGN_LEFT, 0, 0, document); addTitle("Qualifications", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document); LOG.debug("element namespace: " + element.getName()); LOG.debug("element name: " + element.getScope()); if ("http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#" .equals(element.getName().getNamespaceURI()) && "Qualifications".equals(element.getName().getLocalPart())) { QualificationsType qualifications = (QualificationsType) element.getValue(); List<QualificationElementType> qualificationElements = qualifications .getQualificationElement(); for (QualificationElementType qualificationElement : qualificationElements) { QualifiersType qualifiers = qualificationElement.getQualifiers(); List<QualifierType> qualifierList = qualifiers.getQualifier(); for (QualifierType qualifier : qualifierList) { document.add(new Paragraph( "Qualifier: " + qualifier.getUri().substring( qualifier.getUri().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()), this.valueFont)); } CriteriaListType criteriaList = qualificationElement.getCriteriaList(); String description = criteriaList.getDescription(); if (null != description) { document.add(new Paragraph("Criterial List Description", this.labelFont)); document.add(new Paragraph(description, this.valueFont)); } document.add(new Paragraph("Assert: " + criteriaList.getAssert(), this.valueFont)); List<PoliciesListType> policySet = criteriaList.getPolicySet(); for (PoliciesListType policiesList : policySet) { List<ObjectIdentifierType> oids = policiesList.getPolicyIdentifier(); for (ObjectIdentifierType oid : oids) { document.add(new Paragraph("Policy OID: " + oid.getIdentifier().getValue(), this.valueFont)); } } } } } } else if (content instanceof Element) { addTitle("Qualifications", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document); Element element = (Element) content; LOG.debug("element namespace: " + element.getNamespaceURI()); LOG.debug("element name: " + element.getLocalName()); if ("http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#" .equals(element.getNamespaceURI()) && "Qualifications".equals(element.getLocalName())) { try { QualificationsType qualifications = unmarshallQualifications(element); List<QualificationElementType> qualificationElements = qualifications .getQualificationElement(); for (QualificationElementType qualificationElement : qualificationElements) { QualifiersType qualifiers = qualificationElement.getQualifiers(); List<QualifierType> qualifierList = qualifiers.getQualifier(); for (QualifierType qualifier : qualifierList) { document.add(new Paragraph( "Qualifier: " + qualifier.getUri().substring( qualifier.getUri().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()), this.valueFont)); } CriteriaListType criteriaList = qualificationElement.getCriteriaList(); String description = criteriaList.getDescription(); if (null != description) { document.add(new Paragraph("Criterial List Description", this.labelFont)); document.add(new Paragraph(description, this.valueFont)); } document.add(new Paragraph("Assert: " + criteriaList.getAssert(), this.valueFont)); List<PoliciesListType> policySet = criteriaList.getPolicySet(); for (PoliciesListType policiesList : policySet) { List<ObjectIdentifierType> oids = policiesList.getPolicyIdentifier(); for (ObjectIdentifierType oid : oids) { document.add(new Paragraph("Policy OID: " + oid.getIdentifier().getValue(), this.valueFont)); } } } } catch (JAXBException e) { LOG.error("JAXB error: " + e.getMessage(), e); } } } } }
From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java
public <T> Element marshalElementToDom(JAXBElement<T> jaxbElement, Document doc) throws JAXBException { if (doc == null) { doc = DOMUtil.getDocument();// ww w .ja v a 2 s.c o m } Element element = doc.createElementNS(jaxbElement.getName().getNamespaceURI(), jaxbElement.getName().getLocalPart()); marshalElementToDom(jaxbElement, element); return (Element) element.getFirstChild(); }
From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java
/** * This method will update the passed in vApp network by adding an additional * NetworkConfigSection that uses the command line options.networkName. It makes a PUT call * to the edit link of the NetworkConfigSection section of the vApp passed in. The * passed in VdcType is used to look up the parent network which is required for the update * process of the vApp NetworkConfigSection. * /*from w w w . j a v a2s. c o m*/ * NOTE: This step, updating the vApp network section, must be done BEFORE any of the vApp's * children Vm's network sections are updated. * * @param vApp the vApp instance to update network configuration for * @param vdc the VDC this vApp is deployed to * @return a TaskType instance if successful, otherwise an exception is thrown */ private TaskType updateVAppNetwork(VAppType vApp, VdcType vdc) { List<JAXBElement<? extends SectionType>> sections = vApp.getSection(); for (JAXBElement<? extends SectionType> section : sections) { if (section.getName().toString().contains("NetworkConfigSection")) { NetworkConfigSectionType ncst = (NetworkConfigSectionType) section.getValue(); // Find the EDIT link to make a PUT call to to update the network config info List<LinkType> links = ncst.getLink(); String editHref = null; for (LinkType link : links) { if (link.getRel().equalsIgnoreCase("edit")) { editHref = link.getHref(); break; } } if (null != editHref) { VAppNetworkConfigurationType vappNet = new VAppNetworkConfigurationType(); // Use the network name passed on the command line, the same name that will // be applied to each vApp Vm child network configuration so they match vappNet.setNetworkName(options.networkName); // Newly constructed network configuration NetworkConfigurationType networkConfiguration = new NetworkConfigurationType(); ReferenceType networkReference = new ReferenceType(); // Get the parent network that the VDC refers to networkReference.setHref(getParentNetworkHrefFromVdc(vdc)); networkConfiguration.setParentNetwork(networkReference); // hard coded.. 'bridged', 'natRouted' or 'isolated' networkConfiguration.setFenceMode("bridged"); vappNet.setConfiguration(networkConfiguration); // Add the newly configured network to the existing vApp configuration ncst.getNetworkConfig().add(vappNet); // Make the PUT call to update the vApp network configuration HttpPut updateVAppNetwork = vcd.put(editHref, options); OutputStream os = null; ObjectFactory objectFactory = new ObjectFactory(); JAXBElement<NetworkConfigSectionType> networkConfigSectionType = objectFactory .createNetworkConfigSection(ncst); JAXBContext jaxbContexts = null; try { jaxbContexts = JAXBContext.newInstance(NetworkConfigSectionType.class); } catch (JAXBException ex) { throw new RuntimeException("Problem creating JAXB Context: ", ex); } try { javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); os = new ByteArrayOutputStream(); // Marshal the object via JAXB to XML marshaller.marshal(networkConfigSectionType, os); } catch (JAXBException e) { throw new RuntimeException("Problem marshalling VirtualHardwareSection", e); } // Set the Content-Type header for NetworkConfigSection ContentType contentType = ContentType .create("application/vnd.vmware.vcloud.networkConfigSection+xml", "ISO-8859-1"); StringEntity update = new StringEntity(os.toString(), contentType); updateVAppNetwork.setEntity(update); // Invoke the HttoPut to update the VirtualHardwareSection of the Vm HttpResponse response = HttpUtils.httpInvoke(updateVAppNetwork); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class); return taskType; } } } } throw new RuntimeException("Problem trying to update vApp " + vApp.getName() + " network config section with " + options.networkName + " as the network name"); }
From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java
/** * This will use the passed in vm to find the VirtualHardwareSection and modify it to attach * the Vm network to the vApp network the Vm is a child of. The first step is to search the * Vm section types for VirtualHardwareSection. If found, look in the attributes of the section * to find the VirtualHardwareSection Href value. The VirtualHardwareSection found in the Vm * has a number of extra LinkType links that can not be part of the request body when the PUT * call to update the network settings is made. Therefore, the Href is used to first GET the * VirtualHardwareSection again which responds without the links so it can be used to PUT back * to the same Href to update the Vm network settings. With the newly acquired * VirtualHardwareSection, a search through the items is done to find the network item. This * is denoted by a resource type value of "10". If found the command line options.networkName * is set as the value of the connection, and the value POOL is assigned to the ipAddressingMode * attribute. With those values set, the updated VirtualHardwareSection is then sent via a PUT * request to change the Vm network settings. * //from w w w . j a va 2s . co m * @param vm the Vm to change network settings on */ private TaskType updateVMWithNetworkDetails(VmType vm) { // the Href to use for GET and PUT calls for the VirtualHardwareSection String hardwareHref = null; // With the VDC network details, we can now update the Vm network section to connect the Vm to the vApp network for (JAXBElement<? extends SectionType> st : vm.getSection()) { if (st.getName().toString().contains("VirtualHardwareSection")) { VirtualHardwareSectionType hardware = (VirtualHardwareSectionType) st.getValue(); // Try to find the Href attribute which is used for GET and PUT Map<QName, String> map = hardware.getOtherAttributes(); Set<QName> keys = map.keySet(); for (QName key : keys) { if (key.toString().endsWith("href")) { hardwareHref = map.get(key); break; } } // Make sure VirtualHardwareSection href was found. This is used for the GET below // and PUT to later update the network settings of the Vm. if (null != hardwareHref) { // It's necessary to GET the VirtualHardwareSection again because the current // hardware variables from the Vm contains links that can not be sent as part // of the PUT body. This GET call will only get the details without the links // that the Vm section provides. HttpResponse response = HttpUtils.httpInvoke(vcd.get(hardwareHref, options)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { hardware = HttpUtils.unmarshal(response.getEntity(), VirtualHardwareSectionType.class); // Find the RASDType that has a ResourceType of 10, which indicates the // VMs network info for (RASDType rasType : hardware.getItem()) { if (rasType.getResourceType().getValue().equals("10")) { CimBoolean c = new CimBoolean(); c.setValue(true); rasType.setAutomaticAllocation(c); // Get the first CimString CimString cs = rasType.getConnection().get(0); // Set the network name cs.setValue(options.networkName); // Look in the list of attributes for the ip addressing mode map = cs.getOtherAttributes(); keys = map.keySet(); for (QName key : keys) { if (key.toString().endsWith("ipAddressingMode")) { // Set it to POOL map.put(key, "POOL"); break; } } break; } } } // Now do a PUT with update data com.vmware.vcloud.api.rest.schema.ovf.ObjectFactory objectFactory = new com.vmware.vcloud.api.rest.schema.ovf.ObjectFactory(); JAXBElement<VirtualHardwareSectionType> hardwareSection = objectFactory .createVirtualHardwareSection(hardware); JAXBContext jaxbContexts = null; try { jaxbContexts = JAXBContext.newInstance(VirtualHardwareSectionType.class); } catch (JAXBException ex) { throw new RuntimeException("Problem creating JAXB Context: ", ex); } // Create HttpPut request to update the VirtualHardwareSection HttpPut updateVmNetwork = vcd.put(hardwareHref, options); OutputStream os = null; try { javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); os = new ByteArrayOutputStream(); // Marshal the object via JAXB to XML marshaller.marshal(hardwareSection, os); } catch (JAXBException e) { throw new RuntimeException("Problem marshalling VirtualHardwareSection", e); } // Set the Content-Type header for VirtualHardwareSection ContentType contentType = ContentType .create("application/vnd.vmware.vcloud.virtualHardwareSection+xml", "ISO-8859-1"); StringEntity update = new StringEntity(os.toString(), contentType); updateVmNetwork.setEntity(update); // Invoke the HttoPut to update the VirtualHardwareSection of the Vm response = HttpUtils.httpInvoke(updateVmNetwork); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { // Update was good, return the TaskType TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class); return taskType; } break; } } } throw new RuntimeException("Could not update Vm VirtualHardwareSection"); }