List of usage examples for org.apache.commons.lang StringUtils startsWith
public static boolean startsWith(String str, String prefix)
Check if a String starts with a specified prefix.
From source file:org.jahia.services.content.JCRPropertyWrapperImpl.java
public Property getProperty() throws ItemNotFoundException, ValueFormatException, RepositoryException { Value value = getValue();/*from w w w . j a v a 2s .c o m*/ Value pathValue = ValueHelper.convert(value, PropertyType.PATH, session.getValueFactory()); String path = pathValue.getString(); boolean absolute = StringUtils.startsWith(path, "/"); return (absolute) ? session.getProperty(path) : getParent().getProperty(path); }
From source file:org.jahia.services.content.JCRSessionWrapper.java
private boolean checkCyclicReference(String path, String reference) { try {/*from ww w .ja va 2s.c o m*/ int lastIndexOfDeref = StringUtils.lastIndexOf(path, DEREF_SEPARATOR); while (lastIndexOfDeref != -1 || StringUtils.startsWith(path, reference + "/") || StringUtils.equals(path, reference)) { if (lastIndexOfDeref != -1) { path = StringUtils.substring(path, 0, lastIndexOfDeref); JCRNodeWrapper referencedNode = (JCRNodeWrapper) getNode(path).getProperty(Constants.NODE) .getNode(); if (StringUtils.equals(referencedNode.getPath(), reference)) { return true; } } else { return true; } lastIndexOfDeref = StringUtils.lastIndexOf(path, DEREF_SEPARATOR); } } catch (RepositoryException e) { logger.debug("unable to check cyclic reference between node {} and its reference {}", new String[] { path, reference }, e); // do nothing } return false; }
From source file:org.jahia.services.importexport.ExternalUsersImportUpdater.java
public File updateImport(File importFile, String fileName, String fileType) { Map<String, String> pathMapping = new HashMap<String, String>(); File newImportFile = null;//from w w w . j a v a 2s .c o m ZipInputStream zin = null; OutputStream out = null; ZipOutputStream zout = null; boolean updated = false; try { newImportFile = File.createTempFile("import", ".zip"); zin = importFile.isDirectory() ? new DirectoryZipInputStream(importFile) : new NoCloseZipInputStream(new BufferedInputStream(new FileInputStream(importFile))); out = new FileOutputStream(newImportFile); zout = new ZipOutputStream(out); while (true) { ZipEntry zipentry = zin.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (LIVE_REPOSITORY_XML.equals(name) || REPOSITORY_XML.equals(name)) { zout.putNextEntry(new ZipEntry(name)); if ("users.zip".equalsIgnoreCase(fileName)) { updated |= transform(zin, zout, pathMapping); } else { updated |= clean(zin, zout, pathMapping); } } } if (!updated) { FileUtils.deleteQuietly(newImportFile); return importFile; } zin.closeEntry(); if (zin instanceof NoCloseZipInputStream) { ((NoCloseZipInputStream) zin).reallyClose(); } zin = importFile.isDirectory() ? new DirectoryZipInputStream(importFile) : new NoCloseZipInputStream(new BufferedInputStream(new FileInputStream(importFile))); while (true) { ZipEntry zipentry = zin.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (!LIVE_REPOSITORY_XML.equals(name) && !REPOSITORY_XML.equals(name)) { if (name.startsWith(LIVE_CONTENT + "/")) { for (String key : pathMapping.keySet()) { if (StringUtils.startsWith(name, LIVE_CONTENT + key)) { name = StringUtils.replace(name, LIVE_CONTENT + key, LIVE_CONTENT + pathMapping.get(key)); break; } } } else if (name.startsWith(CONTENT + "/")) { for (String key : pathMapping.keySet()) { if (StringUtils.startsWith(name, CONTENT + key)) { name = StringUtils.replace(name, CONTENT + key, CONTENT + pathMapping.get(key)); break; } } } File content = File.createTempFile("content", null); IOUtils.copy(zin, new FileOutputStream(content)); zout.putNextEntry(new ZipEntry(name)); IOUtils.copy(new FileInputStream(content), zout); } } JCRSessionFactory.getInstance().getCurrentUserSession().getPathMapping().putAll(pathMapping); return newImportFile; } catch (IOException | RepositoryException | ParserConfigurationException | XPathExpressionException | SAXException | TransformerException e) { logger.error("An error occurred while updating import file", e); } finally { try { if (zout != null) { zout.closeEntry(); zout.finish(); } if (out != null) { out.close(); } if (zin != null) { zin.closeEntry(); if (zin instanceof NoCloseZipInputStream) { ((NoCloseZipInputStream) zin).reallyClose(); } } } catch (IOException e) { logger.debug("Stream already closed", e); } } FileUtils.deleteQuietly(newImportFile); return importFile; }
From source file:org.jahia.services.importexport.LegacyImportHandler.java
/** * Receive notification of the start of an element. * <p/>/*from www. j a va 2s . co m*/ * <p> * By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each * element (such as allocating a new tree node or writing output to a file). * </p> * * @param uri The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being * performed. * @param localName The local name (without prefix), or the empty string if Namespace processing is not being performed. * @param qName The qualified name (with prefix), or the empty string if qualified names are not available. * @param attributes The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object. * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { int ctx = -1; String uuid = null; try { currentNode = localName; uuid = attributes.getValue("jcr:uuid"); if (!currentCtx.isEmpty()) { ctx = currentCtx.peek().ctx.peek(); } if (logger.isDebugEnabled()) { logger.debug(StringUtils.repeat(" ", level) + "<" + currentNode + "> , ctx = " + ctx); } level++; final Map<String, String> creationMetadata = getMetadataForNodeCreation(attributes); if (ctx == -1) { if (HTTP_WWW_JAHIA_ORG.equals(uri) && PAGE.equals(localName)) { createPage(attributes.getValue(Name.NS_JCR_URI, "primaryType"), attributes.getValue("jahia:title"), attributes.getValue("jahia:template"), attributes.getValue(HTTP_WWW_JAHIA_ORG, "pageKey"), uuid, creationMetadata, attributes.getValue("jahia:pid"), attributes.getValue("jcr:mixinTypes"), getAdditionalProperties(attributes.getValue("jcr:additionalProperties"))); setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl")); setMetadata(attributes); setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings")); return; } else if (HTTP_WWW_JAHIA_ORG.equals(uri) && EMPTY.equals(localName)) { logger.warn("The site " + currentSiteNode.getDisplayableName() + " was not published in language " + locale + ", nothing to import"); return; } logger.error("Unexpected root markup: <" + uri + ":" + localName + " /> for site" + currentSiteNode.getDisplayableName()); return; } switch (ctx) { case CTX_PAGE: if (localName.endsWith("List") && getCurrentContentType() != null && getCurrentContentType().getChildNodeDefinitionsAsMap() .containsKey(StringUtils.substringBeforeLast(localName, "List"))) { // Must be a container list ExtendedNodeDefinition nodeDef = getCurrentContentType().getChildNodeDefinitionsAsMap() .get(StringUtils.substringBeforeLast(localName, "List")); createContentList(nodeDef, uuid, creationMetadata, attributes); setMetadata(attributes); setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl")); setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings")); } else { logger.error("Unexpected " + localName + " element (" + uuid + ") in import file - skipping it and its subtree (more info in debug mode)"); if (logger.isDebugEnabled() && localName.endsWith("List")) { if (getCurrentContentType() == null) { logger.debug("CurrentContentType is null!"); } else { logger.debug( "Only the following elements are allowed sccording to the source definitions: " + getCurrentContentType().getChildNodeDefinitionsAsMap().keySet() .toString()); } } currentCtx.peek().pushSkip(); } break; case CTX_CTN: if (localName.endsWith("List") && getCurrentContentType() != null && getCurrentContentType().getChildNodeDefinitionsAsMap() .containsKey(StringUtils.substringBeforeLast(localName, "List"))) { // Must be a container list ExtendedNodeDefinition nodeDef = getCurrentContentType().getChildNodeDefinitionsAsMap() .get(StringUtils.substringBeforeLast(localName, "List")); try { createContentList(nodeDef, uuid, creationMetadata, attributes); if (currentCtx.peek().ctx.peek() != CTX_DIRECTSUBNODES) { setMetadata(attributes); setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl")); setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings")); } } catch (ConstraintViolationException cve) { logger.error( "Error when creating contentList with def={} (localname={} , uuid={} , currentContentType={})", new Object[] { nodeDef.getName(), localName, uuid, getCurrentContentType().getName() }); } } else { logger.debug("create field " + localName); ExtendedItemDefinition itemDef; if (getCurrentContentType().getChildNodeDefinitionsAsMap().containsKey(localName) && getCurrentContentType().getPropertyDefinitionsAsMap().containsKey(localName)) { itemDef = getCurrentContentType().getChildNodeDefinitionsAsMap().get(localName); if (!itemDef.getDeclaringNodeType().getName() .equals(getCurrentContentType().getNodeTypeDefinition().getName())) { ExtendedItemDefinition itemDef2 = getCurrentContentType().getPropertyDefinitionsAsMap() .get(localName); if (itemDef2.getDeclaringNodeType().getName() .equals(getCurrentContentType().getNodeTypeDefinition().getName())) { itemDef = itemDef2; } } } else if (getCurrentContentType().getChildNodeDefinitionsAsMap().containsKey(localName)) { itemDef = getCurrentContentType().getChildNodeDefinitionsAsMap().get(localName); } else { itemDef = getCurrentContentType().getPropertyDefinitionsAsMap().get(localName); } if (itemDef == null) { logger.error("Definition not found for field " + localName + " in node " + getCurrentContentType().getName() + " , uuid=" + uuid); } else if (logger.isDebugEnabled()) { if (itemDef.isNode()) { logger.debug( "The field {} is a subnode of the node type {} (child node definition = {})", new Object[] { localName, getCurrentContentType().getName(), itemDef.getName() }); } else { logger.debug("The field is a property: " + localName); } } if (itemDef != null && (itemDef.isNode() || setPropertyField(getCurrentContentType(), localName, attributes.getValue("jahia:value"), creationMetadata))) { String mappedProperty = mapping.getMappedProperty(getCurrentContentType(), localName); if ("#skip".equals(mappedProperty)) { currentCtx.peek().pushSkip(); } else { currentCtx.peek().pushField(mappedProperty); } } else { if (logger.isDebugEnabled()) { logger.debug("Not imported field " + localName + ", definition not found"); StringBuilder s = new StringBuilder(); for (String def : getCurrentContentType().getChildNodeDefinitionsAsMap().keySet()) s.append(def).append(", "); logger.debug("Allowed sub definitions: " + (s.length() > 0 ? s : "none")); for (String def : getCurrentContentType().getPropertyDefinitionsAsMap().keySet()) s.append(def).append(", "); logger.debug("Allowed properties: " + (s.length() > 0 ? s : "none")); } currentCtx.peek().pushSkip(); } } break; case CTX_LIST: /** * ExtendedNodeDefinition ctnDefinition = * listType.getDeclaredUnstructuredChildNodeDefinitions().values().iterator().next(); ExtendedNodeType ctnType = * ctnDefinition.getRequiredPrimaryTypes()[0]; */ String pt = attributes.getValue(Name.NS_JCR_URI, "primaryType"); if (pt == null && StringUtils.startsWith(originatingJahiaRelease, "5")) { pt = qName; } createContent(pt, uuid, attributes.getValue("jahia:jahiaLinkActivation_picker_relationship"), creationMetadata, attributes.getValue("jcr:mixinTypes"), getAdditionalProperties(attributes.getValue("jcr:additionalProperties"))); setMetadata(attributes); setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl")); setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings")); break; case CTX_FIELD: setNodeField(uri, localName, uuid, attributes); break; case CTX_SHAREABLE: if ("#shareableSource".equals(mapping.getMappedNode(getCurrentContentType(), localName))) { createShareableNode(attributes.getValue("jahia:value")); } else { currentCtx.peek().pushSkip(); } break; case CTX_SKIP: currentCtx.peek().pushSkip(); break; case CTX_NAVLINK: currentCtx.peek().pushNavLink(getCurrentContentType(), attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl")); currentCtx.peek().properties.peek().putAll(convertToProperties(attributes)); final JCRNodeWrapper page = currentCtx.peek().contents.peek(); String title = attributes.getValue("jahia:title"); if (HTTP_WWW_JAHIA_ORG.equals(uri) && PAGE.equals(localName)) { String acl = null; if (logger.isDebugEnabled()) { logger.debug("page acls: " + currentCtx.peek().acls.toString()); } for (String a : currentCtx.peek().acls) { if (a != null) { acl = a; } } if (attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl") != null) { acl = attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"); } Map<String, String> props = currentCtx.peek().properties.peek(); createPage(attributes.getValue(Name.NS_JCR_URI, "primaryType"), title, attributes.getValue("jahia:template"), attributes.getValue(HTTP_WWW_JAHIA_ORG, "pageKey"), uuid, creationMetadata, attributes.getValue("jahia:pid"), attributes.getValue("jcr:mixinTypes"), getAdditionalProperties(attributes.getValue("jcr:additionalProperties"))); setMetadata(props, creationMetadata); setAcl(acl); setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings")); // todo : add a link here ?? } else if (HTTP_WWW_JAHIA_ORG.equals(uri) && LINK.equals(localName)) { createInternalLink(page, title, uuid, attributes.getValue("jahia:reference"), "jnt:nodeLink", creationMetadata, attributes.getValue("jcr:mixinTypes"), getAdditionalProperties(attributes.getValue("jcr:additionalProperties"))); } else if (HTTP_WWW_JAHIA_ORG.equals(uri) && localName.equals("url")) { createExternalLink(page, title, uuid, attributes.getValue("jahia:value"), externalLinkType, externalLinkUrlPropertyName, externalLinkInternationalized, creationMetadata, attributes.getValue("jcr:mixinTypes"), getAdditionalProperties(attributes.getValue("jcr:additionalProperties"))); } break; case CTX_DIRECTSUBNODES: String ctnPt = attributes.getValue(Name.NS_JCR_URI, "primaryType"); if (ctnPt == null && StringUtils.startsWith(originatingJahiaRelease, "5")) { ctnPt = qName; } createContent(ctnPt, uuid, attributes.getValue("jahia:jahiaLinkActivation_picker_relationship"), creationMetadata, attributes.getValue("jcr:mixinTypes"), getAdditionalProperties(attributes.getValue("jcr:additionalProperties"))); setMetadata(attributes); setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl")); setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings")); break; } } catch (RepositoryException e) { logger.error(MessageFormat.format( "Error while processing element: [uri={0}], [localName={1}], [qName={2}], [uuid={3}], [ctx={4}]", uri, localName, qName, uuid, ctx)); throw new SAXException(e); } }
From source file:org.jahia.services.importexport.LegacyImportHandler.java
private void createContent(String primaryType, String uuid, String pickerRelationshipUuid, Map<String, String> creationMetadata, String mixinsToAdd, JSONObject propertiesToSet) throws RepositoryException { ExtendedNodeType t = registry.getNodeType(primaryType); String nodeType = mapping.getMappedType(t); if (nodeType.equals("#skip")) { currentCtx.peek().pushSkip();/* w w w .jav a2 s . c o m*/ } else if (nodeType.equals("#navlink")) { currentCtx.peek().pushNavLink(t, null); } else if (nodeType.equals("#shareable")) { currentCtx.peek().pushShareable(t); } else { JCRNodeWrapper node = null; if (uuidMapping.containsKey(uuid)) { node = session.getNodeByIdentifier(uuidMapping.get(uuid)); if (pickerRelationshipUuid != null) currentCtx.peek().pushSkip(); else currentCtx.peek().pushContainer(node, t); } else if (pickerRelationshipUuid != null) { node = addOrCheckoutNode(getCurrentContentNode(), StringUtils.substringAfter(nodeType, ":") + "_" + (ctnId++), "jnt:contentReference", null, creationMetadata); final String contentRefUuid = node.getIdentifier(); uuidMapping.put(uuid, contentRefUuid); performActions(mapping.getActions(t), node, creationMetadata); if (uuidMapping.containsKey(pickerRelationshipUuid)) { final JCRNodeWrapper source = session .getNodeByIdentifier(uuidMapping.get(pickerRelationshipUuid)); node.setProperty(Constants.NODE, source); } else { if (!references.containsKey(pickerRelationshipUuid)) { references.put(pickerRelationshipUuid, new ArrayList<String>()); } references.get(pickerRelationshipUuid).add(contentRefUuid + "/" + Constants.NODE); } currentCtx.peek().pushSkip(); } else { try { ExtendedNodeType nt = NodeTypeRegistry.getInstance().getNodeType(nodeType); if (StringUtils.startsWith(originatingJahiaRelease, "5") && nt.isNodeType("jnt:nodeLink")) { currentCtx.peek().pushNavLink(getCurrentContentType(), null); return; } } catch (NoSuchNodeTypeException e) { logger.error("Unexpected nodetype " + nodeType + " - skipping it and its subtree"); currentCtx.peek().pushSkip(); return; } node = addOrCheckoutNode(getCurrentContentNode(), StringUtils.substringAfter(nodeType, ":") + "_" + (ctnId++), nodeType, null, creationMetadata); uuidMapping.put(uuid, node.getIdentifier()); performActions(mapping.getActions(t), node, creationMetadata); currentCtx.peek().pushContainer(node, t); } handleAdditionalMixinsAndProperties(node, mixinsToAdd, propertiesToSet, creationMetadata); if (currentCtx.peek().properties.peek() != null) { for (Map.Entry<String, String> entry : currentCtx.peek().properties.peek().entrySet()) { final ExtendedNodeType currentContentType = getCurrentContentType(); final String fieldName = entry.getKey(); logger.debug("About to import field {}/{}", currentContentType.getName(), fieldName); if (!setPropertyField(currentContentType, fieldName, entry.getValue(), creationMetadata) && !"#skip".equals(fieldName)) { logger.error("Not imported field {}/{}", currentContentType.getName(), fieldName); } } } } }
From source file:org.jahia.services.importexport.validation.ConstraintsValidator.java
@Override public void validate(String decodedLocalName, String decodedQName, String currentPath, Attributes atts) { // Clean up maps of processed path if (!StringUtils.startsWith(currentPath + "/", previousPath + "/")) { while (!StringUtils.startsWith(currentPath + "/", previousPath + "/") && !StringUtils.isEmpty(previousPath)) { parentType.remove(previousPath); parentMixins.remove(previousPath); previousPath = StringUtils.substringBeforeLast(previousPath, "/"); }/*from www .j ava2 s. c o m*/ } previousPath = currentPath; String primaryType = atts.getValue(Constants.JCR_PRIMARYTYPE); String mixinTypes = atts.getValue(Constants.JCR_MIXINTYPES); Set<String> mixins = new HashSet<>(); if (mixinTypes != null) { mixins.addAll(Arrays.asList(mixinTypes.split(COMMA_SPLIT_REGEX))); } // hold the primary type and mixins when processing translation nodes boolean isI18n = Constants.JAHIANT_TRANSLATION.equals(primaryType); if (isI18n) { currentPath = StringUtils.substringBeforeLast(currentPath, "/"); if (parentMixins.get(currentPath) != null) { mixins.addAll(parentMixins.get(currentPath)); } primaryType = parentType.get(currentPath); } else { parentType.put(currentPath, primaryType); parentMixins.put(currentPath, mixins); } checkTypeConstraints(primaryType, currentPath, atts, isI18n); for (String mixin : mixins) { checkTypeConstraints(mixin, currentPath, atts, isI18n); } }
From source file:org.jahia.services.notification.HtmlExternalizationService.java
protected String processCss(String previousOut, String serverUrl, HttpServletRequest request, HttpServletResponse response) {//w w w .j av a 2 s. co m Source source = new Source(previousOut); OutputDocument document = new OutputDocument(source); StringBuilder sb = new StringBuilder(); List<StartTag> linkStartTags = source.getAllStartTags(HTMLElementName.LINK); for (StartTag linkTag : linkStartTags) { Attributes attributes = linkTag.getAttributes(); String rel = attributes.getValue("rel"); if (rel == null || !"stylesheet".equalsIgnoreCase(rel)) { continue; } String href = attributes.getValue("href"); if (href == null) { continue; } String styleSheetContent = null; try { if (useServletContextResources || request == null || response == null) { if (request != null && StringUtils.startsWith(href, request.getContextPath())) { href = StringUtils.substringAfter(href, request.getContextPath()); } if (href.startsWith("/modules/")) { String after = StringUtils.substringAfter(href, "/modules/"); String module = StringUtils.substringBefore(after, "/"); JahiaTemplatesPackage pack = ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackageById(module); if (pack != null) { String prefix = "/modules/" + module; if (!href.startsWith(prefix)) { href = prefix + "/" + StringUtils.substringAfter(after, "/"); } styleSheetContent = StringUtils.join(IOUtils.readLines( pack.getResource(StringUtils.substringAfter(after, "/")).getInputStream()), '\n'); } } else { styleSheetContent = httpClientService.getResourceAsString(href); } } else { styleSheetContent = httpClientService.getResourceAsString(href, request, response); } } catch (Exception e) { logger.warn("Unable to retrieve resource content for " + href + ".Cause: " + e.getMessage(), e); } if (StringUtils.isNotEmpty(styleSheetContent)) { sb.setLength(0); sb.append("<style"); Attribute typeAttribute = attributes.get("type"); if (typeAttribute != null) { sb.append(' ').append(typeAttribute); } if (rewriteUrlsInCss) { String baseUrl = HttpClientService.isAbsoluteUrl(href) ? href : serverUrl + href; baseUrl = StringUtils.substringBeforeLast(baseUrl, "/") + "/"; styleSheetContent = rewriteCssUrls(styleSheetContent, baseUrl); } sb.append(">\n"); if (request != null && Boolean.valueOf(request.getParameter("debug"))) { sb.append("/* ").append(href).append(" */\n"); } sb.append(styleSheetContent).append("\n</style>"); document.replace(linkTag, sb.toString()); } } return document.toString(); }
From source file:org.jahia.services.query.QueryModifierAndOptimizerVisitor.java
private AbstractQOMNode getNewPropertyBasedNodeIfRequired(String selectorName, String propertyName, AbstractQOMNode node) throws RepositoryException { Selector selector = getSelector(getOriginalSource(), selectorName); if (selector == null) { return node; }/* ww w . j a v a 2s. c o m*/ try { if (getModificationInfo().getMode() == TraversingMode.CHECK_FOR_MODIFICATION_MODE || getModificationInfo().getMode() == TraversingMode.MODIFY_MODE) { // check for language dependent modifications and use the translation selector on // jnt:translation node if user specified it in query if (getSelectorsJoinedWithTranslation().get(selector.getSelectorName()) != null) { selector = getSelectorsJoinedWithTranslation().get(selector.getSelectorName()); } Set<String> languageCodes = getLanguagesPerSelector().get(selector.getSelectorName()); if (((languageCodes == null || languageCodes.isEmpty()) && session != null && session.getLocale() != null) && !(Constants.NT_QUERY.equals(selector.getNodeTypeName()) || Constants.JAHIANT_QUERY.equals(selector.getNodeTypeName()))) { if (getModificationInfo().getMode() == TraversingMode.CHECK_FOR_MODIFICATION_MODE) { Set<String> newLanguageCodes = getNewLanguagesPerSelector().get(selector.getSelectorName()); if (newLanguageCodes == null) { newLanguageCodes = new HashSet<String>(); newLanguageCodes.add(session.getLocale().toString()); newLanguageCodes.add(NO_LOCALE); getNewLanguagesPerSelector().put(selector.getSelectorName(), newLanguageCodes); } if (newLanguageCodes.contains(NO_LOCALE)) { ExtendedNodeType nodeType = NodeTypeRegistry.getInstance() .getNodeType(selector.getNodeTypeName()); ExtendedPropertyDefinition propDef = propertyName != null ? getPropertyDefinition(nodeType, selector, propertyName) : null; if (!Constants.JAHIANT_FILE.equals(selector.getNodeTypeName()) && propDef != null && propDef.isInternationalized()) { newLanguageCodes.remove(NO_LOCALE); } } getModificationInfo().setModificationNecessary(true); } else { QueryObjectModelFactory qomFactory = getModificationInfo().getQueryObjectModelFactory(); Set<String> newLanguageCodes = getNewLanguagesPerSelector().get(selector.getSelectorName()); if (newLanguageCodes != null) { Constraint langConstraint = null; for (String newLanguageCode : newLanguageCodes) { Constraint currentConstraint = NO_LOCALE.equals(newLanguageCode) ? qomFactory.not(qomFactory.propertyExistence(selector.getSelectorName(), Constants.JCR_LANGUAGE)) : qomFactory.comparison( qomFactory.propertyValue(selector.getSelectorName(), Constants.JCR_LANGUAGE), QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO, qomFactory.literal(getValueFactory().createValue(newLanguageCode))); langConstraint = langConstraint == null ? currentConstraint : qomFactory.or(langConstraint, currentConstraint); } getModificationInfo().getNewConstraints().add(langConstraint); if (languageCodes == null) { languageCodes = new HashSet<String>(); getLanguagesPerSelector().put(selector.getSelectorName(), languageCodes); } languageCodes.addAll(newLanguageCodes); } } } if (node instanceof Column) { String columnName = ((Column) node).getColumnName(); if (StringUtils.startsWith(columnName, "rep:facet(") && !StringUtils.contains(columnName, "locale=")) { if (getModificationInfo().getMode() == TraversingMode.CHECK_FOR_MODIFICATION_MODE) { getModificationInfo().setModificationNecessary(true); } else { String facetOptions = columnName.substring("rep:facet(".length()); if (languageCodes == null) { languageCodes = getNewLanguagesPerSelector().get(selector.getSelectorName()); } String languageCode = null; if (languageCodes != null) { for (String currentLanguageCode : languageCodes) { if (!NO_LOCALE.equals(currentLanguageCode)) { languageCode = currentLanguageCode; break; } } } if (!StringUtils.isEmpty(languageCode)) { columnName = "rep:facet(locale=" + languageCode + (facetOptions.trim().length() > 1 ? "&" : "") + facetOptions; QueryObjectModelFactory qomFactory = getModificationInfo() .getQueryObjectModelFactory(); node = (AbstractQOMNode) qomFactory.column(selector.getSelectorName(), propertyName, columnName); } } } } } } catch (NoSuchNodeTypeException e) { QueryServiceImpl.logger.debug("Type " + selector.getNodeTypeName() + " not found in registry", e); } return node; }
From source file:org.jahia.services.seo.VanityUrl.java
/** * Initializes an instance of this class. * @param url mapping URL//from w w w . jav a 2 s . c om * @param site virtual site of the mapped content object * @param language the mapping language */ public VanityUrl(String url, String site, String language) { super(); this.url = StringUtils.stripEnd(StringUtils.startsWith(url, "/") ? url : '/' + url, "/"); this.site = site; this.language = language; }
From source file:org.jahia.services.sites.JahiaSitesService.java
/** * Remove a site; if the removed site is the default one: * - the first other site found will become the default * - if no other site found, no default site anymore * * @param siteToRemove the JahiaSite bean to be removed *///from ww w. ja v a2 s . c o m public synchronized void removeSite(final JahiaSite siteToRemove) throws JahiaException { final String siteKeyToRemove = siteToRemove.getSiteKey(); String serverName = siteToRemove.getServerName(); try { // First delete all groups JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Boolean>() { @Override public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { for (String groupPath : groupService.getGroupList(siteKeyToRemove)) { if (StringUtils.startsWith(groupPath, siteToRemove.getJCRLocalPath() + "/groups/") && !StringUtils.startsWith(groupPath, siteToRemove.getJCRLocalPath() + "/groups/providers/")) { groupService.deleteGroup(groupPath, session); } } session.save(); return true; } }); // Now let's delete the site. JCRCallback<Boolean> deleteCallback = new JCRCallback<Boolean>() { @Override public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { JCRNodeWrapper sites = session.getNode(SITES_JCR_PATH); if (!sites.isCheckedOut()) { session.checkout(sites); } JCRNodeWrapper siteNode = sites.getNode(siteKeyToRemove); // check if we need to update the default site if (Constants.EDIT_WORKSPACE.equals(session.getWorkspace().getName()) && StringUtils .equals(sites.getPropertyAsString(DEFAULT_SITE_PROPERTY), siteNode.getIdentifier())) { // our site is the default one: we search for a next candidate for the default site // if there is no one found the "j:defaultSite" is removed from the /sites node sites.setProperty(DEFAULT_SITE_PROPERTY, getFirstSiteFound(session, SYSTEM_SITE_KEY, siteKeyToRemove)); } siteNode.remove(); session.save(); return true; } }; JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(null, Constants.LIVE_WORKSPACE, null, deleteCallback); JCRTemplate.getInstance().doExecuteWithSystemSession(deleteCallback); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } finally { invalidateCache(siteKeyToRemove, serverName); } }