List of usage examples for org.w3c.dom Element setAttributeNode
public Attr setAttributeNode(Attr newAttr) throws DOMException;
From source file:com.twinsoft.convertigo.beans.core.Sequence.java
private static void append(Element parent, Node node) { if (parent != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { parent.appendChild(node);//from w w w .j av a 2 s. com } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) { parent.setAttributeNode((Attr) node); } } }
From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java
/** * Convert the result set into an XML structure. * * @param items// w w w . jav a 2s.c om * @param withHistory * @param locale * @param personBean * @param filterName * @param filterExpression * @param useProjectSpecificID * @param outfileName * @return */ public Document convertToDOM(List<ReportBean> items, boolean withHistory, Locale locale, TPersonBean personBean, String filterName, String filterExpression, boolean useProjectSpecificID, String outfileName) { Document doc = null; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements doc = docBuilder.newDocument(); Element rootElement = doc.createElement("pdfFile"); doc.appendChild(rootElement); // set attribute to staff element Attr attr = doc.createAttribute("file"); outfileName = outfileName.replace(".tex", ".pdf"); attr.setValue(latexTmpDir + File.separator + outfileName); rootElement.setAttributeNode(attr); } catch (FactoryConfigurationError e) { LOGGER.error("Creating the DOM document failed with FactoryConfigurationError:" + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } catch (ParserConfigurationException e) { LOGGER.error("Creating the DOM document failed with ParserConfigurationException: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } return doc; }
From source file:org.shareok.data.sagedata.SageJournalDataProcessorAbstract.java
@Override /** //from w w w . ja va 2 s.c o m * Convert the article data to dublin core xml metadata and save the the file * * @param String fileName : the root folder contains all the uploading article data */ public void exportXmlByJournalData(String fileName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dublin_core"); doc.appendChild(rootElement); // Add the type node: Element element = doc.createElement("dcvalue"); element.appendChild(doc.createTextNode("Research Article")); rootElement.appendChild(element); Attr attr = doc.createAttribute("element"); attr.setValue("type"); element.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); element.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); element.setAttributeNode(attr); // Add the abstract node: String abs = journalData.getAbstractText(); if (null != abs) { Element elementAbs = doc.createElement("dcvalue"); elementAbs.appendChild(doc.createTextNode(abs)); rootElement.appendChild(elementAbs); attr = doc.createAttribute("element"); attr.setValue("description"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("abstract"); elementAbs.setAttributeNode(attr); } // Add the language node: String lang = journalData.getLanguage(); if (null != lang) { Element elementLang = doc.createElement("dcvalue"); elementLang.appendChild(doc.createTextNode(lang)); rootElement.appendChild(elementLang); attr = doc.createAttribute("element"); attr.setValue("language"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("iso"); elementLang.setAttributeNode(attr); } // Add the title node: String tit = journalData.getTitle(); if (null != tit) { Element elementTitle = doc.createElement("dcvalue"); elementTitle.appendChild(doc.createTextNode(tit)); rootElement.appendChild(elementTitle); attr = doc.createAttribute("element"); attr.setValue("title"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementTitle.setAttributeNode(attr); } // Add the available date node: // Element elementAvailable = doc.createElement("dcvalue"); // elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString())); // rootElement.appendChild(elementAvailable); // // attr = doc.createAttribute("element"); // attr.setValue("date"); // elementAvailable.setAttributeNode(attr); // // attr = doc.createAttribute("qualifier"); // attr.setValue("available"); // elementAvailable.setAttributeNode(attr); // Add the issued date node: Date issueDate = journalData.getDateIssued(); if (null != issueDate) { SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd"); Element elementIssued = doc.createElement("dcvalue"); elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate))); rootElement.appendChild(elementIssued); attr = doc.createAttribute("element"); attr.setValue("date"); elementIssued.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("issued"); elementIssued.setAttributeNode(attr); } // Add the author nodes: String[] authorSet = journalData.getAuthors(); if (null != authorSet && authorSet.length > 0) { for (String author : authorSet) { Element elementAuthor = doc.createElement("dcvalue"); elementAuthor.appendChild(doc.createTextNode(author)); rootElement.appendChild(elementAuthor); attr = doc.createAttribute("element"); attr.setValue("contributor"); elementAuthor.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("author"); elementAuthor.setAttributeNode(attr); } } // Add the acknowledgements node: String ack = journalData.getAcknowledgements(); if (null != ack) { Element elementAck = doc.createElement("dcvalue"); elementAck.appendChild(doc.createTextNode(ack)); rootElement.appendChild(elementAck); attr = doc.createAttribute("element"); attr.setValue("description"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementAck.setAttributeNode(attr); } // Add the author contributions node: String contrib = journalData.getAuthorContributions(); if (null != contrib) { Element elementContribution = doc.createElement("dcvalue"); elementContribution.appendChild(doc.createTextNode(contrib)); rootElement.appendChild(elementContribution); attr = doc.createAttribute("element"); attr.setValue("description"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementContribution.setAttributeNode(attr); } // Add the publisher node: String puber = journalData.getPublisher(); if (null != puber) { Element elementPublisher = doc.createElement("dcvalue"); elementPublisher.appendChild(doc.createTextNode(puber)); rootElement.appendChild(elementPublisher); attr = doc.createAttribute("element"); attr.setValue("publisher"); elementPublisher.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementPublisher.setAttributeNode(attr); } // Add the citation node: String cit = journalData.getCitation(); if (null != cit) { Element elementCitation = doc.createElement("dcvalue"); elementCitation.appendChild(doc.createTextNode(cit)); rootElement.appendChild(elementCitation); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("citation"); elementCitation.setAttributeNode(attr); } // Add the rights node: String rit = journalData.getRights(); if (null != rit) { Element elementRights = doc.createElement("dcvalue"); elementRights.appendChild(doc.createTextNode(rit)); rootElement.appendChild(elementRights); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRights.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementRights.setAttributeNode(attr); } // Add the rights URI node: String ritUri = journalData.getRightsUri(); if (null != ritUri) { Element elementRightsUri = doc.createElement("dcvalue"); elementRightsUri.appendChild(doc.createTextNode(ritUri)); rootElement.appendChild(elementRightsUri); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRightsUri.setAttributeNode(attr); } // Add the rights requestable node: Element elementRightsRequestable = doc.createElement("dcvalue"); elementRightsRequestable .appendChild(doc.createTextNode(Boolean.toString(journalData.isRightsRequestable()))); rootElement.appendChild(elementRightsRequestable); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("requestable"); elementRightsRequestable.setAttributeNode(attr); // Add the is part of node: String partOf = journalData.getIsPartOfSeries(); if (null != partOf) { Element elementIsPartOf = doc.createElement("dcvalue"); elementIsPartOf.appendChild(doc.createTextNode(partOf)); rootElement.appendChild(elementIsPartOf); attr = doc.createAttribute("element"); attr.setValue("relation"); elementIsPartOf.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("ispartofseries"); elementIsPartOf.setAttributeNode(attr); } // Add the relation uri node: String reUri = journalData.getRelationUri(); if (null != reUri) { Element elementRelationUri = doc.createElement("dcvalue"); elementRelationUri.appendChild(doc.createTextNode(reUri)); rootElement.appendChild(elementRelationUri); attr = doc.createAttribute("element"); attr.setValue("relation"); elementRelationUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRelationUri.setAttributeNode(attr); } // Add the subject nodes: String[] subjectSet = journalData.getSubjects(); if (null != subjectSet && subjectSet.length > 0) { for (String subject : subjectSet) { Element elementSubject = doc.createElement("dcvalue"); elementSubject.appendChild(doc.createTextNode(subject)); rootElement.appendChild(elementSubject); attr = doc.createAttribute("element"); attr.setValue("subject"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementSubject.setAttributeNode(attr); } } // Add the peerReview node: String review = journalData.getPeerReview(); if (null != review) { Element elementPeerReview = doc.createElement("dcvalue"); elementPeerReview.appendChild(doc.createTextNode(review)); rootElement.appendChild(elementPeerReview); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreview"); elementPeerReview.setAttributeNode(attr); } // Add the peer review notes node: String peer = journalData.getPeerReviewNotes(); if (null != peer) { Element elementPeerReviewNotes = doc.createElement("dcvalue"); elementPeerReviewNotes.appendChild(doc.createTextNode(peer)); rootElement.appendChild(elementPeerReviewNotes); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreviewnotes"); elementPeerReviewNotes.setAttributeNode(attr); } // Add the doi node: String doi = journalData.getDoi(); if (null != doi) { Element elementDoi = doc.createElement("dcvalue"); elementDoi.appendChild(doc.createTextNode(doi)); rootElement.appendChild(elementDoi); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("doi"); elementDoi.setAttributeNode(attr); } String folderPath = setOutputPath(fileName); String filePath = folderPath + "/dublin_core.xml"; TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException pce) { pce.printStackTrace(); } catch (DOMException | BeansException e) { e.printStackTrace(); } }
From source file:org.shareok.data.plosdata.PlosData.java
/** * Generate the metadata xml file/*from ww w . ja va 2s . c om*/ * @param fileName */ public void exportXmlByDoiData(String fileName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dublin_core"); doc.appendChild(rootElement); // Add the type node: Element element = doc.createElement("dcvalue"); element.appendChild(doc.createTextNode("Research Article")); rootElement.appendChild(element); Attr attr = doc.createAttribute("element"); attr.setValue("type"); element.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); element.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); element.setAttributeNode(attr); // Add the abstract node: String abs = getAbstractText(); if (null != abs) { Element elementAbs = doc.createElement("dcvalue"); elementAbs.appendChild(doc.createTextNode(abs)); rootElement.appendChild(elementAbs); attr = doc.createAttribute("element"); attr.setValue("description"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("abstract"); elementAbs.setAttributeNode(attr); } // Add the language node: String lang = getLanguage(); if (null != lang) { Element elementLang = doc.createElement("dcvalue"); elementLang.appendChild(doc.createTextNode(lang)); rootElement.appendChild(elementLang); attr = doc.createAttribute("element"); attr.setValue("language"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("iso"); elementLang.setAttributeNode(attr); } // Add the title node: String tit = getTitle(); if (null != tit) { Element elementTitle = doc.createElement("dcvalue"); elementTitle.appendChild(doc.createTextNode(tit)); rootElement.appendChild(elementTitle); attr = doc.createAttribute("element"); attr.setValue("title"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementTitle.setAttributeNode(attr); } // Add the available date node: // Element elementAvailable = doc.createElement("dcvalue"); // elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString())); // rootElement.appendChild(elementAvailable); // // attr = doc.createAttribute("element"); // attr.setValue("date"); // elementAvailable.setAttributeNode(attr); // // attr = doc.createAttribute("qualifier"); // attr.setValue("available"); // elementAvailable.setAttributeNode(attr); // Add the issued date node: Date issueDate = getDateIssued(); if (null != issueDate) { SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd"); Element elementIssued = doc.createElement("dcvalue"); elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate))); rootElement.appendChild(elementIssued); attr = doc.createAttribute("element"); attr.setValue("date"); elementIssued.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("issued"); elementIssued.setAttributeNode(attr); } // Add the author nodes: String[] authorSet = getAuthors(); if (null != authorSet && authorSet.length > 0) { for (String author : authorSet) { Element elementAuthor = doc.createElement("dcvalue"); elementAuthor.appendChild(doc.createTextNode(author)); rootElement.appendChild(elementAuthor); attr = doc.createAttribute("element"); attr.setValue("contributor"); elementAuthor.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("author"); elementAuthor.setAttributeNode(attr); } } // Add the acknowledgements node: String ack = getAcknowledgements(); if (null != ack) { Element elementAck = doc.createElement("dcvalue"); elementAck.appendChild(doc.createTextNode(ack)); rootElement.appendChild(elementAck); attr = doc.createAttribute("element"); attr.setValue("description"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementAck.setAttributeNode(attr); } // Add the author contributions node: String contrib = getAuthorContributions(); if (null != contrib) { Element elementContribution = doc.createElement("dcvalue"); elementContribution.appendChild(doc.createTextNode(contrib)); rootElement.appendChild(elementContribution); attr = doc.createAttribute("element"); attr.setValue("description"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementContribution.setAttributeNode(attr); } // Add the publisher node: String puber = getPublisher(); if (null != puber) { Element elementPublisher = doc.createElement("dcvalue"); elementPublisher.appendChild(doc.createTextNode(puber)); rootElement.appendChild(elementPublisher); attr = doc.createAttribute("element"); attr.setValue("publisher"); elementPublisher.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementPublisher.setAttributeNode(attr); } // Add the citation node: String cit = getCitation(); if (null != cit) { Element elementCitation = doc.createElement("dcvalue"); elementCitation.appendChild(doc.createTextNode(cit)); rootElement.appendChild(elementCitation); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("citation"); elementCitation.setAttributeNode(attr); } // Add the rights node: String rit = getRights(); if (null != rit) { Element elementRights = doc.createElement("dcvalue"); elementRights.appendChild(doc.createTextNode(rit)); rootElement.appendChild(elementRights); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRights.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementRights.setAttributeNode(attr); } // Add the rights URI node: String ritUri = getRightsUri(); if (null != ritUri) { Element elementRightsUri = doc.createElement("dcvalue"); elementRightsUri.appendChild(doc.createTextNode(ritUri)); rootElement.appendChild(elementRightsUri); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRightsUri.setAttributeNode(attr); } // Add the rights requestable node: Element elementRightsRequestable = doc.createElement("dcvalue"); elementRightsRequestable.appendChild(doc.createTextNode(Boolean.toString(isRightsRequestable()))); rootElement.appendChild(elementRightsRequestable); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("requestable"); elementRightsRequestable.setAttributeNode(attr); // Add the is part of node: String partOf = getIsPartOfSeries(); if (null != partOf) { Element elementIsPartOf = doc.createElement("dcvalue"); elementIsPartOf.appendChild(doc.createTextNode(partOf)); rootElement.appendChild(elementIsPartOf); attr = doc.createAttribute("element"); attr.setValue("relation"); elementIsPartOf.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("ispartofseries"); elementIsPartOf.setAttributeNode(attr); } // Add the relation uri node: String reUri = getRelationUri(); if (null != reUri) { Element elementRelationUri = doc.createElement("dcvalue"); elementRelationUri.appendChild(doc.createTextNode(reUri)); rootElement.appendChild(elementRelationUri); attr = doc.createAttribute("element"); attr.setValue("relation"); elementRelationUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRelationUri.setAttributeNode(attr); } // Add the subject nodes: String[] subjectSet = getSubjects(); if (null != subjectSet && subjectSet.length > 0) { for (String subject : subjectSet) { Element elementSubject = doc.createElement("dcvalue"); elementSubject.appendChild(doc.createTextNode(subject)); rootElement.appendChild(elementSubject); attr = doc.createAttribute("element"); attr.setValue("subject"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementSubject.setAttributeNode(attr); } } // Add the peerReview node: String review = getPeerReview(); if (null != review) { Element elementPeerReview = doc.createElement("dcvalue"); elementPeerReview.appendChild(doc.createTextNode(review)); rootElement.appendChild(elementPeerReview); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreview"); elementPeerReview.setAttributeNode(attr); } // Add the peer review notes node: String peer = getPeerReviewNotes(); if (null != peer) { Element elementPeerReviewNotes = doc.createElement("dcvalue"); elementPeerReviewNotes.appendChild(doc.createTextNode(peer)); rootElement.appendChild(elementPeerReviewNotes); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreviewnotes"); elementPeerReviewNotes.setAttributeNode(attr); } // Add the doi node: String doi = getDoi(); if (null != doi) { Element elementDoi = doc.createElement("dcvalue"); elementDoi.appendChild(doc.createTextNode(doi)); rootElement.appendChild(elementDoi); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("doi"); elementDoi.setAttributeNode(attr); } // Generate the xml file: TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(fileName)); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException pce) { pce.printStackTrace(); System.exit(0); } catch (DOMException | BeansException e) { e.printStackTrace(); System.exit(0); } }
From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java
private void modifyAccessElementAttributes(Document emlDocument) throws TransformerException { CachedXPathAPI xpathapi = new CachedXPathAPI(); // Parse the access elements NodeList accessNodeList = xpathapi.selectNodeList(emlDocument, ACCESS_PATH); if (accessNodeList != null) { for (int i = 0; i < accessNodeList.getLength(); i++) { boolean hasSystemAttribute = false; Element accessElement = (Element) accessNodeList.item(i); NamedNodeMap accessAttributesList = accessElement.getAttributes(); for (int j = 0; j < accessAttributesList.getLength(); j++) { Node attributeNode = accessAttributesList.item(j); String nodeName = attributeNode.getNodeName(); String nodeValue = attributeNode.getNodeValue(); if (nodeName.equals("authSystem")) { attributeNode.setNodeValue(LEVEL_ONE_AUTH_SYSTEM_ATTRIBUTE); } else if (nodeName.equals("system")) { attributeNode.setNodeValue(LEVEL_ONE_SYSTEM_ATTRIBUTE); hasSystemAttribute = true; }//from w ww . j a va 2 s. com } /* * No @system attribute was found in the access element, so we * need to add one. */ if (!hasSystemAttribute) { Attr systemAttribute = emlDocument.createAttribute("system"); systemAttribute.setTextContent(LEVEL_ONE_SYSTEM_ATTRIBUTE); accessElement.setAttributeNode(systemAttribute); } } } }
From source file:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java
/** * Exports an Azure SQL Database into a DACPAC file in Azure Blob Storage. * * @param serverName Required. The name of the Azure SQL Database Server in * which the database to export resides./* ww w . jav a 2 s . c o m*/ * @param parameters Optional. The parameters needed to initiate the export * request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Represents the response that the service returns once an import * or export operation has been initiated. */ @Override public DacImportExportResponse export(String serverName, DacExportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (parameters != null) { if (parameters.getBlobCredentials() != null) { if (parameters.getBlobCredentials().getStorageAccessKey() == null) { throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey"); } if (parameters.getBlobCredentials().getUri() == null) { throw new NullPointerException("parameters.BlobCredentials.Uri"); } } if (parameters.getConnectionInfo() != null) { if (parameters.getConnectionInfo().getDatabaseName() == null) { throw new NullPointerException("parameters.ConnectionInfo.DatabaseName"); } if (parameters.getConnectionInfo().getPassword() == null) { throw new NullPointerException("parameters.ConnectionInfo.Password"); } if (parameters.getConnectionInfo().getServerName() == null) { throw new NullPointerException("parameters.ConnectionInfo.ServerName"); } if (parameters.getConnectionInfo().getUserName() == null) { throw new NullPointerException("parameters.ConnectionInfo.UserName"); } } } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "exportAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/DacOperations/Export"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); if (parameters != null) { Element exportInputElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ExportInput"); requestDoc.appendChild(exportInputElement); if (parameters.getBlobCredentials() != null) { Element blobCredentialsElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobCredentials"); exportInputElement.appendChild(blobCredentialsElement); Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); typeAttribute.setValue("BlobStorageAccessKeyCredentials"); blobCredentialsElement.setAttributeNode(typeAttribute); Element uriElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Uri"); uriElement.appendChild( requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString())); blobCredentialsElement.appendChild(uriElement); Element storageAccessKeyElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StorageAccessKey"); storageAccessKeyElement.appendChild( requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey())); blobCredentialsElement.appendChild(storageAccessKeyElement); } if (parameters.getConnectionInfo() != null) { Element connectionInfoElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ConnectionInfo"); exportInputElement.appendChild(connectionInfoElement); Element databaseNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); databaseNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName())); connectionInfoElement.appendChild(databaseNameElement); Element passwordElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Password"); passwordElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword())); connectionInfoElement.appendChild(passwordElement); Element serverNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); serverNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName())); connectionInfoElement.appendChild(serverNameElement); Element userNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "UserName"); userNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName())); connectionInfoElement.appendChild(userNameElement); } } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DacImportExportResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DacImportExportResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "guid"); if (guidElement != null) { result.setGuid(guidElement.getTextContent()); } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java
/** * Initiates an Import of a DACPAC file from Azure Blob Storage into a Azure * SQL Database.// www. j a va 2 s . c om * * @param serverName Required. The name of the Azure SQL Database Server * into which the database is being imported. * @param parameters Optional. The parameters needed to initiated the Import * request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Represents the response that the service returns once an import * or export operation has been initiated. */ @Override public DacImportExportResponse importMethod(String serverName, DacImportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (parameters != null) { if (parameters.getBlobCredentials() != null) { if (parameters.getBlobCredentials().getStorageAccessKey() == null) { throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey"); } if (parameters.getBlobCredentials().getUri() == null) { throw new NullPointerException("parameters.BlobCredentials.Uri"); } } if (parameters.getConnectionInfo() != null) { if (parameters.getConnectionInfo().getDatabaseName() == null) { throw new NullPointerException("parameters.ConnectionInfo.DatabaseName"); } if (parameters.getConnectionInfo().getPassword() == null) { throw new NullPointerException("parameters.ConnectionInfo.Password"); } if (parameters.getConnectionInfo().getServerName() == null) { throw new NullPointerException("parameters.ConnectionInfo.ServerName"); } if (parameters.getConnectionInfo().getUserName() == null) { throw new NullPointerException("parameters.ConnectionInfo.UserName"); } } } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "importMethodAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/DacOperations/Import"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); if (parameters != null) { Element importInputElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ImportInput"); requestDoc.appendChild(importInputElement); if (parameters.getAzureEdition() != null) { Element azureEditionElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "AzureEdition"); azureEditionElement.appendChild(requestDoc.createTextNode(parameters.getAzureEdition())); importInputElement.appendChild(azureEditionElement); } if (parameters.getBlobCredentials() != null) { Element blobCredentialsElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobCredentials"); importInputElement.appendChild(blobCredentialsElement); Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); typeAttribute.setValue("BlobStorageAccessKeyCredentials"); blobCredentialsElement.setAttributeNode(typeAttribute); Element uriElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Uri"); uriElement.appendChild( requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString())); blobCredentialsElement.appendChild(uriElement); Element storageAccessKeyElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StorageAccessKey"); storageAccessKeyElement.appendChild( requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey())); blobCredentialsElement.appendChild(storageAccessKeyElement); } if (parameters.getConnectionInfo() != null) { Element connectionInfoElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ConnectionInfo"); importInputElement.appendChild(connectionInfoElement); Element databaseNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); databaseNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName())); connectionInfoElement.appendChild(databaseNameElement); Element passwordElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Password"); passwordElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword())); connectionInfoElement.appendChild(passwordElement); Element serverNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); serverNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName())); connectionInfoElement.appendChild(serverNameElement); Element userNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "UserName"); userNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName())); connectionInfoElement.appendChild(userNameElement); } Element databaseSizeInGBElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseSizeInGB"); databaseSizeInGBElement .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getDatabaseSizeInGB()))); importInputElement.appendChild(databaseSizeInGBElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DacImportExportResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DacImportExportResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "guid"); if (guidElement != null) { result.setGuid(guidElement.getTextContent()); } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java
protected void addAttr(Document doc, Element element, String name, String value) { if (value == null) return;/* w w w .j a v a2 s . co m*/ Attr attr = doc.createAttribute(name); attr.setValue(value); element.setAttributeNode(attr); }
From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java
/** * The Update Storage Account operation updates the label and the * description, and enables or disables the geo-replication status for a * storage account in Azure. (see/*from w ww . ja v a2s .c o m*/ * http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for * more information) * * @param accountName Required. Name of the storage account to update. * @param parameters Required. Parameters supplied to the Update Storage * Account operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse update(String accountName, StorageAccountUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (accountName == null) { throw new NullPointerException("accountName"); } if (accountName.length() < 3) { throw new IllegalArgumentException("accountName"); } if (accountName.length() > 24) { throw new IllegalArgumentException("accountName"); } for (char accountNameChar : accountName.toCharArray()) { if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) { throw new IllegalArgumentException("accountName"); } } // TODO: Validate accountName is a valid DNS name. if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { throw new IllegalArgumentException("parameters.Description"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("accountName", accountName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/storageservices/"; url = url + URLEncoder.encode(accountName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-10-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element updateStorageServiceInputElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateStorageServiceInput"); requestDoc.appendChild(updateStorageServiceInputElement); if (parameters.getDescription() != null) { Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); updateStorageServiceInputElement.appendChild(descriptionElement); } else { Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); nilAttribute.setValue("true"); emptyElement.setAttributeNode(nilAttribute); updateStorageServiceInputElement.appendChild(emptyElement); } if (parameters.getLabel() != null) { Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); updateStorageServiceInputElement.appendChild(labelElement); } if (parameters.getExtendedProperties() != null) { if (parameters.getExtendedProperties() instanceof LazyCollection == false || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) { Element extendedPropertiesDictionaryElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) { String extendedPropertiesKey = entry.getKey(); String extendedPropertiesValue = entry.getValue(); Element extendedPropertiesElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); Element extendedPropertiesKeyElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); Element extendedPropertiesValueElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); extendedPropertiesElement.appendChild(extendedPropertiesValueElement); } updateStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement); } } if (parameters.getAccountType() != null) { Element accountTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AccountType"); accountTypeElement.appendChild(requestDoc.createTextNode(parameters.getAccountType())); updateStorageServiceInputElement.appendChild(accountTypeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; // Deserialize Response result = new OperationResponse(); result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java
/** * The Begin Creating Storage Account operation creates a new storage * account in Azure. (see//from ww w . ja va2s. co m * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for * more information) * * @param parameters Required. Parameters supplied to the Begin Creating * Storage Account operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse beginCreating(StorageAccountCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { throw new IllegalArgumentException("parameters.Description"); } if (parameters.getLabel() == null) { throw new NullPointerException("parameters.Label"); } if (parameters.getLabel().length() > 100) { throw new IllegalArgumentException("parameters.Label"); } if (parameters.getName() == null) { throw new NullPointerException("parameters.Name"); } if (parameters.getName().length() < 3) { throw new IllegalArgumentException("parameters.Name"); } if (parameters.getName().length() > 24) { throw new IllegalArgumentException("parameters.Name"); } for (char nameChar : parameters.getName().toCharArray()) { if (Character.isLowerCase(nameChar) == false && Character.isDigit(nameChar) == false) { throw new IllegalArgumentException("parameters.Name"); } } // TODO: Validate parameters.Name is a valid DNS name. // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/storageservices"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-10-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element createStorageServiceInputElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "CreateStorageServiceInput"); requestDoc.appendChild(createStorageServiceInputElement); Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceName"); serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getName())); createStorageServiceInputElement.appendChild(serviceNameElement); if (parameters.getDescription() != null) { Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); createStorageServiceInputElement.appendChild(descriptionElement); } else { Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); nilAttribute.setValue("true"); emptyElement.setAttributeNode(nilAttribute); createStorageServiceInputElement.appendChild(emptyElement); } Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); createStorageServiceInputElement.appendChild(labelElement); if (parameters.getAffinityGroup() != null) { Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AffinityGroup"); affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup())); createStorageServiceInputElement.appendChild(affinityGroupElement); } if (parameters.getLocation() != null) { Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Location"); locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); createStorageServiceInputElement.appendChild(locationElement); } if (parameters.getExtendedProperties() != null) { if (parameters.getExtendedProperties() instanceof LazyCollection == false || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) { Element extendedPropertiesDictionaryElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) { String extendedPropertiesKey = entry.getKey(); String extendedPropertiesValue = entry.getValue(); Element extendedPropertiesElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); Element extendedPropertiesKeyElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); Element extendedPropertiesValueElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); extendedPropertiesElement.appendChild(extendedPropertiesValueElement); } createStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement); } } if (parameters.getAccountType() != null) { Element accountTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AccountType"); accountTypeElement.appendChild(requestDoc.createTextNode(parameters.getAccountType())); createStorageServiceInputElement.appendChild(accountTypeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; // Deserialize Response result = new OperationResponse(); result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }