List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:com.microsoft.windowsazure.management.sql.ServerOperationsImpl.java
/** * Changes the administrative password of an existing Azure SQL Database * Server for a given subscription./*from w w w. j ava2 s .co m*/ * * @param serverName Required. The name of the Azure SQL Database Server * that will have the administrator password changed. * @param parameters Required. The necessary parameters for modifying the * adminstrator password for a server. * @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 changeAdministratorPassword(String serverName, ServerChangeAdministratorPasswordParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getNewPassword() == null) { throw new NullPointerException("parameters.NewPassword"); } // 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, "changeAdministratorPasswordAsync", 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"); ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("op=ResetPassword"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } 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(); Element administratorLoginPasswordElement = requestDoc .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword"); requestDoc.appendChild(administratorLoginPasswordElement); administratorLoginPasswordElement.appendChild(requestDoc.createTextNode(parameters.getNewPassword())); 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.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * ?SAML????.//from w ww . jav a 2s .c o m * @return SAML */ public String toSamlString() { /* * Creation of SAML2.0 Document * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.newDocument(); Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion"); doc.appendChild(assertion); assertion.setAttribute("ID", this.id); assertion.setAttribute("Version", "2.0"); // Dummy Date DateTime dateTime = new DateTime(this.issuedAt); assertion.setAttribute("IssueInstant", dateTime.toString()); // Issuer Element issuer = doc.createElement("Issuer"); issuer.setTextContent(this.issuer); assertion.appendChild(issuer); // Subject Element subject = doc.createElement("Subject"); Element nameId = doc.createElement("NameID"); nameId.setTextContent(this.subject); Element subjectConfirmation = doc.createElement("SubjectConfirmation"); subject.appendChild(nameId); subject.appendChild(subjectConfirmation); assertion.appendChild(subject); // Conditions Element conditions = doc.createElement("Conditions"); Element audienceRestriction = doc.createElement("AudienceRestriction"); for (String aud : new String[] { this.target, this.schema }) { Element audience = doc.createElement("Audience"); audience.setTextContent(aud); audienceRestriction.appendChild(audience); } conditions.appendChild(audienceRestriction); assertion.appendChild(conditions); // AuthnStatement Element authnStmt = doc.createElement("AuthnStatement"); authnStmt.setAttribute("AuthnInstant", dateTime.toString()); Element authnCtxt = doc.createElement("AuthnContext"); Element authnCtxtCr = doc.createElement("AuthnContextClassRef"); authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); authnCtxt.appendChild(authnCtxtCr); authnStmt.appendChild(authnCtxt); assertion.appendChild(authnStmt); // AttributeStatement Element attrStmt = doc.createElement("AttributeStatement"); Element attribute = doc.createElement("Attribute"); for (Role role : this.roleList) { Element attrValue = doc.createElement("AttributeValue"); Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); attr.setPrefix("xsi"); attr.setValue("string"); attrValue.setAttributeNodeNS(attr); attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer)); attribute.appendChild(attrValue); } attrStmt.appendChild(attribute); assertion.appendChild(attrStmt); // Normalization doc.normalizeDocument(); // Dsig?? // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. try { signature.sign(dsc); // ? return DcCoreUtils.nodeToString(doc.getDocumentElement()); } catch (MarshalException e1) { // DOM??????? throw new RuntimeException(e1); } catch (XMLSignatureException e1) { // ?????????? throw new RuntimeException(e1); } /* * ------------------------------------------------------------ * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10 * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648] * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/ * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be * line wrapped and pad characters ("=") SHOULD NOT be included. */ }
From source file:com.haulmont.cuba.restapi.XMLConverter.java
/** * Create a new document with the given tag as the root element. * * @param rootTag the tag of the root element * @return the document element of a new document *//* w ww .j av a 2 s . c om*/ public Element newDocument(String rootTag) { DocumentBuilder builder; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } Document doc = builder.newDocument(); Element root = doc.createElement(rootTag); doc.appendChild(root); String[] nvpairs = new String[] { "xmlns:xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, // "xsi:noNamespaceSchemaLocation", INSTANCE_XSD, ATTR_VERSION, "1.0", }; for (int i = 0; i < nvpairs.length; i += 2) { root.setAttribute(nvpairs[i], nvpairs[i + 1]); } return root; }
From source file:com.ggvaidya.scinames.model.Project.java
public void saveToFile() throws IOException { File saveToFile = projectFile.getValue(); if (saveToFile == null) throw new IOException("Project file not set: nowhere to save to!"); /*// ww w.j a v a2s . c o m XMLOutputFactory factory = XMLOutputFactory.newFactory(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(saveToFile)); writer.writeStartDocument(); serializeToXMLStream(writer); writer.writeEndDocument(); writer.flush(); // Success! lastModified.saved(); } catch (XMLStreamException ex) { throw new IOException("Could not write project to XML file '" + saveToFile + "': " + ex); }*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Create a document representation of this project. Document docProject; try { DocumentBuilder db = dbf.newDocumentBuilder(); docProject = db.newDocument(); serializeToDocument(docProject); } catch (ParserConfigurationException ex) { Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null, ex); return; } // Write the document representation of this project // as XML. TransformerFactory tfc = TransformerFactory.newInstance(); try { OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(saveToFile)); StreamResult res = new StreamResult(outputStream); Transformer t = tfc.newTransformer(); DOMSource ds = new DOMSource(docProject); t.setOutputProperty(OutputKeys.METHOD, "xml"); t.setOutputProperty(OutputKeys.VERSION, "1.0"); // Do NOT change to 1.1 -- this leads to complex problems! t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.STANDALONE, "yes"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.transform(ds, res); // Success! lastModified.saved(); outputStream.close(); } catch (TransformerConfigurationException ex) { throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex); } catch (TransformerException ex) { throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex); } }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * ?SAML????.// ww w. j a v a 2 s . c o m * @return SAML */ public String toSamlString() { /* * Creation of SAML2.0 Document * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.newDocument(); Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion"); doc.appendChild(assertion); assertion.setAttribute("ID", this.id); assertion.setAttribute("Version", "2.0"); // Dummy Date DateTime dateTime = new DateTime(this.issuedAt); assertion.setAttribute("IssueInstant", dateTime.toString()); // Issuer Element issuer = doc.createElement("Issuer"); issuer.setTextContent(this.issuer); assertion.appendChild(issuer); // Subject Element subject = doc.createElement("Subject"); Element nameId = doc.createElement("NameID"); nameId.setTextContent(this.subject); Element subjectConfirmation = doc.createElement("SubjectConfirmation"); subject.appendChild(nameId); subject.appendChild(subjectConfirmation); assertion.appendChild(subject); // Conditions Element conditions = doc.createElement("Conditions"); Element audienceRestriction = doc.createElement("AudienceRestriction"); for (String aud : new String[] { this.target, this.schema }) { Element audience = doc.createElement("Audience"); audience.setTextContent(aud); audienceRestriction.appendChild(audience); } conditions.appendChild(audienceRestriction); assertion.appendChild(conditions); // AuthnStatement Element authnStmt = doc.createElement("AuthnStatement"); authnStmt.setAttribute("AuthnInstant", dateTime.toString()); Element authnCtxt = doc.createElement("AuthnContext"); Element authnCtxtCr = doc.createElement("AuthnContextClassRef"); authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); authnCtxt.appendChild(authnCtxtCr); authnStmt.appendChild(authnCtxt); assertion.appendChild(authnStmt); // AttributeStatement Element attrStmt = doc.createElement("AttributeStatement"); Element attribute = doc.createElement("Attribute"); for (Role role : this.roleList) { Element attrValue = doc.createElement("AttributeValue"); Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); attr.setPrefix("xsi"); attr.setValue("string"); attrValue.setAttributeNodeNS(attr); attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer)); attribute.appendChild(attrValue); } attrStmt.appendChild(attribute); assertion.appendChild(attrStmt); // Normalization doc.normalizeDocument(); // Dsig?? // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. try { signature.sign(dsc); // ? return PersoniumCoreUtils.nodeToString(doc.getDocumentElement()); } catch (MarshalException e1) { // DOM??????? throw new RuntimeException(e1); } catch (XMLSignatureException e1) { // ?????????? throw new RuntimeException(e1); } /* * ------------------------------------------------------------ * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10 * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648] * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/ * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be * line wrapped and pad characters ("=") SHOULD NOT be included. */ }
From source file:com.microsoft.windowsazure.management.ManagementCertificateOperationsImpl.java
/** * The Create Management Certificate operation adds a certificate to the * list of management certificates. Management certificates, which are also * known as subscription certificates, authenticate clients attempting to * connect to resources associated with your Azure subscription. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for * more information)// w w w.j a va 2 s . com * * @param parameters Required. Parameters supplied to the Create Management * Certificate 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 create(ManagementCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } // 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, "createAsync", 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 + "/certificates"; 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 subscriptionCertificateElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate"); requestDoc.appendChild(subscriptionCertificateElement); if (parameters.getPublicKey() != null) { Element subscriptionCertificatePublicKeyElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey"); subscriptionCertificatePublicKeyElement .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPublicKey()))); subscriptionCertificateElement.appendChild(subscriptionCertificatePublicKeyElement); } if (parameters.getThumbprint() != null) { Element subscriptionCertificateThumbprintElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); subscriptionCertificateThumbprintElement .appendChild(requestDoc.createTextNode(parameters.getThumbprint())); subscriptionCertificateElement.appendChild(subscriptionCertificateThumbprintElement); } if (parameters.getData() != null) { Element subscriptionCertificateDataElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData"); subscriptionCertificateDataElement .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData()))); subscriptionCertificateElement.appendChild(subscriptionCertificateDataElement); } 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.sql.ServerOperationsImpl.java
/** * Provisions a new SQL Database server in a subscription. * * @param parameters Required. The parameters needed to provision a server. * @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.//from w w w. ja v a 2 s .c om * @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 The response returned from the Create Server operation. This * contains all the information returned from the service when a server is * created. */ @Override public ServerCreateResponse create(ServerCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getAdministratorPassword() == null) { throw new NullPointerException("parameters.AdministratorPassword"); } if (parameters.getAdministratorUserName() == null) { throw new NullPointerException("parameters.AdministratorUserName"); } if (parameters.getLocation() == null) { throw new NullPointerException("parameters.Location"); } // 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, "createAsync", 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"; 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(); Element serverElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "Server"); requestDoc.appendChild(serverElement); Element administratorLoginElement = requestDoc .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLogin"); administratorLoginElement.appendChild(requestDoc.createTextNode(parameters.getAdministratorUserName())); serverElement.appendChild(administratorLoginElement); Element administratorLoginPasswordElement = requestDoc .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword"); administratorLoginPasswordElement .appendChild(requestDoc.createTextNode(parameters.getAdministratorPassword())); serverElement.appendChild(administratorLoginPasswordElement); Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "Location"); locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); serverElement.appendChild(locationElement); if (parameters.getVersion() != null) { Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "Version"); versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion())); serverElement.appendChild(versionElement); } 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_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServerCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServerCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serverNameElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/sqlazure/2010/12/", "ServerName"); if (serverNameElement != null) { Attr fullyQualifiedDomainNameAttribute = serverNameElement.getAttributeNodeNS( "http://schemas.microsoft.com/sqlazure/2010/12/", "FullyQualifiedDomainName"); if (fullyQualifiedDomainNameAttribute != null) { result.setFullyQualifiedDomainName(fullyQualifiedDomainNameAttribute.getValue()); } result.setServerName(serverNameElement.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:ar.edu.uns.cs.vyglab.arq.rockar.gui.JFrameControlPanel.java
public void saveTable() { File currentDir = new File(System.getProperty("user.dir")); JFileChooser saveDialog = new JFileChooser(currentDir); FileNameExtensionFilter filter = new FileNameExtensionFilter("MTF File", "mtf", "mtf"); saveDialog.setFileFilter(filter);//from www.j a v a 2 s. co m int response = saveDialog.showSaveDialog(this); if (response == saveDialog.APPROVE_OPTION) { File file = saveDialog.getSelectedFile(); if (file.getName().lastIndexOf(".") == -1) { file = new File(file.getName() + ".mtf"); } DataCenter.fileMineralList = file; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("table"); doc.appendChild(rootElement); // para cada mineral en la tabla de minerales, agrego un Element for (int i = 0; i < this.jTableMineralsModel.getRowCount(); i++) { Element mineral = doc.createElement("mineral"); // set attribute id to mineral element Attr attr = doc.createAttribute("key"); //attr.setValue(this.jTableMinerales.getModel().getValueAt(i, 0).toString()); attr.setValue(this.jTableMineralsModel.getValueAt(i, 0).toString()); mineral.setAttributeNode(attr); // set attribute name to mineral element attr = doc.createAttribute("name"); attr.setValue(this.jTableMineralsModel.getValueAt(i, 1).toString()); mineral.setAttributeNode(attr); // set attribute color to mineral element attr = doc.createAttribute("color"); attr.setValue(String.valueOf(((Color) this.jTableMineralsModel.getValueAt(i, 2)).getRGB())); mineral.setAttributeNode(attr); // agrego el mineral a los minerales rootElement.appendChild(mineral); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(DataCenter.fileMineralList); transformer.transform(source, result); } catch (Exception e) { } } }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException/* w w w. ja v a 2 s . co m*/ * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void execute(TransformerPluginContext context) throws XtentisException { try { // fetch data from context Transformer transformer = (Transformer) context.get(TRANSFORMER); String outputMethod = (String) context.get(OUTPUT_METHOD); TypedContent xmlTC = (TypedContent) context.get(INPUT_XML); // get the charset String charset = Util.extractCharset(xmlTC.getContentType()); // get the xml String String xml = new String(xmlTC.getContentBytes(), charset); // get the xml parameters TypedContent parametersTC = (TypedContent) context.get(INPUT_PARAMETERS); if (parametersTC != null) { String parametersCharset = Util.extractCharset(parametersTC.getContentType()); byte[] parametersBytes = parametersTC.getContentBytes(); if (parametersBytes != null) { String parameters = new String(parametersBytes, parametersCharset); Document parametersDoc = Util.parse(parameters); NodeList paramList = Util.getNodeList(parametersDoc.getDocumentElement(), "//Parameter"); //$NON-NLS-1$ for (int i = 0; i < paramList.getLength(); i++) { String paramName = Util.getFirstTextNode(paramList.item(i), "Name"); //$NON-NLS-1$ String paramValue = Util.getFirstTextNode(paramList.item(i), "Value"); //$NON-NLS-1$ if (paramValue == null) paramValue = ""; //$NON-NLS-1$ if (paramName != null) { transformer.setParameter(paramName, paramValue); } } } } // FIXME: ARRRRGHHHHHH - How do you prevent the Transformer to process doctype instructions? // Sets the current time transformer.setParameter("TIMESTAMP", getTimestamp()); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void fatalError(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void warning(TransformerException exception) throws TransformerException { transformationeWarning = exception.getMessage(); } }); transformatioError = null; transformationeWarning = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); if ("xml".equals(outputMethod) || "xhtml".equals(outputMethod)) { //$NON-NLS-1$ //$NON-NLS-2$ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.newDocument(); DOMResult domResult = new DOMResult(document); transformer.transform(new StreamSource(new StringReader(xml)), domResult); if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } Node rootNode = document.getDocumentElement(); // process the cross-referencings NodeList xrefl = Util.getNodeList(rootNode.getOwnerDocument(), "//*[@xrefCluster]"); //$NON-NLS-1$ int len = xrefl.getLength(); for (int i = 0; i < len; i++) { Element xrefe = (Element) xrefl.item(i); xrefe = processMappings(xrefe); } TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); Transformer serializer = transFactory.newTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, outputMethod); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ serializer.transform(new DOMSource(rootNode), new StreamResult(baos)); } else { if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } // transform the item transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(baos)); } // Call Back byte[] bytes = baos.toByteArray(); if (LOG.isDebugEnabled()) { LOG.debug("execute() Inserting XSL Result in '" + OUTPUT_TEXT + "'\n" + new String(bytes, "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } context.put(OUTPUT_TEXT, new TypedContent(bytes, ("xhtml".equals(outputMethod) ? "application/xhtml+xml" //$NON-NLS-1$//$NON-NLS-2$ : "text/" //$NON-NLS-1$ + outputMethod) + "; charset=utf-8")); //$NON-NLS-1$ context.getPluginCallBack().contentIsReady(context); } catch (Exception e) { String err = "Could not start the XSLT plugin"; //$NON-NLS-1$ LOG.error(err, e); throw new XtentisException(err); } }
From source file:com.aurel.track.exchange.track.exporter.TrackExportBL.java
/** * Exports the reportBeans to an xml file * @param reportBeans//from w w w. j a v a 2 s . c om * @param personID * @return */ private static Document exportWorkItems(List<ReportBean> reportBeansList, Integer personID) { Document dom = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); dom = builder.newDocument(); } 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; } //create the DOM object Element root = dom.createElement(ExchangeFieldNames.TRACKPLUS_EXCHANGE); dom.appendChild(root); if (reportBeansList == null || reportBeansList.isEmpty()) { return dom; } LOGGER.info("Number of workItems exported: " + reportBeansList.size()); //load also the full history List<ReportBeanWithHistory> reportBeansWithHistoryList = ReportBeanHistoryLoader .getReportBeanWithHistoryList(reportBeansList, Locale.ENGLISH, true, false, true, null, true, true, true, true, true, personID, null, null, null, true, LONG_TEXT_TYPE.ISFULLHTML); //get the workItemIDs List<Integer> workItemIDsList = new ArrayList<Integer>(); Set<Integer> issueTypeSet = new HashSet<Integer>(); Set<Integer> projectTypeSet = new HashSet<Integer>(); Set<Integer> projectSet = new HashSet<Integer>(); for (ReportBean reportBean : reportBeansWithHistoryList) { TWorkItemBean workItemBean = reportBean.getWorkItemBean(); workItemIDsList.add(workItemBean.getObjectID()); issueTypeSet.add(workItemBean.getListTypeID()); projectSet.add(workItemBean.getProjectID()); } List<TProjectBean> projectBeans = ProjectBL.loadByProjectIDs(GeneralUtils.createListFromSet(projectSet)); if (projectBeans != null) { for (TProjectBean projectBean : projectBeans) { projectTypeSet.add(projectBean.getProjectType()); } } //load the dropdown container based on the workItemIDsList DropDownContainer dropDownContainer = HistoryDropdownContainerLoader .loadExporterDropDownContainer(GeneralUtils.createIntArrFromIntegerList(workItemIDsList)); /** * fieldType based lookup values will be gathered in the lookup map: * fieldID_parametercode keyed -> lookup objectID keyed -> attribute name to attribute string value map */ Map<Integer, ILabelBean> personBeansMap = dropDownContainer .getDataSourceMap(MergeUtil.mergeKey(SystemFields.INTEGER_PERSON, null)); Map<String, Map<Integer, Map<String, String>>> serializedLookupsMap = new HashMap<String, Map<Integer, Map<String, String>>>(); //initialize the serialized person map explicitly because it will be loaded also //from other parts (consultants/informants, budget, cost etc.) Map<Integer, Map<String, String>> serializedPersonsMap = new HashMap<Integer, Map<String, String>>(); serializedLookupsMap.put(MergeUtil.mergeKey(SystemFields.INTEGER_PERSON, null), serializedPersonsMap); /** * gather all non-fieldType based lookup values in the additionalSerializedEntitiesMap map: * accounts, costcenteres, departments, system states, projectTypes and lists */ Map<String, Map<Integer, Map<String, String>>> additionalSerializedLookupsMap = new HashMap<String, Map<Integer, Map<String, String>>>(); Map<Integer, TCostCenterBean> costCentersMap = GeneralUtils .createMapFromList(AccountBL.getAllCostcenters()); Map<Integer, TAccountBean> accountsMap = GeneralUtils.createMapFromList(AccountBL.getAllAccounts()); //get the custom fields map Map<Integer, ISerializableLabelBean> customFieldBeansMap = GeneralUtils .createMapFromList(FieldBL.loadCustom()); Set<Integer> pseudoHistoryFields = HistoryLoaderBL.getPseudoHistoryFields(); /** * add the actual attribute values */ Set<Integer> nonNullFields = new HashSet<Integer>(); //linked through parent, issueNos in descriptions/comments and later issueLinks Set<Integer> linkedWorkItemIDs = new HashSet<Integer>(); for (int n = 0; n < reportBeansWithHistoryList.size(); n++) { ReportBean reportBean = (ReportBean) reportBeansWithHistoryList.get(n); TWorkItemBean workItemBean = reportBean.getWorkItemBean(); Map<String, String> attributes = new HashMap<String, String>(); attributes.put(ExchangeFieldNames.UUID, workItemBean.getUuid()); attributes.put(ExchangeFieldNames.WORKITEMID, workItemBean.getObjectID().toString()); Element itemElement = createElementWithAttributes(ExchangeFieldNames.ITEM, null, false, attributes, dom); //system field nodes for (int i = 0; i < SystemFields.getSystemFieldsArray().length; i++) { Integer fieldID = Integer.valueOf(SystemFields.getSystemFieldsArray()[i]); if (!fieldID.equals(SystemFields.INTEGER_ISSUENO)) { //the issueNo is added directly to item element { Object workItemAttribute = workItemBean.getAttribute(fieldID, null); if (workItemAttribute != null) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); if (fieldTypeRT != null) { nonNullFields.add(fieldID); gatherLinkedWorkItems(workItemAttribute, fieldTypeRT, linkedWorkItemIDs); Map<String, String> fieldAndParameterCodeAttributes = new HashMap<String, String>(); fieldAndParameterCodeAttributes.put(ExchangeFieldNames.FIELDID, fieldID.toString()); appendAttributeElement(ExchangeFieldNames.ITEM_ATTRIBUTE, itemElement, workItemAttribute, fieldTypeRT, fieldID, null, dropDownContainer, serializedLookupsMap, additionalSerializedLookupsMap, fieldAndParameterCodeAttributes, dom); } } } } //custom field nodes Map<String, Object> customAttributes = workItemBean.getCustomAttributeValues(); Integer parameterCode; if (customAttributes != null && !customAttributes.isEmpty()) { Iterator<String> iterator = customAttributes.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String[] splittedKey = MergeUtil.splitKey(key); String strFieldID = splittedKey[0].substring(1); //get rid of "f" Integer fieldID = Integer.valueOf(strFieldID); String strParameterCode = null; parameterCode = null; if (splittedKey.length > 1) { //whether the workItemAttribute is a part of a composite custom field strParameterCode = splittedKey[1]; if (strParameterCode != null && !"null".equals(strParameterCode)) { try { parameterCode = Integer.valueOf(strParameterCode); } catch (Exception e) { LOGGER.error("Converting the parameterCode " + strParameterCode + " to an integer failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } } //add to custom field beans addToAdditionalSerializedLookupsMap(customFieldBeansMap.get(fieldID), ExchangeFieldNames.FIELD, additionalSerializedLookupsMap); Object workItemAttribute = workItemBean.getAttribute(fieldID, parameterCode); if (workItemAttribute != null) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID, parameterCode); nonNullFields.add(fieldID); gatherLinkedWorkItems(workItemAttribute, fieldTypeRT, linkedWorkItemIDs); Map<String, String> fieldAndParameterCodeAttributes = new HashMap<String, String>(); if (strFieldID != null) { fieldAndParameterCodeAttributes.put(ExchangeFieldNames.FIELDID, strFieldID); } if (strParameterCode != null) { fieldAndParameterCodeAttributes.put(ExchangeFieldNames.PARAMETERCODE, strParameterCode); } appendAttributeElement(ExchangeFieldNames.ITEM_ATTRIBUTE, itemElement, workItemAttribute, fieldTypeRT, fieldID, parameterCode, dropDownContainer, serializedLookupsMap, additionalSerializedLookupsMap, fieldAndParameterCodeAttributes, dom); } } } /** * add the consulted and informed nodes */ Set<Integer> consultedList = reportBean.getConsultedList(); if (consultedList != null && !consultedList.isEmpty()) { itemElement.appendChild(createConsInfElement(ExchangeFieldNames.CONSULTANT_LIST, ExchangeFieldNames.CONSULTANT, consultedList, personBeansMap, serializedPersonsMap, dom)); } Set<Integer> informedList = reportBean.getInformedList(); if (informedList != null && !informedList.isEmpty()) { itemElement.appendChild(createConsInfElement(ExchangeFieldNames.INFORMANT_LIST, ExchangeFieldNames.INFORMANT, informedList, personBeansMap, serializedPersonsMap, dom)); } /** * add the history nodes */ ReportBeanWithHistory reportBeanWithHistory = (ReportBeanWithHistory) reportBean; Element historyElement = createHistoryElement(reportBeanWithHistory.getHistoryValuesMap(), dropDownContainer, dom, serializedLookupsMap, additionalSerializedLookupsMap, pseudoHistoryFields, linkedWorkItemIDs); if (historyElement != null) { itemElement.appendChild(historyElement); } /** * add the budget nodes */ Element budgetElement = createBudgetPlanElement(reportBeanWithHistory.getBudgetHistory(), personBeansMap, serializedPersonsMap, dom, false); if (budgetElement != null) { itemElement.appendChild(budgetElement); } Element plannedValueElement = createBudgetPlanElement(reportBeanWithHistory.getPlannedValueHistory(), personBeansMap, serializedPersonsMap, dom, true); if (plannedValueElement != null) { itemElement.appendChild(plannedValueElement); } if (budgetElement != null) { //do not add estimated remaining budget element if no budget exists Element remainingBudgetElement = createRemainingBudgetElement( reportBeanWithHistory.getActualEstimatedBudgetBean(), personBeansMap, serializedPersonsMap, dom); if (remainingBudgetElement != null) { itemElement.appendChild(remainingBudgetElement); } } /** * add the expense nodes */ Element costElement = createExpenseElement(reportBeanWithHistory.getCosts(), personBeansMap, accountsMap, costCentersMap, serializedPersonsMap, dom, additionalSerializedLookupsMap); if (costElement != null) { itemElement.appendChild(costElement); } List<TAttachmentBean> existingAttachments = AttachBL .getExistingAttachments(reportBeanWithHistory.getAttachments()); Element attachmentElement = createAttachmentElement(existingAttachments, personBeansMap, serializedPersonsMap, dom); if (attachmentElement != null) { itemElement.appendChild(attachmentElement); } root.appendChild(itemElement); } /** * load the not explicitly exported linked workItems */ linkedWorkItemIDs.removeAll(workItemIDsList); if (!linkedWorkItemIDs.isEmpty()) { List<TWorkItemBean> workItemBeanList = ItemBL .loadByWorkItemKeys(GeneralUtils.createIntArrFromSet(linkedWorkItemIDs)); if (workItemIDsList != null) { Iterator<TWorkItemBean> itrWorkItemBean = workItemBeanList.iterator(); while (itrWorkItemBean.hasNext()) { TWorkItemBean workItemBean = itrWorkItemBean.next(); Map<String, String> attributeValues = workItemBean.serializeBean(); root.appendChild(createElementWithAttributes(ExchangeFieldNames.LINKED_ITEMS, "", false, attributeValues, dom)); } } } /** * add the systemState entries to the additionalSerializedEntitiesMap */ Map<Integer, Map<String, String>> serializedProjectMap = serializedLookupsMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_PROJECT, null)); Map<Integer, Map<String, String>> serializedReleaseMap = serializedLookupsMap .get(MergeUtil.mergeKey(SystemFields.RELEASE, null)); Map<Integer, Map<String, String>> serializedAccountsMap = additionalSerializedLookupsMap .get(ExchangeFieldNames.ACCOUNT); Map<Integer, TSystemStateBean> systemStateMap = GeneralUtils.createMapFromList(SystemStatusBL.loadAll()); addSystemState(serializedProjectMap, systemStateMap, additionalSerializedLookupsMap); addSystemState(serializedReleaseMap, systemStateMap, additionalSerializedLookupsMap); addSystemState(serializedAccountsMap, systemStateMap, additionalSerializedLookupsMap); /** * add each option for the list (which have at least one option set on an issue) */ Map<Integer, Map<String, String>> serializedListMap = additionalSerializedLookupsMap .get(ExchangeFieldNames.LIST); addListAdditional(serializedListMap, dropDownContainer, serializedLookupsMap, additionalSerializedLookupsMap); /** * add the project related additional entities to serializedEntitiesMap and additionalSerializedEntitiesMap */ Map<Integer, TProjectTypeBean> projetcTypesMap = GeneralUtils.createMapFromList(ProjectTypesBL.loadAll()); addProjectAdditional(serializedProjectMap, projetcTypesMap, serializedLookupsMap, additionalSerializedLookupsMap, accountsMap, costCentersMap); /** * add field related entities: the owners */ Map<Integer, Map<String, String>> serializedCustomFields = additionalSerializedLookupsMap .get(ExchangeFieldNames.FIELD); addFieldAdditional(serializedCustomFields, serializedLookupsMap); /** * add the used fieldConfigs */ List<TFieldConfigBean> fieldConfigBeans = FieldConfigBL.loadAllForFields(nonNullFields); for (Iterator<TFieldConfigBean> iterator = fieldConfigBeans.iterator(); iterator.hasNext();) { //remove the field configurations for not used issueTypes, projectTypes and projects TFieldConfigBean fieldConfigBean = iterator.next(); Integer issueTypeID = fieldConfigBean.getIssueType(); Integer projectTypeID = fieldConfigBean.getProjectType(); Integer projectID = fieldConfigBean.getProject(); if (issueTypeID != null && !issueTypeSet.contains(issueTypeID)) { iterator.remove(); continue; } if (projectTypeID != null && !projectTypeSet.contains(projectTypeID)) { iterator.remove(); continue; } if (projectID != null && !projectSet.contains(projectID)) { iterator.remove(); continue; } } //comment this and uncomment the coming block to add fewer field configs addToAdditionalSerializedLookupsMap((List) fieldConfigBeans, ExchangeFieldNames.FIELDCONFIG, additionalSerializedLookupsMap); Map<Integer, Map<String, String>> serializedFieldConfigs = additionalSerializedLookupsMap .get(ExchangeFieldNames.FIELDCONFIG); addFieldConfigsAdditional(serializedFieldConfigs, projetcTypesMap, serializedLookupsMap, additionalSerializedLookupsMap); /** * add the field settings */ List<Integer> userFieldConfigIDs = GeneralUtils.createListFromSet(serializedFieldConfigs.keySet()); //option settings List<ISerializableLabelBean> optionSettingsList = (List) OptionSettingsBL .loadByConfigList(userFieldConfigIDs); if (optionSettingsList != null) { Iterator<ISerializableLabelBean> itrOptionSettings = optionSettingsList.iterator(); while (itrOptionSettings.hasNext()) { TOptionSettingsBean optionSettingsBean = (TOptionSettingsBean) itrOptionSettings.next(); Integer listID = optionSettingsBean.getList(); if (serializedListMap == null || !serializedListMap.containsKey(listID)) { //do not export the option settings if the corresponding list is not exported //(none of the selected workItems has a value from this list) //because creating the optionSetings will fail without the listID itrOptionSettings.remove(); } } } addToAdditionalSerializedLookupsMap(optionSettingsList, ExchangeFieldNames.OPTIONSETTINGS, additionalSerializedLookupsMap); //textbox settings List<ISerializableLabelBean> textBoxSettingsList = (List) TextBoxSettingsBL .loadByConfigList(userFieldConfigIDs); addToAdditionalSerializedLookupsMap(textBoxSettingsList, ExchangeFieldNames.TEXTBOXSETTINGS, additionalSerializedLookupsMap); //general settings List<ISerializableLabelBean> generalSettingsList = (List) GeneralSettingsBL .loadByConfigList(userFieldConfigIDs); addToAdditionalSerializedLookupsMap(generalSettingsList, ExchangeFieldNames.GENERALSETTINGS, additionalSerializedLookupsMap); /** * add the person related additional entities to serializedEntitiesMap and additionalSerializedEntitiesMap */ addPersonAdditional(serializedPersonsMap, GeneralUtils.createMapFromList(DepartmentBL.getAllDepartments()), costCentersMap, serializedLookupsMap, additionalSerializedLookupsMap); /** * add the role assignments and the roles * the role assignments cannot be added to the additionalSerializedLookupsMap because they have no objectID * consequently they will be serialized directly */ List<ISerializableLabelBean> accessControlListBeanList = (List) AccessControlBL.loadByPersonsAndProjects( GeneralUtils.createIntegerListFromCollection(serializedPersonsMap.keySet()), GeneralUtils.createIntegerListFromCollection(serializedProjectMap.keySet())); if (accessControlListBeanList != null) { Map<Integer, TRoleBean> roleMap = GeneralUtils.createMapFromList(RoleBL.loadAll()); Iterator<ISerializableLabelBean> iterator = accessControlListBeanList.iterator(); while (iterator.hasNext()) { TAccessControlListBean accessControlListBean = (TAccessControlListBean) iterator.next(); //serialize the role assignment directly root.appendChild(createElementWithAttributes(ExchangeFieldNames.ACL, null, false, accessControlListBean.serializeBean(), dom)); Integer role = accessControlListBean.getRoleID(); TRoleBean roleBean = roleMap.get(role); if (roleBean != null) { //add the roles which are present in the role assignments addToAdditionalSerializedLookupsMap(roleBean, ExchangeFieldNames.ROLE, additionalSerializedLookupsMap); } } } /** * first add the additional serialized entities first because the fieldID mapping is needed by parsing the serialized entities */ Iterator<String> iterator = additionalSerializedLookupsMap.keySet().iterator(); while (iterator.hasNext()) { String entityName = iterator.next(); Map<Integer, Map<String, String>> lookupEntityMap = additionalSerializedLookupsMap.get(entityName); if (lookupEntityMap != null && !lookupEntityMap.isEmpty()) { Iterator<Integer> itrObjectID = lookupEntityMap.keySet().iterator(); while (itrObjectID.hasNext()) { Integer objectID = itrObjectID.next(); Map<String, String> attributes = lookupEntityMap.get(objectID); if (attributes != null && !attributes.isEmpty()) { root.appendChild(createElementWithAttributes(entityName, null, false, attributes, dom)); } } } } /** * add the serialized entities */ iterator = serializedLookupsMap.keySet().iterator(); while (iterator.hasNext()) { String mergedKey = iterator.next(); Integer[] parts = MergeUtil.getParts(mergedKey); Integer fieldID = parts[0]; Integer parameterCode = parts[1]; Map<Integer, Map<String, String>> lookupEntityMap = serializedLookupsMap.get(mergedKey); if (lookupEntityMap != null && !lookupEntityMap.isEmpty()) { Iterator<Integer> itrObjectID = lookupEntityMap.keySet().iterator(); while (itrObjectID.hasNext()) { Integer objectID = itrObjectID.next(); Map<String, String> attributes = lookupEntityMap.get(objectID); if (attributes != null && !attributes.isEmpty()) { if (fieldID != null) { attributes.put(ExchangeFieldNames.FIELDID, fieldID.toString()); } if (parameterCode != null) { attributes.put(ExchangeFieldNames.PARAMETERCODE, parameterCode.toString()); } root.appendChild(createElementWithAttributes(ExchangeFieldNames.DROPDOWN_ELEMENT, null, false, attributes, dom)); } } } } return dom; }