List of usage examples for org.w3c.dom Document cloneNode
public Node cloneNode(boolean deep);
From source file:Main.java
private static Document pruneDocument(Document doc, int maxElement) throws ParserConfigurationException { if (maxElement == -1) { return doc; }// ww w .j a v a2 s. c o m Document newDoc = (Document) doc.cloneNode(false); Element newRoot = (Element) doc.getDocumentElement().cloneNode(false); newDoc.adoptNode(newRoot); newDoc.appendChild(newRoot); NodeList nl = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < maxElement && i < nl.getLength(); i++) { if (!(nl.item(i) instanceof Element)) { maxElement++; continue; } Node item = nl.item(i).cloneNode(true); newDoc.adoptNode(item); newDoc.getDocumentElement().appendChild(item); } if (debug) System.out.println("Creating document of " + newDoc.getDocumentElement().getChildNodes().getLength()); return newDoc; }
From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java
private Document loadTemplate(String templateViewName, TemplateContext templateContext) throws Exception { ViewConfigInfo viewConfigInfo = getViewConfigModelInfo(templateViewName); if (viewConfigInfo == null) { throw new XmlParseException("Template view not found [" + templateViewName + "].", templateContext.getSourceContext()); }/* w ww.j a va 2 s.co m*/ Document templateDocument = (Document) viewConfigInfo.getConfigModel(); synchronized (templateDocument) { templateDocument = (Document) templateDocument.cloneNode(true); mergeMetaData(templateDocument, templateDocument.getDocumentElement(), templateContext.getSourceDocument().getDocumentElement()); mergeArguments(templateDocument, templateContext); mergeModels(templateDocument, templateContext); gothroughPlaceHolders(templateDocument, templateContext); } return templateDocument; }
From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java
public static Map<String, Object> uspsPriorityMailInternationalLabel(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId"); String resource = (String) context.get("configProps"); GenericValue shipmentRouteSegment = (GenericValue) context.get("shipmentRouteSegment"); Locale locale = (Locale) context.get("locale"); // Start the document Document requestDocument; boolean certify = false; String test = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "test", resource, "shipment.usps.test"); if (!"Y".equalsIgnoreCase(test)) { requestDocument = createUspsRequestDocument("PriorityMailIntlRequest", false, delegator, shipmentGatewayConfigId, resource); } else {// w ww .j av a2 s . com requestDocument = createUspsRequestDocument("PriorityMailIntlCertifyRequest", false, delegator, shipmentGatewayConfigId, resource); certify = true; } Element rootElement = requestDocument.getDocumentElement(); // Retrieve from/to address and package details GenericValue originAddress = null; GenericValue originTelecomNumber = null; GenericValue destinationAddress = null; GenericValue destinationProvince = null; GenericValue destinationCountry = null; GenericValue destinationTelecomNumber = null; List<GenericValue> shipmentPackageRouteSegs = null; try { originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false); originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false); destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false); if (destinationAddress != null) { destinationProvince = destinationAddress.getRelatedOne("StateProvinceGeo", false); destinationCountry = destinationAddress.getRelatedOne("CountryGeo", false); } destinationTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false); shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, null, false); } catch (GenericEntityException e) { Debug.logError(e, module); } if (originAddress == null || originTelecomNumber == null) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelOriginAddressMissing", locale)); } // Origin Info // USPS wants a separate first name and last, best we can do is split the string on the white space, if that doesn't work then default to putting the attnName in both fields String fromAttnName = originAddress.getString("attnName"); String fromFirstName = StringUtils.defaultIfEmpty(StringUtils.substringBefore(fromAttnName, " "), fromAttnName); String fromLastName = StringUtils.defaultIfEmpty(StringUtils.substringAfter(fromAttnName, " "), fromAttnName); UtilXml.addChildElementValue(rootElement, "FromFirstName", fromFirstName, requestDocument); UtilXml.addChildElementValue(rootElement, "FromLastName", fromLastName, requestDocument); UtilXml.addChildElementValue(rootElement, "FromFirm", originAddress.getString("toName"), requestDocument); // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1 UtilXml.addChildElementValue(rootElement, "FromAddress1", originAddress.getString("address2"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromAddress2", originAddress.getString("address1"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromCity", originAddress.getString("city"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromState", originAddress.getString("stateProvinceGeoId"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromZip5", originAddress.getString("postalCode"), requestDocument); // USPS expects a phone number consisting of area code + contact number as a single numeric string String fromPhoneNumber = originTelecomNumber.getString("areaCode") + originTelecomNumber.getString("contactNumber"); fromPhoneNumber = StringUtil.removeNonNumeric(fromPhoneNumber); UtilXml.addChildElementValue(rootElement, "FromPhone", fromPhoneNumber, requestDocument); // Destination Info UtilXml.addChildElementValue(rootElement, "ToName", destinationAddress.getString("attnName"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToFirm", destinationAddress.getString("toName"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToAddress1", destinationAddress.getString("address1"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToAddress2", destinationAddress.getString("address2"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToCity", destinationAddress.getString("city"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToProvince", destinationProvince.getString("geoName"), requestDocument); // TODO: Test these country names, I think we're going to need to maintain a list of USPS names UtilXml.addChildElementValue(rootElement, "ToCountry", destinationCountry.getString("geoName"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToPostalCode", destinationAddress.getString("postalCode"), requestDocument); // TODO: Figure out how to answer this question accurately UtilXml.addChildElementValue(rootElement, "ToPOBoxFlag", "N", requestDocument); String toPhoneNumber = destinationTelecomNumber.getString("countryCode") + destinationTelecomNumber.getString("areaCode") + destinationTelecomNumber.getString("contactNumber"); UtilXml.addChildElementValue(rootElement, "ToPhone", toPhoneNumber, requestDocument); UtilXml.addChildElementValue(rootElement, "NonDeliveryOption", "RETURN", requestDocument); for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) { Document packageDocument = (Document) requestDocument.cloneNode(true); // This is our reference and can be whatever we want. For lack of a better alternative we'll use shipmentId:shipmentPackageSeqId:shipmentRouteSegmentId String fromCustomsReference = shipmentRouteSegment.getString("shipmentId") + ":" + shipmentRouteSegment.getString("shipmentRouteSegmentId"); fromCustomsReference = StringUtils.join(UtilMisc.toList(shipmentRouteSegment.get("shipmentId"), shipmentPackageRouteSeg.get("shipmentPackageSeqId"), shipmentRouteSegment.get("shipmentRouteSegementId")), ':'); UtilXml.addChildElementValue(rootElement, "FromCustomsReference", fromCustomsReference, packageDocument); // Determine the container type for this package String container = "VARIABLE"; String packageTypeCode = null; GenericValue shipmentPackage = null; List<GenericValue> shipmentPackageContents = null; try { shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false); shipmentPackageContents = shipmentPackage.getRelated("ShipmentPackageContent", null, null, false); GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false); if (shipmentBoxType != null) { GenericValue carrierShipmentBoxType = EntityUtil.getFirst(shipmentBoxType .getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "USPS"), null, false)); if (carrierShipmentBoxType != null) { packageTypeCode = carrierShipmentBoxType.getString("packageTypeCode"); // Supported type codes List<String> supportedPackageTypeCodes = UtilMisc.toList("LGFLATRATEBOX", "SMFLATRATEBOX", "FLATRATEBOX", "MDFLATRATEBOX", "FLATRATEENV"); if (supportedPackageTypeCodes.contains(packageTypeCode)) { container = packageTypeCode; } } } } catch (GenericEntityException e) { Debug.logError(e, module); } UtilXml.addChildElementValue(rootElement, "Container", container, packageDocument); // According to the docs sending an empty postage tag will cause the postage to be calculated UtilXml.addChildElementValue(rootElement, "Postage", "", packageDocument); BigDecimal packageWeight = shipmentPackage.getBigDecimal("weight"); String weightUomId = shipmentPackage.getString("weightUomId"); BigDecimal packageWeightPounds = UomWorker.convertUom(packageWeight, weightUomId, "WT_lb", dispatcher); Integer[] packagePoundsOunces = convertPoundsToPoundsOunces(packageWeightPounds); UtilXml.addChildElementValue(rootElement, "GrossPounds", packagePoundsOunces[0].toString(), packageDocument); UtilXml.addChildElementValue(rootElement, "GrossOunces", packagePoundsOunces[1].toString(), packageDocument); UtilXml.addChildElementValue(rootElement, "ContentType", "MERCHANDISE", packageDocument); UtilXml.addChildElementValue(rootElement, "Agreement", "N", packageDocument); UtilXml.addChildElementValue(rootElement, "ImageType", "PDF", packageDocument); // TODO: Try the different layouts UtilXml.addChildElementValue(rootElement, "ImageType", "ALLINONEFILE", packageDocument); UtilXml.addChildElementValue(rootElement, "CustomerRefNo", fromCustomsReference, packageDocument); // Add the shipping contents Element shippingContents = UtilXml.addChildElement(rootElement, "ShippingContents", packageDocument); for (GenericValue shipmentPackageContent : shipmentPackageContents) { Element itemDetail = UtilXml.addChildElement(shippingContents, "ItemDetail", packageDocument); GenericValue product = null; GenericValue originGeo = null; try { GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem", false); product = shipmentItem.getRelatedOne("Product", false); originGeo = product.getRelatedOne("OriginGeo", false); } catch (GenericEntityException e) { Debug.logInfo(e, module); } UtilXml.addChildElementValue(itemDetail, "Description", product.getString("productName"), packageDocument); UtilXml.addChildElementValue(itemDetail, "Quantity", shipmentPackageContent .getBigDecimal("quantity").setScale(0, BigDecimal.ROUND_CEILING).toPlainString(), packageDocument); String packageContentValue = ShipmentWorker.getShipmentPackageContentValue(shipmentPackageContent) .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); UtilXml.addChildElementValue(itemDetail, "Value", packageContentValue, packageDocument); BigDecimal productWeight = ProductWorker.getProductWeight(product, "WT_lbs", delegator, dispatcher); Integer[] productPoundsOunces = convertPoundsToPoundsOunces(productWeight); UtilXml.addChildElementValue(itemDetail, "NetPounds", productPoundsOunces[0].toString(), packageDocument); UtilXml.addChildElementValue(itemDetail, "NetOunces", productPoundsOunces[1].toString(), packageDocument); UtilXml.addChildElementValue(itemDetail, "HSTariffNumber", "", packageDocument); UtilXml.addChildElementValue(itemDetail, "CountryOfOrigin", originGeo.getString("geoName"), packageDocument); } // Send the request Document responseDocument = null; String api = certify ? "PriorityMailIntlCertify" : "PriorityMailIntl"; try { responseDocument = sendUspsRequest(api, requestDocument, delegator, shipmentGatewayConfigId, resource, locale); } catch (UspsRequestException e) { Debug.logInfo(e, module); return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelSendingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } Element responseElement = responseDocument.getDocumentElement(); // TODO: No mention of error returns in the docs String labelImageString = UtilXml.childElementValue(responseElement, "LabelImage"); if (UtilValidate.isEmpty(labelImageString)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementLabelImage", locale)); } shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes())); String trackingCode = UtilXml.childElementValue(responseElement, "BarcodeNumber"); if (UtilValidate.isEmpty(trackingCode)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementBarcodeNumber", locale)); } shipmentPackageRouteSeg.set("trackingCode", trackingCode); try { shipmentPackageRouteSeg.store(); } catch (GenericEntityException e) { Debug.logError(e, module); } } return ServiceUtil.returnSuccess(); }
From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java
/** * Handles locking and identifying proper root and namespaces that used to * take place in super class./*w w w.j av a2 s . c o m*/ * * @param person * @param profile * @return * @ */ private Document _safeGetUserLayout(IPerson person, IUserProfile profile) { Document layoutDoc; Tuple<String, String> key = null; final Cache<Tuple<String, String>, Document> layoutCache = getLayoutImportExportCache(); if (layoutCache != null) { key = new Tuple<String, String>(person.getUserName(), profile.getProfileFname()); layoutDoc = layoutCache.getIfPresent(key); if (layoutDoc != null) { return (Document) layoutDoc.cloneNode(true); } } layoutDoc = super.getPersonalUserLayout(person, profile); Element layout = layoutDoc.getDocumentElement(); layout.setAttribute(Constants.NS_DECL, Constants.NS_URI); if (layoutCache != null && key != null) { layoutCache.put(key, (Document) layoutDoc.cloneNode(true)); } return layoutDoc; }
From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java
/** * Returns the layout for a user. This method overrides the same * method in the superclass to return a composite layout for non * fragment owners and a regular layout for layout owners. A * composite layout is made up of layout pieces from potentially * multiple incorporated layouts. If no layouts are defined then * the composite layout will be the same as the user's personal * layout fragment or PLF, the one holding only those UI elements * that they own or incorporated elements that they have been * allowed to changed./*w w w .j ava 2 s.c om*/ **/ private DistributedUserLayout _getUserLayout(IPerson person, IUserProfile profile) { final String userName = (String) person.getAttribute("username"); final FragmentDefinition ownedFragment = this.fragmentUtils.getFragmentDefinitionByOwner(person); final boolean isLayoutOwnerDefault = this.isLayoutOwnerDefault(person); final Set<String> fragmentNames = new LinkedHashSet<String>(); final Document ILF; final Document PLF = this.getPLF(person, profile); // If this user is an owner then ownedFragment will be non null. For // fragment owners and owners of any default layout from which a // fragment owners layout is copied there should not be any imported // distributed layouts. Instead, load their PLF, mark as an owned // if a fragment owner, and return. if (ownedFragment != null || isLayoutOwnerDefault) { ILF = (Document) PLF.cloneNode(true); final Element layoutNode = ILF.getDocumentElement(); final Element ownerDocument = layoutNode.getOwnerDocument().getDocumentElement(); final NodeList channelNodes = ownerDocument.getElementsByTagName("channel"); for (int i = 0; i < channelNodes.getLength(); i++) { Element channelNode = (Element) channelNodes.item(i); final Node chanIdNode = channelNode.getAttributeNode("chanID"); if (chanIdNode == null || MissingPortletDefinition.CHANNEL_ID.equals(chanIdNode.getNodeValue())) { channelNode.getParentNode().removeChild(channelNode); } } if (ownedFragment != null) { fragmentNames.add(ownedFragment.getName()); layoutNode.setAttributeNS(Constants.NS_URI, Constants.ATT_FRAGMENT_NAME, ownedFragment.getName()); logger.debug("User '{}' is owner of '{}' fragment.", userName, ownedFragment.getName()); } else if (isLayoutOwnerDefault) { layoutNode.setAttributeNS(Constants.NS_URI, Constants.ATT_IS_TEMPLATE_USER, "true"); layoutNode.setAttributeNS(Constants.NS_URI, Constants.ATT_TEMPLATE_LOGIN_ID, (String) person.getAttribute("username")); } } else { final Locale locale = profile.getLocaleManager().getLocales()[0]; final List<FragmentDefinition> applicableFragmentDefinitions = this.fragmentUtils .getFragmentDefinitionsApplicableToPerson(person); final List<Document> applicableLayouts = this.fragmentUtils .getFragmentDefinitionUserViewLayouts(applicableFragmentDefinitions, locale); final IntegrationResult integrationResult = new IntegrationResult(); ILF = this.createCompositeILF(person, PLF, applicableLayouts, integrationResult); // push optimizations made during merge back into db. if (integrationResult.isChangedPLF()) { if (logger.isDebugEnabled()) { logger.debug("Saving PLF for {} due to changes during merge.", person.getAttribute(IPerson.USERNAME)); } super.setUserLayout(person, profile, PLF, false); } fragmentNames.addAll(this.fragmentUtils.getFragmentNames(applicableFragmentDefinitions)); } return this.createDistributedUserLayout(person, profile, ILF, fragmentNames); }
From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java
/** Replaces the layout Document stored on a fragment definition with a new version. This is called when a fragment owner updates their layout. */// w w w .jav a 2 s . c om private void updateCachedLayout(Document layout, IUserProfile profile, FragmentDefinition fragment) { final Locale locale = profile.getLocaleManager().getLocales()[0]; // need to make a copy that we can fragmentize layout = (Document) layout.cloneNode(true); // Fix later to handle multiple profiles final Element root = layout.getDocumentElement(); final UserView userView = this.fragmentUtils.getUserView(fragment, locale); if (userView == null) { throw new IllegalStateException("No UserView found for fragment: " + fragment.getName()); } root.setAttribute(Constants.ATT_ID, Constants.FRAGMENT_ID_USER_PREFIX + userView.getUserId() + Constants.FRAGMENT_ID_LAYOUT_PREFIX + "1"); try { this.fragmentActivator.clearChacheForOwner(fragment.getOwnerId()); this.fragmentUtils.getUserView(fragment, locale); } catch (final Exception e) { logger.error("An exception occurred attempting to update a layout.", e); } }
From source file:org.cruxframework.crux.core.declarativeui.crossdevice.CrossDevices.java
/** * // w w w. j ava 2 s . c o m * @param deviceAdaptive * @param device * @return */ public static Document getDeviceAdaptiveTemplate(String deviceAdaptive, Device device, boolean clone) { if (templates == null) { initialize(); } Document document = templates.get(deviceAdaptive + "_" + device.toString()); if (document != null) { document = (Document) document.cloneNode(true); } return document; }
From source file:org.cruxframework.crux.core.declarativeui.template.Templates.java
/** * /*from w w w. ja v a2 s . com*/ * @param library * @param id * @return */ public static Document getTemplate(String library, String id, boolean clone) { if (!initialized) { initialize(); } Document document = templates.get(library + "_" + id); if (document != null) { document = (Document) document.cloneNode(true); } return document; }
From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java
/** * Returns the layout for a user. This method overrides the same * method in the superclass to return a composite layout for non * fragment owners and a regular layout for layout owners. A * composite layout is made up of layout pieces from potentially * multiple incorporated layouts. If no layouts are defined then * the composite layout will be the same as the user's personal * layout fragment or PLF, the one holding only those UI elements * that they own or incorporated elements that they have been * allowed to changed./* ww w . j a v a 2 s.c o m*/ **/ private DistributedUserLayout _getUserLayout(IPerson person, IUserProfile profile) { final String userName = (String) person.getAttribute("username"); final FragmentDefinition ownedFragment = this.getOwnedFragment(person); final boolean isLayoutOwnerDefault = this.isLayoutOwnerDefault(person); // if this user is an owner then ownedFragment will be non null. For // fragment owners and owners of any default layout from which a // fragment owners layout is copied there should not be any imported // distributed layouts. Instead, load their plf, mark as an owned // if a fragment owner, and return. if (ownedFragment != null || isLayoutOwnerDefault) { Document PLF, ILF = null; PLF = this._safeGetUserLayout(person, profile); ILF = (Document) PLF.cloneNode(true); final Element layoutNode = ILF.getDocumentElement(); if (ownedFragment != null) { layoutNode.setAttributeNS(Constants.NS_URI, Constants.ATT_FRAGMENT_NAME, ownedFragment.getName()); if (LOG.isDebugEnabled()) { LOG.debug("User '" + userName + "' is owner of '" + ownedFragment.getName() + "' fragment."); } } else if (isLayoutOwnerDefault) { layoutNode.setAttributeNS(Constants.NS_URI, Constants.ATT_IS_TEMPLATE_USER, "true"); layoutNode.setAttributeNS(Constants.NS_URI, Constants.ATT_TEMPLATE_LOGIN_ID, (String) person.getAttribute("username")); } // cache in person as PLF for storage later like normal users person.setAttribute(Constants.PLF, PLF); return new DistributedUserLayout(ILF); } return this.getCompositeLayout(person, profile); }
From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java
/** Replaces the layout Document stored on a fragment definition with a new version. This is called when a fragment owner updates their layout. *//*w w w. j av a 2s .com*/ private void updateCachedLayout(Document layout, IUserProfile profile, FragmentDefinition fragment) { final Locale locale = profile.getLocaleManager().getLocales()[0]; // need to make a copy that we can fragmentize layout = (Document) layout.cloneNode(true); final FragmentActivator activator = this.getFragmentActivator(); // Fix later to handle multiple profiles final Element root = layout.getDocumentElement(); final UserView userView = activator.getUserView(fragment, locale); if (userView == null) { throw new IllegalStateException("No UserView found for fragment: " + fragment.getName()); } root.setAttribute(Constants.ATT_ID, Constants.FRAGMENT_ID_USER_PREFIX + userView.getUserId() + Constants.FRAGMENT_ID_LAYOUT_PREFIX + "1"); try { activator.clearChacheForOwner(fragment.getOwnerId()); activator.getUserView(fragment, locale); } catch (final Exception e) { LOG.error("An exception occurred attempting to update a layout.", e); } }