List of usage examples for org.xml.sax Attributes getIndex
public int getIndex(String qName);
From source file:org.jahia.services.importexport.DocumentViewImportHandler.java
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (error > 0) { error++;/*from ww w. j ava 2 s . c om*/ return; } batchCount++; // do a session.save each maxBatch if (batchCount > maxBatch) { try { ReferencesHelper.resolveCrossReferences(session, references, false); session.save(JCRObservationManager.IMPORT); batchCount = 0; } catch (CompositeConstraintViolationException e) { logger.error("Constraint violation exception", e); throw new SAXException("Cannot save batch", e); } catch (ConstraintViolationException e) { if (e.getMessage().contains("mandatory child node") && nodes.size() > 1 && e.getMessage().startsWith(nodes.peek().getPath())) { // save on the next node when next node is needed (like content node for files) batchCount = maxBatch - 1; } else { throw new SAXException("Cannot save batch", e); } } catch (RepositoryException e) { throw new SAXException("Cannot save batch", e); } } if (ugcLevel > 0 || "live".equals(atts.getValue("j:originWS"))) { if (importUserGeneratedContent) { ugcLevel++; } else { error++; return; } } if (atts.getIndex(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR) > -1) { String providerKey = atts.getValue(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR); Map<String, JCRStoreProvider> providers = JCRSessionFactory.getInstance().getProviders(); if (!providers.containsKey(providerKey) || !providers.get(providerKey).isAvailable()) { error++; return; } } if (atts.getIndex(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR) > -1) { try { String providerKey = session .getNode(atts.getValue(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR)).getIdentifier(); Map<String, JCRStoreProvider> providers = JCRSessionFactory.getInstance().getProviders(); if (!providers.containsKey(providerKey) || !providers.get(providerKey).isAvailable()) { error++; return; } } catch (RepositoryException e) { error++; return; } } String decodedLocalName = ISO9075.decode(localName); for (Map.Entry<Pattern, String> entry : replacements.entrySet()) { decodedLocalName = entry.getKey().matcher(decodedLocalName).replaceAll(entry.getValue()); } String decodedQName = qName.replace(localName, decodedLocalName); if (rootBehavior == ROOT_BEHAVIOUR_RENAME && pathes.size() <= 1 && !pathMapping.containsKey(pathes.peek() + "/" + decodedQName)) { String newName = JCRContentUtils.findAvailableNodeName(nodes.peek(), decodedQName); if (!decodedQName.equals(newName)) { pathMapping.put(nodes.peek().getPath() + "/" + decodedQName + "/", nodes.peek().getPath() + "/" + newName + "/"); decodedQName = newName; } } if (rootBehavior == ROOT_BEHAVIOUR_IGNORE && pathes.size() <= 1) { session.getPathMapping().put("/" + decodedQName + "/", nodes.peek().getPath().equals("/") ? "/" : nodes.peek().getPath() + "/"); pathes.push(""); return; } pathes.push(pathes.peek() + "/" + decodedQName); try { if (ignorePath != null) { nodes.push(null); return; } String path; if (nodes.peek().getPath().equals("/")) { path = "/" + decodedQName; } else { path = nodes.peek().getPath() + "/" + decodedQName; } if (pathes.peek().startsWith("/users/") && "jnt:user".equals(atts.getValue("jcr:primaryType"))) { Matcher m = Pattern.compile("/users/([^/]+)").matcher(pathes.peek()); if (m.matches()) { path = JahiaUserManagerService.getInstance().getUserSplittingRule() .getPathForUsername(m.group(1)); } } String pt = atts.getValue(Constants.JCR_PRIMARYTYPE); // Create missing structure for group members if ("jnt:member".equals(pt) && nodes.peek().isNodeType("jnt:members") && "j:members".equals(nodes.peek().getName())) { String memberRef = atts.getValue("j:member"); if (memberRef != null) { String referenceValue = getReferenceValue(memberRef); JCRNodeWrapper principal; if (referenceValue.startsWith("/")) { for (String key : pathMapping.keySet()) { if (referenceValue.startsWith(key)) { referenceValue = StringUtils.replace(referenceValue, key, pathMapping.get(key)); break; } } principal = session.getNode(referenceValue); } else { principal = session.getNodeByIdentifier(memberRef); } JCRGroupNode groupNode = JahiaGroupManagerService.getInstance().lookupGroupByPath( StringUtils.substringBeforeLast(nodes.peek().getPath(), "/"), session); JCRNodeWrapper member = groupNode.addMember(principal); if (member != null) { uuids.add(member.getIdentifier()); } nodes.push(member); return; } } if (pathMapping.containsKey(path + "/")) { path = StringUtils.substringBeforeLast(pathMapping.get(path + "/"), "/"); decodedQName = StringUtils.substringAfter(path, "/"); } if (noSubNodesImport.contains(pt)) { ignorePath = path; } JCRNodeWrapper child = null; boolean isValid = true; try { child = session.getNode(path); if (child.hasPermission("jcr:versionManagement") && child.isVersioned() && !child.isCheckedOut()) { session.checkout(child); } } catch (PathNotFoundException e) { isValid = false; } if (!importUserGeneratedContent || ugcLevel > 0) { String originalUuid = atts.getValue("jcr:uuid"); String uuid = originalUuid; if (uuid != null && uuidMapping.containsKey(uuid)) { uuid = uuidMapping.get(uuid); } else if (enforceUuid) { uuid = null; } if (isValid && enforceUuid && uuid != null) { if (!child.getIdentifier().equals(uuid)) { child.remove(); isValid = false; } } if (!isValid || (child.getDefinition() != null && child.getDefinition().allowsSameNameSiblings())) { isValid = false; if (nodes.peek().hasPermission("jcr:addChildNodes")) { if ("jnt:acl".equals(pt) && !nodes.peek().isNodeType("jmix:accessControlled")) { nodes.peek().addMixin("jmix:accessControlled"); } Calendar created = null; String createdBy = null; Calendar lastModified = null; String lastModifiedBy = null; if (!StringUtils.isEmpty(atts.getValue("jcr:created"))) { created = ISO8601.parse(atts.getValue("jcr:created")); } if (!StringUtils.isEmpty(atts.getValue("jcr:lastModified"))) { lastModified = ISO8601.parse(atts.getValue("jcr:lastModified")); } if (!StringUtils.isEmpty(atts.getValue("jcr:createdBy"))) { createdBy = atts.getValue("jcr:createdBy"); } if (!StringUtils.isEmpty(atts.getValue("jcr:lastModifiedBy"))) { lastModifiedBy = atts.getValue("jcr:lastModifiedBy"); } // String share = atts.getValue("j:share"); // if (!StringUtils.isEmpty(uuid) && uuidMapping.containsKey(uuid)) { // child = nodes.peek().clone(session.getNodeByUUID(uuidMapping.get(uuid)), decodedQName); // } else if (!StringUtils.isEmpty(share)) { // for (Map.Entry<String, String> entry : pathMapping.entrySet()) { // if (share.startsWith(entry.getKey())) { // share = entry.getValue() + StringUtils.substringAfter(share, entry.getKey()); // break; // } // } // child = nodes.peek().clone(session.getNode(share), decodedQName); // } else { if (!StringUtils.isEmpty(uuid)) { switch (uuidBehavior) { case IMPORT_UUID_COLLISION_THROW: try { JCRNodeWrapper node = session.getNodeByUUID(uuid); if (node.isNodeType("mix:shareable")) { // .. } else { throw new ItemExistsException(uuid); } } catch (ItemNotFoundException e) { } case IMPORT_UUID_COLLISION_REMOVE_EXISTING: try { JCRNodeWrapper node = session.getNodeByUUID(uuid); // make sure conflicting node is not importTargetNode or an ancestor thereof if (nodes.peek().getPath().startsWith(node.getPath())) { String msg = "cannot remove ancestor node"; logger.debug(msg); throw new ConstraintViolationException(msg); } // remove conflicting node.remove(); } catch (ItemNotFoundException e) { } break; case IMPORT_UUID_COLLISION_REPLACE_EXISTING: throw new UnsupportedOperationException(); case IMPORT_UUID_CREATE_NEW: uuid = null; break; case IMPORT_UUID_COLLISION_MOVE_EXISTING: try { JCRNodeWrapper node = session.getNodeByUUID(uuid); // make sure conflicting node is not importTargetNode or an ancestor thereof if (nodes.peek().getPath().startsWith(node.getPath())) { String msg = "cannot move ancestor node"; logger.debug(msg); throw new ConstraintViolationException(msg); } if (!node.getPath().equals(path)) { // move conflicting session.move(node.getPath(), path); node = session.getNodeByUUID(uuid); } child = node; isValid = true; } catch (ItemNotFoundException e) { } break; } } if (!isValid) { try { session.checkout(nodes.peek()); } catch (PathNotFoundException e) { logger.error("Couldn't find parent node " + nodes.peek(), e); } try { checkDependencies(path, pt, atts); child = nodes.peek().addNode(decodedQName, pt, uuid, created, createdBy, lastModified, lastModifiedBy); } catch (ConstraintViolationException e) { if (pathes.size() <= 2 && nodes.peek().getName().equals(decodedQName) && nodes.peek().getPrimaryNodeTypeName().equals(pt)) { session.getPathMapping().put("/" + decodedQName, nodes.peek().getPath().equals("/") ? "" : nodes.peek().getPath()); return; } else { throw e; } } } addMixins(child, atts); uploadFile(atts, decodedQName, path, child); setAttributes(child, atts); uuids.add(child.getIdentifier()); if (child.isFile() && currentFilePath == null) { currentFilePath = child.getPath(); } if (child.isNodeType(Constants.JAHIANT_MOUNTPOINT)) { session.save(JCRObservationManager.IMPORT); } // } } else { throw new AccessDeniedException( "Missing jcr:addChildNodes permission for user " + session.getUser().getName()); } } else { if (child.hasPermission("jcr:modifyProperties") && child.isCheckedOut()) { if (!noUpdateTypes.contains(child.getPrimaryNodeType().getName()) && atts.getValue("jcr:primaryType") != null) { addMixins(child, atts); setAttributes(child, atts); uploadFile(atts, decodedQName, path, child); } } uuids.add(child.getIdentifier()); } if (originalUuid != null) { uuidMapping.put(originalUuid, child.getIdentifier()); } if (nodes.peek().getPrimaryNodeType().hasOrderableChildNodes() && nodes.peek().hasPermission("jcr:write") && !JCRSessionFactory.getInstance().getMountPoints().containsKey(child.getPath())) { nodes.peek().orderBefore(decodedQName, null); } } if (child == null) { error++; } else { nodes.push(child); } } catch (NoSuchNodeTypeException e) { if (logger.isDebugEnabled()) { logger.warn("Cannot import " + pathes.pop(), e); } else { logger.warn("Cannot import \"{}\" due to missing node type definition \"{}\"", pathes.pop(), e.getMessage()); } error++; } catch (AccessDeniedException e) { if (logger.isDebugEnabled()) { logger.warn("Cannot import " + pathes.pop() + getLocation(), e); } else { logger.warn("Cannot import \"{}\" due to \"{}\"", pathes.pop(), e.getMessage()); } error++; } catch (RepositoryException re) { logger.error("Cannot import " + pathes.pop() + getLocation(), re); error++; } catch (Exception re) { throw new SAXException(re); } }
From source file:org.jahia.services.importexport.validation.ProviderAvailabilityValidator.java
@Override public void validate(String decodedLocalName, String decodedQName, String currentPath, Attributes atts) { String path = StringUtils.removeStart(currentPath, "/content"); if (StringUtils.isNotBlank(path)) { visitedPaths.add(path);//ww w .jav a 2 s . com } String type = atts.getValue("jcr:primaryType"); try { if (type != null && NodeTypeRegistry.getInstance().getNodeType(type).isNodeType(Constants.JAHIANT_MOUNTPOINT)) { neededMountPoint.add(type); } } catch (NoSuchNodeTypeException e) { // Ignore } if (atts.getIndex(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR) > -1) { neededStaticProviders.add(atts.getValue(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR)); } if (atts.getIndex(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR) > -1) { neededDynamicProviders.add(atts.getValue(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR)); } }
From source file:org.jajuk.base.Collection.java
/** * Called when we start an element intern() method use policy : we use this * method when adding a new string into JVM that will probably be referenced * by several objects like the Genre ID that is referenced by many tracks. In * this case, all the String objects share the same char[]. On another hand, * it musn't be used for strings that have low probability to be used several * times (like raw names) as it uses a lot of CPU (equals() is called) and we * want startup to be as fast as possible. Note that the use of intern() save * around 1/4 of overall heap memory/*from ww w . j ava 2s . co m*/ * * We use sax-interning for the main items sections (<styles> for ie). For all * raw items, we don't perform equals on item name but we compare the string * hashcode * * @param sUri * @param s * @param sQName * @param attributes * * @throws SAXException the SAX exception */ @Override public void startElement(String sUri, String s, String sQName, Attributes attributes) throws SAXException { try { int idIndex = attributes.getIndex(Const.XML_ID); // [PERF] Manage top tags to set current stage. Manages 'properties' // tags as well if (idIndex == -1) { // Note that we compare string with '==' for performance reasons and it is safe here. if (Const.XML_DEVICES == sQName) { //NOSONAR manager = DeviceManager.getInstance(); stage = Stage.STAGE_DEVICES; needCheckID = true; } else if (Const.XML_ALBUMS == sQName) {//NOSONAR manager = AlbumManager.getInstance(); stage = Stage.STAGE_ALBUMS; needCheckID = true; } else if (Const.XML_ARTISTS == sQName) {//NOSONAR manager = ArtistManager.getInstance(); stage = Stage.STAGE_ARTISTS; needCheckID = true; } else if (Const.XML_ALBUM_ARTISTS == sQName) {//NOSONAR manager = AlbumArtistManager.getInstance(); stage = Stage.STAGE_ALBUM_ARTIST; needCheckID = true; } else if (Const.XML_DIRECTORIES == sQName) {//NOSONAR manager = DirectoryManager.getInstance(); stage = Stage.STAGE_DIRECTORIES; needCheckID = true; } else if (Const.XML_FILES == sQName) {//NOSONAR manager = FileManager.getInstance(); stage = Stage.STAGE_FILES; needCheckID = true; } else if (Const.XML_PLAYLISTS == sQName) {//NOSONAR // This code is here for Jajuk < 1.6 compatibility manager = PlaylistManager.getInstance(); stage = Stage.STAGE_PLAYLISTS; needCheckID = true; } else if (Const.XML_PLAYLIST_FILES == sQName) {//NOSONAR manager = PlaylistManager.getInstance(); stage = Stage.STAGE_PLAYLIST_FILES; needCheckID = true; } else if (Const.XML_GENRES == sQName) {//NOSONAR manager = GenreManager.getInstance(); stage = Stage.STAGE_GENRES; needCheckID = true; } else if (Const.XML_TRACKS == sQName) {//NOSONAR manager = TrackManager.getInstance(); stage = Stage.STAGE_TRACKS; needCheckID = true; } else if (Const.XML_YEARS == sQName) {//NOSONAR manager = YearManager.getInstance(); stage = Stage.STAGE_YEARS; needCheckID = true; } else if (Const.XML_TYPES == sQName) {//NOSONAR // This is here for pre-1.7 collections, after we don't commit types // anymore (they are set programmatically) manager = TypeManager.getInstance(); stage = Stage.STAGE_TYPES; needCheckID = false; } else if (Const.XML_PROPERTY == sQName) {//NOSONAR // A property description boolean bCustom = Boolean .parseBoolean(attributes.getValue(attributes.getIndex(Const.XML_CUSTOM))); boolean bConstructor = Boolean .parseBoolean(attributes.getValue(attributes.getIndex(Const.XML_CONSTRUCTOR))); boolean bShouldBeDisplayed = Boolean .parseBoolean(attributes.getValue(attributes.getIndex(Const.XML_VISIBLE))); boolean bEditable = Boolean .parseBoolean(attributes.getValue(attributes.getIndex(Const.XML_EDITABLE))); boolean bUnique = Boolean .parseBoolean(attributes.getValue(attributes.getIndex(Const.XML_UNIQUE))); Class<?> cType = Class.forName(attributes.getValue(Const.XML_TYPE)); String sDefaultValue = attributes.getValue(Const.XML_DEFAULT_VALUE).intern(); Object oDefaultValue = null; if (sDefaultValue != null && sDefaultValue.length() > 0) { try { // Date format has changed from 1.3 (only yyyyMMdd // addition format is used) // so an exception will be thrown when upgrading // from 1.2 // we reset default value to "today" oDefaultValue = UtilString.parse(sDefaultValue, cType); } catch (ParseException e) { oDefaultValue = new Date(); } } String sPropertyName = attributes.getValue(Const.XML_NAME).intern(); if (manager.getMetaInformation(sPropertyName) == null) { PropertyMetaInformation meta = new PropertyMetaInformation(sPropertyName, bCustom, bConstructor, bShouldBeDisplayed, bEditable, bUnique, cType, oDefaultValue); // standard properties are already loaded manager.registerProperty(meta); } } if (Const.XML_PROPERTY == sQName) {//NOSONAR Log.debug("Found property: " + attributes.getValue(Const.XML_NAME)); } else { Log.debug("Starting stage: '" + stage + "' with property: '" + sQName + "' manager: " + (manager != null ? manager.getXMLTag() : "<null>")); } } else { // Manage elements themselves using a switch for performances switch (stage) { case STAGE_FILES: handleFiles(attributes, idIndex); break; case STAGE_DIRECTORIES: handleDirectories(attributes, idIndex); break; case STAGE_TRACKS: handleTracks(attributes, idIndex); break; case STAGE_ALBUMS: handleAlbums(attributes, idIndex); break; case STAGE_ARTISTS: handleArtists(attributes, idIndex); break; case STAGE_ALBUM_ARTIST: handleAlbumArtists(attributes, idIndex); break; case STAGE_GENRES: handleGenres(attributes, idIndex); break; case STAGE_PLAYLIST_FILES: handlePlaylistFiles(attributes, idIndex); break; case STAGE_DEVICES: handleDevices(attributes, idIndex); break; case STAGE_YEARS: handleYears(attributes, idIndex); break; case STAGE_TYPES: Log.warn("Unexpected Stage: STAGE_TYPES"); break; default: Log.warn("Unexpected Stage: " + stage); } } } catch (Throwable e) {//NOSONAR // Make sure to catch every issue here (including runtime exceptions) so we make sure to start // jajuk StringBuilder sAttributes = new StringBuilder(); for (int i = 0; i < attributes.getLength(); i++) { sAttributes.append('\n').append(attributes.getQName(i)).append('=').append(attributes.getValue(i)); } Log.error(5, sAttributes.toString(), e); } }
From source file:org.xwiki.portlet.view.HTMLIdAttributeXMLFilter.java
/** * Rewrites the value of the {@link #ID_ATTRIBUTES} in the given list of attributes. * //from w w w .j a va 2 s.c o m * @param attributes the list of element attributes * @return the given list of attributes where the value of the {@link #ID_ATTRIBUTES} have been changed */ private Attributes rewriteIds(Attributes attributes) { Attributes newAttributes = null; for (String idAttribute : ID_ATTRIBUTES) { int index = attributes.getIndex(idAttribute); if (index >= 0) { if (newAttributes == null) { newAttributes = attributes instanceof AttributesImpl ? attributes : new AttributesImpl(attributes); } ((AttributesImpl) newAttributes).setValue(index, namespace(attributes.getValue(index))); } } return newAttributes != null ? newAttributes : attributes; }
From source file:org.xwiki.portlet.view.HTMLIdAttributeXMLFilter.java
/** * Rewrites URL fragments in anchor URLs relative to the current page. * // ww w.ja v a 2s . c om * @param atts the lists of element attributes * @return the given list of attributes where the value of the {@link #HREF} attribute has been changed */ private Attributes rewriteURLFragment(Attributes atts) { String href = atts.getValue(HREF); if (href != null && href.startsWith("#")) { AttributesImpl newAtts = atts instanceof AttributesImpl ? (AttributesImpl) atts : new AttributesImpl(atts); newAtts.setValue(atts.getIndex(HREF), String.format("#%s", namespace(href.substring(1)))); return newAtts; } return atts; }