List of usage examples for org.apache.commons.lang StringUtils substringBefore
public static String substringBefore(String str, String separator)
Gets the substring before the first occurrence of a separator.
From source file:org.apache.jackrabbit.core.query.lucene.JahiaLuceneQueryFactoryImpl.java
private boolean checkIndexedAcl(Map<String, Boolean> checkedAcls, IndexedNodeInfo infos) throws RepositoryException { boolean canRead = true; String[] acls = infos.getAclUuid() != null ? Patterns.SPACE.split(infos.getAclUuid()) : ArrayUtils.EMPTY_STRING_ARRAY; ArrayUtils.reverse(acls);//from ww w . j av a 2 s . co m for (String acl : acls) { if (acl.contains("/")) { // ACL indexed contains a single user ACE, get the username String singleUser = StringUtils.substringAfter(acl, "/"); acl = StringUtils.substringBefore(acl, "/"); if (singleUser.contains("/")) { // Granted roles are specified in the indexed entry String roles = StringUtils.substringBeforeLast(singleUser, "/"); singleUser = StringUtils.substringAfterLast(singleUser, "/"); if (!singleUser.equals(session.getUserID())) { // If user does not match, skip this ACL continue; } else { // If user matches, check if one the roles gives the read permission for (String role : StringUtils.split(roles, '/')) { if (((JahiaAccessManager) session.getAccessControlManager()).matchPermission( Sets.newHashSet(Privilege.JCR_READ + "_" + session.getWorkspace().getName()), role)) { // User and role matches, read is granted return true; } } } } else { if (!singleUser.equals(session.getUserID())) { // If user does not match, skip this ACL continue; } // Otherwise, do normal ACL check. } } // Verify first if this acl has already been checked Boolean aclChecked = checkedAcls.get(acl); if (aclChecked == null) { try { canRead = session.getAccessManager().canRead(null, new NodeId(acl)); checkedAcls.put(acl, canRead); } catch (RepositoryException e) { } } else { canRead = aclChecked; } break; } return canRead; }
From source file:org.apache.jackrabbit.core.query.lucene.JahiaLuceneQueryFactoryImpl.java
private Query resolveSingleMixedInclusiveExclusiveRangeQuery(String expression) { Query qobj = null;// w w w . j a v a 2 s.c o m boolean inclusiveEndRange = expression.endsWith("]"); boolean exclusiveEndRange = expression.endsWith("}"); int inclusiveBeginRangeCount = StringUtils.countMatches(expression, "["); int exclusiveBeginRangeCount = StringUtils.countMatches(expression, "{"); if (((inclusiveEndRange && exclusiveBeginRangeCount == 1 && inclusiveBeginRangeCount == 0) || (exclusiveEndRange && inclusiveBeginRangeCount == 1 && exclusiveBeginRangeCount == 0))) { String fieldName = (inclusiveEndRange || exclusiveEndRange) ? StringUtils.substringBefore(expression, inclusiveEndRange ? ":{" : ":[") : ""; if (fieldName.indexOf(' ') == -1) { fieldName = fieldName.replace("\\:", ":"); String rangeExpression = StringUtils.substringBetween(expression, inclusiveEndRange ? "{" : "[", inclusiveEndRange ? "]" : "}"); String part1 = StringUtils.substringBefore(rangeExpression, " TO"); String part2 = StringUtils.substringAfter(rangeExpression, "TO "); SchemaField sf = new SchemaField(fieldName, JahiaQueryParser.STRING_TYPE); qobj = JahiaQueryParser.STRING_TYPE.getRangeQuery(null, sf, part1.equals("*") ? null : part1, part2.equals("*") ? null : part2, !inclusiveEndRange, inclusiveEndRange); } } return qobj; }
From source file:org.apache.jackrabbit.core.query.lucene.JahiaSearchIndex.java
@Override protected void doInit() throws IOException { Set<Name> ignoredTypes = new HashSet<>(); NameFactory nf = NameFactoryImpl.getInstance(); if (SKIP_VERSION_INDEX && isVersionIndex()) { ignoredTypes.add(nf.create(Name.NS_REP_URI, "versionStorage")); ignoredTypes.add(nf.create(Name.NS_NT_URI, "versionHistory")); ignoredTypes.add(nf.create(Name.NS_NT_URI, "version")); ignoredTypes.add(nf.create(Name.NS_NT_URI, "versionLabels")); ignoredTypes.add(nf.create(Name.NS_NT_URI, "frozenNode")); ignoredTypes.add(nf.create(Name.NS_NT_URI, "versionedChild")); }/* w ww .j a va2 s. c o m*/ if (ignoredTypesString != null) { for (String s : StringUtils.split(ignoredTypesString, ", ")) { try { if (!s.startsWith("{")) { try { ignoredTypes.add(nf.create( getContext().getNamespaceRegistry().getURI(StringUtils.substringBefore(s, ":")), StringUtils.substringAfter(s, ":"))); } catch (NamespaceException e) { log.error("Cannot parse namespace for " + s, e); } } else { ignoredTypes.add(nf.create(s)); } } catch (IllegalArgumentException iae) { log.error("Illegal node type name: " + s, iae); } } } this.ignoredTypes = ignoredTypes.isEmpty() ? null : ignoredTypes; super.doInit(); }
From source file:org.apache.jackrabbit.server.JahiaBasicCredentialsProvider.java
/** * Creates the {@link SimpleCredentials} object for the provided username and password considering the impersonation case. * /*from w w w.j a v a 2 s. co m*/ * @param user * the received username * @param password * the user password * @return the {@link SimpleCredentials} object for the provided username and password considering the impersonation case */ protected Credentials createCredentials(String user, char[] password) { SimpleCredentials credentials = null; if (user != null && user.contains(IMPERSONATOR)) { credentials = new SimpleCredentials(StringUtils.substringBefore(user, IMPERSONATOR), ArrayUtils.EMPTY_CHAR_ARRAY); credentials.setAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE, new SimpleCredentials(StringUtils.substringAfter(user, IMPERSONATOR), password)); } else { credentials = new SimpleCredentials(user, password); } return credentials; }
From source file:org.apache.maven.archetype.ui.generation.ArchetypeSelectorUtils.java
private static String extractGroupIdFromFilter(String filter) { return StringUtils.contains(filter, ':') ? StringUtils.substringBefore(filter, ":") : null; }
From source file:org.apache.nutch.crawl.SeedGenerator.java
public static void main(String[] args) throws Exception { String urlFormat = "http://oumen.com/detail.php?atid={{{1000,4460}}}"; String[] urlParts = urlFormat.split("\\{\\{\\{\\d+\\,\\d+\\}\\}\\}"); String[] placeholders = StringUtils.substringsBetween(urlFormat, "{{{", "}}}"); ArrayList<ArrayList<Integer>> ranges = Lists.newArrayList(); for (int i = 0; i < placeholders.length; ++i) { int min = Integer.parseInt(StringUtils.substringBefore(placeholders[i], ",")); int max = Integer.parseInt(StringUtils.substringAfter(placeholders[i], ",")); ranges.add(Lists.newArrayList(min, max)); }/* w w w. j a va 2s .com*/ // we can support only one placeholder right now StringBuilder content = new StringBuilder(); for (int i = ranges.get(0).get(0); i <= ranges.get(0).get(1); ++i) { String url = urlParts[0] + i; if (urlParts.length > 1) { url += urlParts[1]; } content.append(url); content.append("\n"); } String tidyDomain = NetUtil.getTopLevelDomain(urlFormat); String file = StringUtils.substringBefore(tidyDomain, ".").toLowerCase().replaceAll("[^a-z]", "_"); file = "/tmp/" + file + ".txt"; FileUtils.writeStringToFile(new File(file), content.toString(), "utf-8"); System.out.println("url seed results are saved in : " + file); }
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;/*from w w w . j av a 2s . c o m*/ 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 { 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.apache.ranger.audit.provider.MiscUtil.java
/** * * @param principal/*from w w w . j av a 2 s .c o m*/ * This could be in the format abc/host@domain.com * @return */ static public String getShortNameFromPrincipalName(String principal) { if (principal == null) { return null; } try { // Assuming it is kerberos name for now KerberosName kerbrosName = new KerberosName(principal); String userName = kerbrosName.getShortName(); userName = StringUtils.substringBefore(userName, "/"); userName = StringUtils.substringBefore(userName, "@"); return userName; } catch (Throwable t) { logger.error("Error converting kerberos name. principal=" + principal + ", KerberosName.rules=" + KerberosName.getRules()); } return principal; }
From source file:org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer.java
@Override public boolean authorize(Session session, Operation operation, Resource resource) { if (rangerPlugin == null) { MiscUtil.logErrorMessageByInterval(logger, "Authorizer is still not initialized"); return false; }/*from w ww .j ava2s. c o m*/ // TODO: If resource type is consumer group, then allow it by default if (resource.resourceType().equals(Group$.MODULE$)) { if (logger.isDebugEnabled()) { logger.debug("If resource type is consumer group, then we allow it by default! Returning true"); } return true; } String userName = null; if (session.principal() != null) { userName = session.principal().getName(); userName = StringUtils.substringBefore(userName, "/"); userName = StringUtils.substringBefore(userName, "@"); } java.util.Set<String> userGroups = MiscUtil.getGroupsForRequestUser(userName); String ip = session.clientAddress().getHostAddress(); // skip leading slash if (StringUtils.isNotEmpty(ip) && ip.charAt(0) == '/') { ip = ip.substring(1); } Date eventTime = new Date(); String accessType = mapToRangerAccessType(operation); boolean validationFailed = false; String validationStr = ""; if (accessType == null) { if (MiscUtil.logErrorMessageByInterval(logger, "Unsupported access type. operation=" + operation)) { logger.fatal("Unsupported access type. session=" + session + ", operation=" + operation + ", resource=" + resource); } validationFailed = true; validationStr += "Unsupported access type. operation=" + operation; } String action = accessType; RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl(); rangerRequest.setUser(userName); rangerRequest.setUserGroups(userGroups); rangerRequest.setClientIPAddress(ip); rangerRequest.setAccessTime(eventTime); RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl(); rangerRequest.setResource(rangerResource); rangerRequest.setAccessType(accessType); rangerRequest.setAction(action); rangerRequest.setRequestData(resource.name()); if (resource.resourceType().equals(Topic$.MODULE$)) { rangerResource.setValue(KEY_TOPIC, resource.name()); } else if (resource.resourceType().equals(Cluster$.MODULE$)) { //NOPMD // CLUSTER should go as null // rangerResource.setValue(KEY_CLUSTER, resource.name()); } else if (resource.resourceType().equals(Group$.MODULE$)) { rangerResource.setValue(KEY_CONSUMER_GROUP, resource.name()); } else { logger.fatal("Unsupported resourceType=" + resource.resourceType()); validationFailed = true; } boolean returnValue = false; if (validationFailed) { MiscUtil.logErrorMessageByInterval(logger, validationStr + ", request=" + rangerRequest); } else { try { RangerAccessResult result = rangerPlugin.isAccessAllowed(rangerRequest); if (result == null) { logger.error("Ranger Plugin returned null. Returning false"); } else { returnValue = result.getIsAllowed(); } } catch (Throwable t) { logger.error("Error while calling isAccessAllowed(). request=" + rangerRequest, t); } } if (logger.isDebugEnabled()) { logger.debug("rangerRequest=" + rangerRequest + ", return=" + returnValue); } return returnValue; }
From source file:org.apache.sling.its.servlets.ItsImportServlet.java
/** * Store the element and its attribute. The child node of global rules are * specially handled so they will not be traversed. * * @param path//from w w w . jav a 2 s. co m * the target path * @param resourceType * the resourceType * @param doc * the document * @param file * the file. * @param isExternalDoc * true if this is for storing global rules for external documents */ private void store(String path, final String resourceType, final Document doc, final File file, final boolean isExternalDoc) { final ITraversal itsEng = applyITSRules(doc, file, null, false); itsEng.startTraversal(); Node node; while ((node = itsEng.nextNode()) != null) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: final Element element = (Element) node; // Use !backTracking() to get to the elements only once // and to include the empty elements (for attributes). if (itsEng.backTracking()) { if (!SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) { path = backTrack(path); } } else { if (element.isSameNode(doc.getDocumentElement()) && !isExternalDoc) { path += "/" + element.getNodeName(); output(path, null, null); setAttributes(element, path); } else if (SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) { storeGlobalRule(element, resourceType, itsEng); } else if (!isExternalDoc && !SlingItsConstants.getGlobalRules().containsKey(element.getLocalName()) && !(element.getParentNode().getLocalName().equals(SlingItsConstants.ITS_RULES) && element.getParentNode().getPrefix() != null)) { if (element.getLocalName().equals(SlingItsConstants.ITS_RULES) && element.getPrefix() != null) { this.hasGlobalRules = true; } if (element.getPrefix() != null) { path += String.format("/%s(%d)", element.getLocalName(), getCounter(path + "/" + element.getLocalName())); element.setAttribute(SlingItsConstants.NODE_PREFIX, element.getPrefix()); } else if (element.getNodeName().equals("link") && StringUtils.endsWith(element.getAttribute("rel"), "-rules")) { path += String.format("/%s(%d)", SlingItsConstants.ITS_RULES, getCounter(path + "/" + SlingItsConstants.ITS_RULES)); final String prefix = StringUtils.substringBefore(element.getAttribute("rel"), "-rules"); element.setAttribute(SlingItsConstants.NODE_PREFIX, prefix); element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, SlingItsConstants.XMLNS + prefix, Namespaces.ITS_NS_URI); element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:h", Namespaces.HTML_NS_URI); element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:jcr", NamespaceRegistry.NAMESPACE_JCR); this.hasGlobalRules = true; } else { path += String.format("/%s(%d)", element.getNodeName(), getCounter(path + "/" + element.getNodeName())); } output(path, null, null); setAttributes(element, path); if (!element.hasChildNodes()) // Empty elements: { path = backTrack(path); } } } break; case Node.TEXT_NODE: if (StringUtils.isNotBlank(node.getNodeValue()) && !isExternalDoc) { path += String.format("/%s(%d)", SlingItsConstants.TEXT_CONTENT_NODE, getCounter(path + "/" + SlingItsConstants.TEXT_CONTENT_NODE)); output(path, null, node.getNodeValue()); path = backTrack(path); } break; default: break; } } }