List of usage examples for org.apache.commons.lang StringUtils substringBeforeLast
public static String substringBeforeLast(String str, String separator)
Gets the substring before the last occurrence of a separator.
From source file:org.apache.archiva.metadata.repository.storage.maven2.RepositoryModelResolver.java
private boolean getModelFromProxy(RemoteRepository remoteRepository, String groupId, String artifactId, String version, String filename) throws AuthorizationException, TransferFailedException, ResourceDoesNotExistException, WagonFactoryException, XMLException, IOException { boolean success = false; File tmpMd5 = null;/*from w ww. j a v a2 s.com*/ File tmpSha1 = null; File tmpResource = null; String artifactPath = pathTranslator.toPath(groupId, artifactId, version, filename); File resource = new File(targetRepository.getLocation(), artifactPath); File workingDirectory = createWorkingDirectory(targetRepository.getLocation()); try { Wagon wagon = null; try { String protocol = getProtocol(remoteRepository.getUrl()); final NetworkProxy networkProxy = this.networkProxyMap.get(remoteRepository.getId()); wagon = wagonFactory .getWagon(new WagonFactoryRequest("wagon#" + protocol, remoteRepository.getExtraHeaders()) .networkProxy(networkProxy)); if (wagon == null) { throw new RuntimeException("Unsupported remote repository protocol: " + protocol); } boolean connected = connectToRepository(wagon, remoteRepository); if (connected) { tmpResource = new File(workingDirectory, filename); if (VersionUtil.isSnapshot(version)) { // get the metadata first! File tmpMetadataResource = new File(workingDirectory, METADATA_FILENAME); String metadataPath = StringUtils.substringBeforeLast(artifactPath, "/") + "/" + METADATA_FILENAME; wagon.get(addParameters(metadataPath, remoteRepository), tmpMetadataResource); log.debug("Successfully downloaded metadata."); ArchivaRepositoryMetadata metadata = MavenMetadataReader.read(tmpMetadataResource); // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename SnapshotVersion snapshotVersion = metadata.getSnapshotVersion(); String timestampVersion = version; if (snapshotVersion != null) { timestampVersion = timestampVersion.substring(0, timestampVersion.length() - 8); // remove SNAPSHOT from end timestampVersion = timestampVersion + snapshotVersion.getTimestamp() + "-" + snapshotVersion.getBuildNumber(); filename = artifactId + "-" + timestampVersion + ".pom"; artifactPath = pathTranslator.toPath(groupId, artifactId, version, filename); log.debug("New artifactPath :{}", artifactPath); } } log.info("Retrieving {} from {}", artifactPath, remoteRepository.getName()); wagon.get(addParameters(artifactPath, remoteRepository), tmpResource); log.debug("Downloaded successfully."); tmpSha1 = transferChecksum(wagon, remoteRepository, artifactPath, tmpResource, workingDirectory, ".sha1"); tmpMd5 = transferChecksum(wagon, remoteRepository, artifactPath, tmpResource, workingDirectory, ".md5"); } } finally { if (wagon != null) { try { wagon.disconnect(); } catch (ConnectionException e) { log.warn("Unable to disconnect wagon.", e); } } } if (resource != null) { synchronized (resource.getAbsolutePath().intern()) { File directory = resource.getParentFile(); moveFileIfExists(tmpMd5, directory); moveFileIfExists(tmpSha1, directory); moveFileIfExists(tmpResource, directory); success = true; } } } finally { FileUtils.deleteQuietly(workingDirectory); } // do we still need to execute the consumers? return success; }
From source file:org.apache.archiva.rest.services.DefaultBrowseService.java
@Override public Boolean artifactAvailable(String groupId, String artifactId, String version, String classifier, String repositoryId) throws ArchivaRestServiceException { List<String> selectedRepos = getSelectedRepos(repositoryId); boolean snapshot = VersionUtil.isSnapshot(version); try {/*from w w w. j a v a2 s.c o m*/ for (String repoId : selectedRepos) { ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository(repoId); if ((snapshot && !managedRepository.isSnapshots()) || (!snapshot && managedRepository.isSnapshots())) { continue; } ManagedRepositoryContent managedRepositoryContent = repositoryContentFactory .getManagedRepositoryContent(repoId); // FIXME default to jar which can be wrong for war zip etc.... ArchivaArtifact archivaArtifact = new ArchivaArtifact(groupId, artifactId, version, StringUtils.isEmpty(classifier) ? "" : classifier, "jar", repoId); File file = managedRepositoryContent.toFile(archivaArtifact); if (file != null && file.exists()) { return true; } // in case of SNAPSHOT we can have timestamped version locally ! if (StringUtils.endsWith(version, VersionUtil.SNAPSHOT)) { File metadataFile = new File(file.getParent(), MetadataTools.MAVEN_METADATA); if (metadataFile.exists()) { try { ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader .read(metadataFile); int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber(); String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp(); // rebuild file name with timestamped version and build number String timeStampFileName = new StringBuilder(artifactId).append('-') // .append(StringUtils.remove(version, "-" + VersionUtil.SNAPSHOT)) // .append('-').append(timeStamp) // .append('-').append(Integer.toString(buildNumber)) // .append((StringUtils.isEmpty(classifier) ? "" : "-" + classifier)) // .append(".jar").toString(); File timeStampFile = new File(file.getParent(), timeStampFileName); log.debug("try to find timestamped snapshot version file: {}", timeStampFile.getPath()); if (timeStampFile.exists()) { return true; } } catch (XMLException e) { log.warn("skip fail to find timestamped snapshot file: {}", e.getMessage()); } } } String path = managedRepositoryContent.toPath(archivaArtifact); file = connectors.fetchFromProxies(managedRepositoryContent, path); if (file != null && file.exists()) { // download pom now String pomPath = StringUtils.substringBeforeLast(path, ".jar") + ".pom"; connectors.fetchFromProxies(managedRepositoryContent, pomPath); return true; } } } catch (RepositoryAdminException e) { log.error(e.getMessage(), e); throw new ArchivaRestServiceException(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e); } catch (RepositoryException e) { log.error(e.getMessage(), e); throw new ArchivaRestServiceException(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e); } return false; }
From source file:org.apache.archiva.rest.services.DefaultBrowseService.java
protected List<ArtifactContentEntry> readFileEntries(File file, String filterPath, String repoId) throws IOException { Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>(); int filterDepth = StringUtils.countMatches(filterPath, "/"); /*if ( filterDepth == 0 ) {/*from ww w . j a v a2s .c om*/ filterDepth = 1; }*/ JarFile jarFile = new JarFile(file); try { Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries(); while (jarEntryEnumeration.hasMoreElements()) { JarEntry currentEntry = jarEntryEnumeration.nextElement(); String cleanedEntryName = StringUtils.endsWith(currentEntry.getName(), "/") ? // StringUtils.substringBeforeLast(currentEntry.getName(), "/") : currentEntry.getName(); String entryRootPath = getRootPath(cleanedEntryName); int depth = StringUtils.countMatches(cleanedEntryName, "/"); if (StringUtils.isEmpty(filterPath) // && !artifactContentEntryMap.containsKey(entryRootPath) // && depth == filterDepth) { artifactContentEntryMap.put(entryRootPath, new ArtifactContentEntry(entryRootPath, !currentEntry.isDirectory(), depth, repoId)); } else { if (StringUtils.startsWith(cleanedEntryName, filterPath) // && (depth == filterDepth || (!currentEntry.isDirectory() && depth == filterDepth))) { artifactContentEntryMap.put(cleanedEntryName, new ArtifactContentEntry(cleanedEntryName, !currentEntry.isDirectory(), depth, repoId)); } } } if (StringUtils.isNotEmpty(filterPath)) { Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>(); for (Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet()) { filteredArtifactContentEntryMap.put(entry.getKey(), entry.getValue()); } List<ArtifactContentEntry> sorted = getSmallerDepthEntries(filteredArtifactContentEntryMap); if (sorted == null) { return Collections.emptyList(); } Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE); return sorted; } } finally { if (jarFile != null) { jarFile.close(); } } List<ArtifactContentEntry> sorted = new ArrayList<>(artifactContentEntryMap.values()); Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE); return sorted; }
From source file:org.apache.archiva.web.rss.RssFeedServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String repoId = null;//from w w w.j ava 2s .co m String groupId = null; String artifactId = null; String url = StringUtils.removeEnd(req.getRequestURL().toString(), "/"); if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") > 0) { artifactId = StringUtils.substringAfterLast(url, "/"); groupId = StringUtils.substringBeforeLast(StringUtils.substringAfter(url, "feeds/"), "/"); groupId = StringUtils.replaceChars(groupId, '/', '.'); } else if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") == 0) { // we receive feeds?babla=ded which is not correct if (StringUtils.countMatches(url, "feeds?") > 0) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url."); return; } repoId = StringUtils.substringAfterLast(url, "/"); } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url."); return; } RssFeedProcessor processor = null; try { Map<String, String> map = new HashMap<>(); SyndFeed feed = null; if (isAllowed(req, repoId, groupId, artifactId)) { if (repoId != null) { // new artifacts in repo feed request processor = newArtifactsprocessor; map.put(RssFeedProcessor.KEY_REPO_ID, repoId); } else if ((groupId != null) && (artifactId != null)) { // TODO: this only works for guest - we could pass in the list of repos // new versions of artifact feed request processor = newVersionsprocessor; map.put(RssFeedProcessor.KEY_GROUP_ID, groupId); map.put(RssFeedProcessor.KEY_ARTIFACT_ID, artifactId); } } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED); return; } RepositorySession repositorySession = repositorySessionFactory.createSession(); try { feed = processor.process(map, repositorySession.getRepository()); } finally { repositorySession.close(); } if (feed == null) { res.sendError(HttpServletResponse.SC_NO_CONTENT, "No information available."); return; } res.setContentType(MIME_TYPE); if (repoId != null) { feed.setLink(req.getRequestURL().toString()); } else if ((groupId != null) && (artifactId != null)) { feed.setLink(req.getRequestURL().toString()); } SyndFeedOutput output = new SyndFeedOutput(); output.output(feed, res.getWriter()); } catch (UserNotFoundException unfe) { log.debug(COULD_NOT_AUTHENTICATE_USER, unfe); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER); } catch (AccountLockedException acce) { res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER); } catch (AuthenticationException authe) { log.debug(COULD_NOT_AUTHENTICATE_USER, authe); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER); } catch (FeedException ex) { log.debug(COULD_NOT_GENERATE_FEED_ERROR, ex); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR); } catch (MustChangePasswordException e) { res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER); } catch (UnauthorizedException e) { log.debug(e.getMessage()); if (repoId != null) { res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository"); } else { res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId); } res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED); } }
From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java
@Override public DavResource createResource(final DavResourceLocator locator, final DavServletRequest request, final DavServletResponse response) throws DavException { ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator(locator); RepositoryGroupConfiguration repoGroupConfig = archivaConfiguration.getConfiguration() .getRepositoryGroupsAsMap().get(archivaLocator.getRepositoryId()); String activePrincipal = getActivePrincipal(request); List<String> resourcesInAbsolutePath = new ArrayList<>(); boolean readMethod = WebdavMethodUtil.isReadMethod(request.getMethod()); DavResource resource;// w w w . j a v a 2s . c om if (repoGroupConfig != null) { if (!readMethod) { throw new DavException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Write method not allowed for repository groups."); } log.debug("Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal); // handle browse requests for virtual repos if (getLogicalResource(archivaLocator, null, true).endsWith("/")) { try { DavResource davResource = getResourceFromGroup(request, repoGroupConfig.getRepositories(), archivaLocator, repoGroupConfig); setHeaders(response, locator, davResource, true); return davResource; } catch (RepositoryAdminException e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } } else { // make a copy to avoid potential concurrent modifications (eg. by configuration) // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are // infrequent List<String> repositories = new ArrayList<>(repoGroupConfig.getRepositories()); resource = processRepositoryGroup(request, archivaLocator, repositories, activePrincipal, resourcesInAbsolutePath, repoGroupConfig); } } else { try { RemoteRepository remoteRepository = remoteRepositoryAdmin .getRemoteRepository(archivaLocator.getRepositoryId()); if (remoteRepository != null) { String logicalResource = getLogicalResource(archivaLocator, null, false); IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext(remoteRepository); File resourceFile = StringUtils.equals(logicalResource, "/") ? new File(indexingContext.getIndexDirectoryFile().getParent()) : new File(indexingContext.getIndexDirectoryFile().getParent(), logicalResource); resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), // locator.getResourcePath(), // null, // request.getRemoteAddr(), // activePrincipal, // request.getDavSession(), // archivaLocator, // this, // mimeTypes, // auditListeners, // scheduler, // fileLockManager); setHeaders(response, locator, resource, false); return resource; } } catch (RepositoryAdminException e) { log.debug("RepositoryException remote repository with d'{}' not found, msg: {}", archivaLocator.getRepositoryId(), e.getMessage()); } ManagedRepositoryContent managedRepositoryContent = null; try { managedRepositoryContent = repositoryFactory .getManagedRepositoryContent(archivaLocator.getRepositoryId()); } catch (RepositoryNotFoundException e) { throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " + archivaLocator.getRepositoryId()); } catch (RepositoryException e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } log.debug("Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal); try { resource = processRepository(request, archivaLocator, activePrincipal, managedRepositoryContent, managedRepositoryAdmin.getManagedRepository(archivaLocator.getRepositoryId())); String logicalResource = getLogicalResource(archivaLocator, null, false); resourcesInAbsolutePath .add(new File(managedRepositoryContent.getRepoRoot(), logicalResource).getAbsolutePath()); } catch (RepositoryAdminException e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } } String requestedResource = request.getRequestURI(); // MRM-872 : merge all available metadata // merge metadata only when requested via the repo group if ((repositoryRequest.isMetadata(requestedResource) || repositoryRequest.isMetadataSupportFile(requestedResource)) && repoGroupConfig != null) { // this should only be at the project level not version level! if (isProjectReference(requestedResource)) { ArchivaDavResource res = (ArchivaDavResource) resource; String filePath = StringUtils .substringBeforeLast(res.getLocalResource().getAbsolutePath().replace('\\', '/'), "/"); filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml"; // for MRM-872 handle checksums of the merged metadata files if (repositoryRequest.isSupportFile(requestedResource)) { File metadataChecksum = new File( filePath + "." + StringUtils.substringAfterLast(requestedResource, ".")); if (metadataChecksum.exists()) { LogicalResource logicalResource = new LogicalResource( getLogicalResource(archivaLocator, null, false)); resource = new ArchivaDavResource(metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null, request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager); } } else { if (resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1) { // merge the metadata of all repos under group ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata(); for (String resourceAbsPath : resourcesInAbsolutePath) { try { File metadataFile = new File(resourceAbsPath); ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read(metadataFile); mergedMetadata = RepositoryMetadataMerge.merge(mergedMetadata, repoMetadata); } catch (XMLException e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while reading metadata file."); } catch (RepositoryMetadataException r) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while merging metadata file."); } } try { File resourceFile = writeMergedMetadataToFile(mergedMetadata, filePath); LogicalResource logicalResource = new LogicalResource( getLogicalResource(archivaLocator, null, false)); resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), logicalResource.getPath(), null, request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager); } catch (RepositoryMetadataException r) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while writing metadata file."); } catch (IOException ie) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while generating checksum files."); } catch (DigesterException de) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while generating checksum files." + de.getMessage()); } } } } } setHeaders(response, locator, resource, false); // compatibility with MRM-440 to ensure browsing the repository works ok if (resource.isCollection() && !request.getRequestURI().endsWith("/")) { throw new BrowserRedirectException(resource.getHref()); } resource.addLockManager(lockManager); return resource; }
From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java
private DavResource processRepositoryGroup(final DavServletRequest request, ArchivaDavResourceLocator archivaLocator, List<String> repositories, String activePrincipal, List<String> resourcesInAbsolutePath, RepositoryGroupConfiguration repoGroupConfig) throws DavException { DavResource resource = null;/*w w w . ja va 2s . com*/ List<DavException> storedExceptions = new ArrayList<>(); String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/"); String rootPath = StringUtils.substringBeforeLast(pathInfo, "/"); if (StringUtils.endsWith(rootPath, repoGroupConfig.getMergedIndexPath())) { // we are in the case of index file request String requestedFileName = StringUtils.substringAfterLast(pathInfo, "/"); File temporaryIndexDirectory = buildMergedIndexDirectory(repositories, activePrincipal, request, repoGroupConfig); File resourceFile = new File(temporaryIndexDirectory, requestedFileName); resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), requestedFileName, null, request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager); } else { for (String repositoryId : repositories) { ManagedRepositoryContent managedRepositoryContent; try { managedRepositoryContent = repositoryFactory.getManagedRepositoryContent(repositoryId); } catch (RepositoryNotFoundException e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } catch (RepositoryException e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } try { ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository(repositoryId); DavResource updatedResource = processRepository(request, archivaLocator, activePrincipal, managedRepositoryContent, managedRepository); if (resource == null) { resource = updatedResource; } String logicalResource = getLogicalResource(archivaLocator, null, false); if (logicalResource.endsWith("/")) { logicalResource = logicalResource.substring(1); } resourcesInAbsolutePath.add( new File(managedRepositoryContent.getRepoRoot(), logicalResource).getAbsolutePath()); } catch (DavException e) { storedExceptions.add(e); } catch (RepositoryAdminException e) { storedExceptions.add(new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e)); } } } if (resource == null) { if (!storedExceptions.isEmpty()) { // MRM-1232 for (DavException e : storedExceptions) { if (401 == e.getErrorCode()) { throw e; } } throw new DavException(HttpServletResponse.SC_NOT_FOUND); } else { throw new DavException(HttpServletResponse.SC_NOT_FOUND); } } return resource; }
From source file:org.apache.cocoon.components.source.impl.QDoxSource.java
/** * @see XMLizable#toSAX(org.xml.sax.ContentHandler) * @throws SAXException if any error occurs during SAX outputting. *///from w w w . ja v a 2 s .c o m public void toSAX(ContentHandler handler) throws SAXException { if (javadocClass == null) { logger.error("No classfile loaded! Cannot output SAX events."); return; } if (logger.isDebugEnabled()) { logger.debug("Outputting SAX events for class " + javadocClass.getFullyQualifiedName()); logger.debug(" #fields: " + javadocClass.getFields().length); logger.debug(" #methods and constructors: " + javadocClass.getMethods().length); } // Output SAX 'header': handler.startDocument(); handler.startPrefixMapping(NS_PREFIX, NS_URI); // Output class-level element: outputClassStartElement(handler, javadocClass); // Modifiers: outputModifiers(handler, javadocClass); // Imports: JavaSource parent = javadocClass.getParentSource(); // Add two implicit imports: parent.addImport("java.lang.*"); if (parent.getPackage() != null) { parent.addImport(parent.getPackage() + ".*"); } else { parent.addImport("*"); } String[] imports = parent.getImports(); saxStartElement(handler, IMPORTS_ELEMENT); for (int i = 0; i < imports.length; i++) { if (imports[i].endsWith("*")) { // package import: saxStartElement(handler, IMPORT_ELEMENT, new String[][] { { IMPORT_ATTRIBUTE, "package" } }); String imp = StringUtils.substringBeforeLast(imports[i], ".*"); saxCharacters(handler, imp); } else { saxStartElement(handler, IMPORT_ELEMENT, new String[][] { { IMPORT_ATTRIBUTE, "class" } }); saxCharacters(handler, imports[i]); } saxEndElement(handler, IMPORT_ELEMENT); } saxEndElement(handler, IMPORTS_ELEMENT); // Superclass: if (!javadocClass.isInterface()) { outputSuperClassInheritance(handler, javadocClass, CLASS_INHERITANCE); } // Implements: outputImplements(handler, javadocClass, true); // Containing class in case this is an inner class: if (containingJavadocClass != null) { saxStartElement(handler, NESTED_IN_ELEMENT); outputClassStartElement(handler, containingJavadocClass); outputModifiers(handler, containingJavadocClass); outputComment(handler, containingJavadocClass.getComment()); outputTags(handler, containingJavadocClass); outputClassEndElement(handler, containingJavadocClass); saxEndElement(handler, NESTED_IN_ELEMENT); } // Comment: outputComment(handler, javadocClass.getComment()); // Tags: outputTags(handler, javadocClass); // Inner classes: outputInnerClasses(handler, javadocClass, true); // Fields: outputFields(handler, javadocClass, true); // Constructors: outputMethods(handler, javadocClass, CONSTRUCTOR_MODE); // Methods: outputMethods(handler, javadocClass, METHOD_MODE); // Close class-level element: outputClassEndElement(handler, javadocClass); // Output SAX 'footer': handler.endPrefixMapping(NS_PREFIX); handler.endDocument(); }
From source file:org.apache.jackrabbit.core.query.lucene.FacetHandler.java
private void extractFacetInfo(NamedList<Object> info, SolrParams solrParams) { // Parse the queries _facetQuery = new LinkedHashMap<String, Long>(); NamedList<Long> fq = (NamedList<Long>) info.get("facet_queries"); if (fq != null) { for (Map.Entry<String, Long> entry : fq) { _facetQuery.put(entry.getKey(), entry.getValue()); }/* w w w . ja va 2 s.c o m*/ } // Parse the facet info into fields // TODO?? The list could be <int> or <long>? If always <long> then we can switch to <Long> NamedList<NamedList<Number>> ff = (NamedList<NamedList<Number>>) info.get("facet_fields"); Map<String, FieldType> fieldTypeMap = new HashMap<>(); if (ff != null) { _facetFields = new ArrayList<FacetField>(ff.size()); _limitingFacets = new ArrayList<FacetField>(ff.size()); long minsize = totalSize; for (Map.Entry<String, NamedList<Number>> facet : ff) { String key = StringUtils.substringBeforeLast(facet.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR); String fieldInIndex = StringUtils.substringAfterLast(facet.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR); FacetField f = new FacetField(key); if (!fieldTypeMap.containsKey(key)) { try { //Find a key like f.field_name#unknownumber.facet.nodetype Pattern facetNodetype = Pattern.compile("f\\." + key + "#[0-9]+\\.facet\\.nodetype"); String nodetypeName = null; Iterator<String> parameterNamesIterator = solrParams.getParameterNamesIterator(); while (parameterNamesIterator.hasNext()) { String next = parameterNamesIterator.next(); if (facetNodetype.matcher(next).matches()) { nodetypeName = solrParams.get(next); break; } } ExtendedPropertyDefinition epd = NodeTypeRegistry.getInstance().getNodeType(nodetypeName) .getPropertyDefinition(key); fieldTypeMap.put(key, getType(epd)); } catch (NoSuchNodeTypeException e) { log.error(e.getMessage(), e); } } for (Map.Entry<String, Number> entry : facet.getValue()) { String facetValue = entry.getKey(); String query = fieldTypeMap.get(key).toInternal(entry.getKey()); Matcher matcher = valueWithQuery.matcher(facetValue); if (matcher.matches()) { query = matcher.group(2); facetValue = matcher.replaceFirst("$1"); } f.add(facetValue, entry.getValue().longValue()); f.getValues().get(f.getValueCount() - 1).setFilterQuery( ClientUtils.escapeQueryChars(fieldInIndex) + ":" + ClientUtils.escapeQueryChars(query)); } _facetFields.add(f); FacetField nl = f.getLimitingFields(minsize); if (nl.getValueCount() > 0) { _limitingFacets.add(nl); } } } // Parse date facets NamedList<NamedList<Object>> df = (NamedList<NamedList<Object>>) info.get("facet_dates"); if (df != null) { // System.out.println(df); _facetDates = new ArrayList<FacetField>(df.size()); for (Map.Entry<String, NamedList<Object>> facet : df) { // System.out.println("Key: " + facet.getKey() + " Value: " + facet.getValue()); NamedList<Object> values = facet.getValue(); String gap = (String) values.get("gap"); Date end = (Date) values.get("end"); FacetField f = new FacetField(StringUtils.substringBeforeLast(facet.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR), gap, end); for (Map.Entry<String, Object> entry : values) { try { String key = StringUtils.substringBeforeLast(entry.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR); String query = StringUtils.substringAfterLast(entry.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR); f.add(key, Long.parseLong(entry.getValue().toString())); if (!StringUtils.isEmpty(query)) { String rangePrefix = null; if (query.contains(RANGEFROM_EXCLUSIVE_PREFIX)) { rangePrefix = RANGEFROM_EXCLUSIVE_PREFIX; } else if (query.contains(RANGEFROM_INCLUSIVE_PREFIX)) { rangePrefix = RANGEFROM_INCLUSIVE_PREFIX; } if (!StringUtils.isEmpty(rangePrefix)) { f.getValues().get(f.getValueCount() - 1) .setFilterQuery(ClientUtils .escapeQueryChars(StringUtils.substringBefore(query, rangePrefix)) + rangePrefix + StringUtils.substringAfter(query, rangePrefix)); } } } catch (NumberFormatException e) { // Ignore for non-number responses which are already handled above } } _facetDates.add(f); } } // Parse range facets NamedList<NamedList<Object>> rf = (NamedList<NamedList<Object>>) info.get("facet_ranges"); if (rf != null) { // System.out.println(df); _facetRanges = new ArrayList<RangeFacet>(rf.size()); for (Map.Entry<String, NamedList<Object>> facet : rf) { NamedList<Object> values = facet.getValue(); Object rawGap = values.get("gap"); RangeFacet rangeFacet; if (rawGap instanceof Number) { Number gap = (Number) rawGap; Number start = (Number) values.get("start"); Number end = (Number) values.get("end"); Number before = (Number) values.get("before"); Number after = (Number) values.get("after"); rangeFacet = new RangeFacet.Numeric(StringUtils.substringBeforeLast(facet.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR), start, end, gap, before, after); } else { String gap = (String) rawGap; Date start = (Date) values.get("start"); Date end = (Date) values.get("end"); Number before = (Number) values.get("before"); Number after = (Number) values.get("after"); rangeFacet = new RangeFacet.Date(StringUtils.substringBeforeLast(facet.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR), start, end, gap, before, after); } NamedList<Integer> counts = (NamedList<Integer>) values.get("counts"); for (Map.Entry<String, Integer> entry : counts) { try { String key = StringUtils.substringBeforeLast(entry.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR); String query = StringUtils.substringAfterLast(entry.getKey(), SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR); rangeFacet.addCount(key, entry.getValue()); if (!StringUtils.isEmpty(query)) { String rangePrefix = null; if (query.contains(RANGEFROM_EXCLUSIVE_PREFIX)) { rangePrefix = RANGEFROM_EXCLUSIVE_PREFIX; } else if (query.contains(RANGEFROM_INCLUSIVE_PREFIX)) { rangePrefix = RANGEFROM_INCLUSIVE_PREFIX; } if (!StringUtils.isEmpty(rangePrefix)) { ((RangeFacet.Count) rangeFacet.getCounts().get(rangeFacet.getCounts().size() - 1)) .setFilterQuery(ClientUtils .escapeQueryChars(StringUtils.substringBefore(query, rangePrefix)) + rangePrefix + StringUtils.substringAfter(query, rangePrefix)); } } } catch (NumberFormatException e) { // Ignore for non-number responses which are already handled above } } _facetRanges.add(rangeFacet); } } }
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 w ww . ja va 2s . c o 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.jetspeed.portlets.spaces.PageNavigator.java
@Override public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String name = actionRequest.getParameter("name"); String type = actionRequest.getParameter("type"); String templatePage = StringUtils.defaultString(actionRequest.getParameter("templatePage"), null); SpaceBean space = (SpaceBean) actionRequest.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACE, PortletSession.APPLICATION_SCOPE); if (space == null) { log.warn("Space not found in session."); return;/*from w w w . ja va2s. c o m*/ } if (StringUtils.isBlank(name)) { log.warn("Blank name to create a node of type " + type); return; } if (StringUtils.isBlank(type)) { throw new PortletException("Blank node type: " + type); } if ((Page.DOCUMENT_TYPE.equals(type) || (Folder.FOLDER_TYPE.equals(type))) && StringUtils.isBlank(templatePage)) { templatePage = actionRequest.getPreferences().getValue("defaultTemplatePage", null); if (StringUtils.isBlank(templatePage)) { throw new PortletException("Invalid template page: " + templatePage); } } try { RequestContext requestContext = (RequestContext) actionRequest .getAttribute(RequestContext.REQUEST_PORTALENV); ContentPage contentPage = requestContext.getPage(); String spacePath = space.getPath(); String contentPagePath = contentPage.getPath(); String contentFolderPath = StringUtils .defaultIfEmpty(StringUtils.substringBeforeLast(contentPagePath, "/"), "/"); String nodeName = name.replace(' ', '_'); String nodePath = null; if (contentFolderPath.startsWith(spacePath)) { nodePath = StringUtils.removeEnd(contentFolderPath, "/") + "/" + StringUtils.removeStart(nodeName, "/"); } else { nodePath = StringUtils.removeEnd(spacePath, "/") + "/" + StringUtils.removeStart(nodeName, "/"); } if (Page.DOCUMENT_TYPE.equals(type)) { String path = nodePath + Page.DOCUMENT_TYPE; Page source = pageManager.getPage(templatePage); Page newPage = pageManager.copyPage(source, path, false); newPage.setTitle(name); pageManager.updatePage(newPage); requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null); String redirect = admin.getPortalURL(actionRequest, actionResponse, path); actionResponse.sendRedirect(redirect); } else if (Folder.FOLDER_TYPE.equals(type)) { String path = nodePath; Folder folder = pageManager.newFolder(path); folder.setTitle(name); pageManager.updateFolder(folder); String defaultPagePath = folder.getPath() + "/" + Folder.FALLBACK_DEFAULT_PAGE; Page source = pageManager.getPage(templatePage); Page newPage = pageManager.copyPage(source, defaultPagePath, false); pageManager.updatePage(newPage); requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null); } else if (Link.DOCUMENT_TYPE.equals(type)) { String path = nodePath + Link.DOCUMENT_TYPE; Link link = pageManager.newLink(path); link.setTitle(name); pageManager.updateLink(link); requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null); } } catch (Exception e) { log.error("Failed to update page.", e); } }