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:edu.arizona.kra.kim.impl.identity.PersonServiceImpl.java
/** * @see org.kuali.rice.kim.api.identity.PersonService#resolvePrincipalNamesToPrincipalIds(org.kuali.rice.krad.bo.BusinessObject, java.util.Map) */// w ww . j a v a2 s.c o m @SuppressWarnings("unchecked") @Override public Map<String, String> resolvePrincipalNamesToPrincipalIds(BusinessObject businessObject, Map<String, String> fieldValues) { if (fieldValues == null) { return null; } if (businessObject == null) { return fieldValues; } StringBuffer resolvedPrincipalIdPropertyName = new StringBuffer(); // save off all criteria which are not references to Person properties // leave person properties out so they can be resolved and replaced by this method Map<String, String> processedFieldValues = getNonPersonSearchCriteria(businessObject, fieldValues); for (String propertyName : fieldValues.keySet()) { if (!StringUtils.isBlank(fieldValues.get(propertyName)) // property has a value && isPersonProperty(businessObject, propertyName) // is a property on a Person object ) { // strip off the prefix on the property String personPropertyName = ObjectUtils.getNestedAttributePrimitive(propertyName); // special case - the user ID if (StringUtils.equals(KIMPropertyConstants.Person.PRINCIPAL_NAME, personPropertyName)) { @SuppressWarnings("rawtypes") Class targetBusinessObjectClass = null; BusinessObject targetBusinessObject = null; resolvedPrincipalIdPropertyName.setLength(0); // clear the buffer without requiring a new object allocation on each iteration // get the property name up until the ".principalName" // this should be a reference to the Person object attached to the BusinessObject String personReferenceObjectPropertyName = ObjectUtils.getNestedAttributePrefix(propertyName); // check if the person was nested within another BO under the master BO. If so, go up one more level // otherwise, use the passed in BO class as the target class if (ObjectUtils.isNestedAttribute(personReferenceObjectPropertyName)) { String targetBusinessObjectPropertyName = ObjectUtils .getNestedAttributePrefix(personReferenceObjectPropertyName); targetBusinessObject = (BusinessObject) ObjectUtils.getPropertyValue(businessObject, targetBusinessObjectPropertyName); if (targetBusinessObject != null) { targetBusinessObjectClass = targetBusinessObject.getClass(); resolvedPrincipalIdPropertyName.append(targetBusinessObjectPropertyName).append("."); } else { LOG.error("Could not find target property '" + propertyName + "' in class " + businessObject.getClass().getName() + ". Property value was null."); } } else { // not a nested Person property targetBusinessObjectClass = businessObject.getClass(); targetBusinessObject = businessObject; } if (targetBusinessObjectClass != null) { // use the relationship metadata in the KNS to determine the property on the // host business object to put back into the map now that the principal ID // (the value stored in application tables) has been resolved String propName = ObjectUtils .getNestedAttributePrimitive(personReferenceObjectPropertyName); DataObjectRelationship rel = getBusinessObjectMetaDataService() .getBusinessObjectRelationship(targetBusinessObject, propName); if (rel != null) { String sourcePrimitivePropertyName = rel .getParentAttributeForChildAttribute(KIMPropertyConstants.Person.PRINCIPAL_ID); resolvedPrincipalIdPropertyName.append(sourcePrimitivePropertyName); // get the principal - for translation of the principalName to principalId String principalName = fieldValues.get(propertyName); Principal principal = getIdentityService().getPrincipalByPrincipalName(principalName); if (principal != null) { processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), principal.getPrincipalId()); } else { processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null); try { // if the principalName is bad, then we need to clear out the Person object // and base principalId property // so that their values are no longer accidentally used or re-populate // the object ObjectUtils.setObjectProperty(targetBusinessObject, resolvedPrincipalIdPropertyName.toString(), null); ObjectUtils.setObjectProperty(targetBusinessObject, propName, null); ObjectUtils.setObjectProperty(targetBusinessObject, propName + ".principalName", principalName); } catch (Exception ex) { LOG.error( "Unable to blank out the person object after finding that the person with the given principalName does not exist.", ex); } } } else { LOG.error("Missing relationship for " + propName + " on " + targetBusinessObjectClass.getName()); } } else { // no target BO class - the code below probably will not work processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null); } } // if the property does not seem to match the definition of a Person property but it // does end in principalName then... // this is to handle the case where the user ID is on an ADD line - a case excluded from isPersonProperty() } else if (propertyName.endsWith("." + KIMPropertyConstants.Person.PRINCIPAL_NAME)) { // if we're adding to a collection and we've got the principalName; let's populate universalUser String principalName = fieldValues.get(propertyName); if (StringUtils.isNotEmpty(principalName)) { String containerPropertyName = propertyName; if (containerPropertyName.startsWith(KRADConstants.MAINTENANCE_ADD_PREFIX)) { containerPropertyName = StringUtils.substringAfter(propertyName, KRADConstants.MAINTENANCE_ADD_PREFIX); } // get the class of the object that is referenced by the property name // if this is not true then there's a principalName collection or primitive attribute // directly on the BO on the add line, so we just ignore that since something is wrong here if (ObjectUtils.isNestedAttribute(containerPropertyName)) { // the first part of the property is the collection name String collectionName = StringUtils.substringBefore(containerPropertyName, "."); // what is the class held by that collection? // JHK: I don't like this. This assumes that this method is only used by the maintenance // document service. If that will always be the case, this method should be moved over there. Class<? extends BusinessObject> collectionBusinessObjectClass = getMaintenanceDocumentDictionaryService() .getCollectionBusinessObjectClass(getMaintenanceDocumentDictionaryService() .getDocumentTypeName(businessObject.getClass()), collectionName); if (collectionBusinessObjectClass != null) { // we are adding to a collection; get the relationships for that object; // is there one for personUniversalIdentifier? List<DataObjectRelationship> relationships = getBusinessObjectMetaDataService() .getBusinessObjectRelationships(collectionBusinessObjectClass); // JHK: this seems like a hack - looking at all relationships for a BO does not guarantee that we get the right one // JHK: why not inspect the objects like above? Is it the property path problems because of the .add. portion? for (DataObjectRelationship rel : relationships) { String parentAttribute = rel.getParentAttributeForChildAttribute( KIMPropertyConstants.Person.PRINCIPAL_ID); if (parentAttribute == null) { continue; } // there is a relationship for personUserIdentifier; use that to find the universal user processedFieldValues.remove(propertyName); String fieldPrefix = StringUtils .substringBeforeLast(StringUtils.substringBeforeLast(propertyName, "." + KIMPropertyConstants.Person.PRINCIPAL_NAME), "."); String relatedPrincipalIdPropertyName = fieldPrefix + "." + parentAttribute; // KR-683 Special handling for extension objects if (EXTENSION.equals(StringUtils.substringAfterLast(fieldPrefix, ".")) && EXTENSION.equals(StringUtils.substringBefore(parentAttribute, "."))) { relatedPrincipalIdPropertyName = fieldPrefix + "." + StringUtils.substringAfter(parentAttribute, "."); } String currRelatedPersonPrincipalId = processedFieldValues .get(relatedPrincipalIdPropertyName); if (StringUtils.isBlank(currRelatedPersonPrincipalId)) { Principal principal = getIdentityService() .getPrincipalByPrincipalName(principalName); if (principal != null) { processedFieldValues.put(relatedPrincipalIdPropertyName, principal.getPrincipalId()); } else { processedFieldValues.put(relatedPrincipalIdPropertyName, null); } } } // relationship loop } else { if (LOG.isDebugEnabled()) { LOG.debug( "Unable to determine class for collection referenced as part of property: " + containerPropertyName + " on " + businessObject.getClass().getName()); } } } else { if (LOG.isDebugEnabled()) { LOG.debug("Non-nested property ending with 'principalName': " + containerPropertyName + " on " + businessObject.getClass().getName()); } } } } } return processedFieldValues; }
From source file:biz.netcentric.cq.tools.actool.authorizableutils.impl.AuthorizableCreatorServiceImpl.java
private void setAuthorizableProperties(Authorizable authorizable, ValueFactory vf, AuthorizableConfigBean principalConfigBean, Session session) throws RepositoryException { String profileContent = principalConfigBean.getProfileContent(); if (StringUtils.isNotBlank(profileContent)) { ContentHelper.importContent(session, authorizable.getPath() + "/profile", profileContent); }//from w w w . ja va2s . c o m String preferencesContent = principalConfigBean.getPreferencesContent(); if (StringUtils.isNotBlank(preferencesContent)) { ContentHelper.importContent(session, authorizable.getPath() + "/preferences", preferencesContent); } String name = principalConfigBean.getPrincipalName(); if (StringUtils.isNotBlank(name)) { if (authorizable.isGroup()) { authorizable.setProperty("profile/givenName", vf.createValue(name)); } else { String givenName = StringUtils.substringBeforeLast(name, " "); String familyName = StringUtils.substringAfterLast(name, " "); authorizable.setProperty("profile/givenName", vf.createValue(givenName)); authorizable.setProperty("profile/familyName", vf.createValue(familyName)); } } String description = principalConfigBean.getDescription(); if (StringUtils.isNotBlank(description)) { authorizable.setProperty("profile/aboutMe", vf.createValue(description)); } }
From source file:info.magnolia.importexport.DataTransporter.java
/** * The opposite of {@link #createExportPath(String)}. * I.e. given a path like this <code>.foo.bar..baz.test.....dir.baz....bar</code>, this method will produce <code>/foo/bar.baz/test../dir/baz..bar</code>. *//*from w ww . j a v a 2s. com*/ public static String revertExportPath(String exportPath) { if (".".equals(exportPath)) { return "/"; } //TODO I have a feeling there's a simpler way to achieve our goal. Matcher matcher = DOT_NAME_PATTERN.matcher(exportPath); StringBuilder reversed = new StringBuilder(exportPath.length()); while (matcher.find()) { String group = matcher.group(); int dotsNumber = StringUtils.countMatches(group, "."); if (dotsNumber == 1) { reversed.append(group.replaceFirst("\\.", "/")); } else { String dots = StringUtils.substringBeforeLast(group, ".").replace("..", "."); String name = StringUtils.substringAfterLast(group, "."); reversed.append(dots); //if number is odd, the last dot has to be replaced with a slash if (dotsNumber % 2 != 0) { reversed.append("/"); } reversed.append(name); } } return reversed.toString(); }
From source file:info.magnolia.module.admininterface.SaveHandlerImpl.java
/** * Returns the page. The page is created if not yet existing depending on the property create * @param hm// ww w . jav a 2 s . co m * @return the node * @throws RepositoryException * @throws AccessDeniedException * @throws PathNotFoundException */ protected Content getPageNode(HierarchyManager hm) throws RepositoryException, AccessDeniedException, PathNotFoundException { Content page = null; String path = this.getPath(); try { page = hm.getContent(path); } catch (RepositoryException e) { if (this.isCreate()) { String parentPath = StringUtils.substringBeforeLast(path, "/"); //$NON-NLS-1$ String label = StringUtils.substringAfterLast(path, "/"); //$NON-NLS-1$ if (StringUtils.isEmpty(parentPath)) { page = hm.getRoot(); } else { page = hm.getContent(parentPath); } page = page.createContent(label, this.getCreationItemType()); } else { log.error("Tried to save a not existing node with path {}. use create = true to force creation", //$NON-NLS-1$ path); } } return page; }
From source file:com.htmlhifive.tools.wizard.download.DownloadModule.java
/** * ZIP?./*from w ww . jav a2 s.co m*/ * * @param libraryNode * @param perLibWork libWork * @param folder * @param monitor * @param logger . * @return ???????. * @throws IOException IO * @throws CoreException */ private boolean downloadZip(LibraryNode libraryNode, int perLibWork, IContainer folder, IProgressMonitor monitor, ResultStatus logger) throws IOException, CoreException { boolean result = true; boolean addStatus = false; ZipFile cachedZipFile = null; String cachedSite = null; Library library = libraryNode.getValue(); if (!library.getSite().isEmpty()) { int perSiteWork = Math.max(1, perLibWork / library.getSite().size()); for (Site site : library.getSite()) { String siteUrl = site.getUrl(); String path = H5IOUtils.getURLPath(siteUrl); if (path == null) { logger.log(Messages.SE0082, siteUrl); continue; } boolean setWorked = false; IContainer savedFolder = folder; if (site.getExtractPath() != null) { savedFolder = savedFolder.getFolder(Path.fromOSString(site.getExtractPath())); } // ?. IFile iFile = null; if (path.endsWith(".zip") || path.endsWith(".jar") || site.getFilePattern() != null) { // Zip // ?????????. if (!siteUrl.equals(cachedSite)) { cachedZipFile = download(monitor, perSiteWork, logger, null, siteUrl); setWorked = true; if (!lastDownloadStatus || cachedZipFile == null) { libraryNode.setInError(true); result = false; break; } cachedSite = siteUrl; } final ZipFile zipFile = cachedZipFile; // int perZipWork = Math.max(1, perSiteWork / zipFile.size()); // Zip. for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { final ZipEntry zipEntry = e.nextElement(); if (site.getFilePattern() != null && !FilenameUtils.wildcardMatch(zipEntry.getName(), site.getFilePattern())) { // ???. continue; } IContainer savedFolder2 = savedFolder; String wildCardStr = StringUtils.defaultString(site.getFilePattern()); if (wildCardStr.contains("*") && wildCardStr.contains("/")) { // ??????. wildCardStr = StringUtils.substringBeforeLast(site.getFilePattern(), "/"); } String entryName = zipEntry.getName(); if (entryName.startsWith(wildCardStr + "/")) { entryName = entryName.substring(wildCardStr.length() + 1); } if (zipEntry.isDirectory()) { // zip?????. if (StringUtils.isNotEmpty(entryName)) { // ?. savedFolder2 = savedFolder2.getFolder(Path.fromOSString(entryName)); if (libraryNode.isAddable() && !savedFolder2.exists()) { logger.log(Messages.SE0091, savedFolder2.getFullPath()); H5IOUtils.createParentFolder(savedFolder2, null); logger.log(Messages.SE0092, savedFolder2.getFullPath()); } else if (libraryNode.getState() == LibraryState.REMOVE && savedFolder2.exists()) { // . logger.log(Messages.SE0095, savedFolder2.getFullPath()); H5IOUtils.createParentFolder(savedFolder2, null); logger.log(Messages.SE0096, savedFolder2.getFullPath()); } } } else { // zip. // ???. if (site.getReplaceFileName() != null) { iFile = savedFolder2.getFile(Path.fromOSString(site.getReplaceFileName())); } else { iFile = savedFolder2.getFile(Path.fromOSString(entryName)); } // ?. updateFile(monitor, 0, logger, iFile, new ZipFileContentsHandler(zipFile, zipEntry)); addStatus = true; } } if (savedFolder.exists() && savedFolder.members().length == 0) { // ????. savedFolder.delete(true, monitor); } } else { // ???. if (site.getReplaceFileName() != null) { iFile = savedFolder.getFile(Path.fromOSString(site.getReplaceFileName())); } else { // . iFile = savedFolder.getFile(Path.fromOSString(StringUtils.substringAfterLast(path, "/"))); } // . download(monitor, perSiteWork, logger, iFile, siteUrl); setWorked = true; if (!lastDownloadStatus) { // SE0101=ERROR,({0})??????URL={1}, File={2} logger.log(Messages.SE0101, iFile != null ? iFile.getFullPath().toString() : StringUtils.defaultString(site.getFilePattern()), site.getUrl(), site.getFilePattern()); libraryNode.setInError(true); } else { addStatus = true; } } // ?????. // . if (!addStatus) { // SE0099=ERROR,???????URL={1}, File={2} logger.log(Messages.SE0099, site.getUrl(), iFile != null ? iFile.getFullPath().toString() : StringUtils.defaultString(site.getFilePattern())); libraryNode.setInError(true); result = false; } // folder.refreshLocal(IResource.DEPTH_ZERO, null); // // SE0102=INFO,???? // logger.log(Messages.SE0102); // logger.log(Messages.SE0068, iFile.getFullPath()); if (!setWorked) { monitor.worked(perSiteWork); } } } else { monitor.worked(perLibWork); } return result; }
From source file:com.adobe.acs.tools.csv_asset_importer.impl.CsvAssetImporterServlet.java
/** * Gets the ModifiableValueMap for the Asset's metadata node. * * @param asset the asset to get the properties for * @return the ModifiableValueMap for the Asset's metadata node *///from ww w .j a v a 2s. c o m private Node getMetadataProperties(final Asset asset, final String relPropertyPath) throws RepositoryException, CsvAssetImportException { String metadataResourcePath = JcrConstants.JCR_CONTENT + "/" + DamConstants.METADATA_FOLDER; Resource assetResource = asset.adaptTo(Resource.class); Resource metadataResource = assetResource.getChild(metadataResourcePath); if (metadataResource == null) { throw new CsvAssetImportException("Could not find metadata resource at [ " + assetResource.getPath() + "/" + metadataResourcePath + " ]. This is very strange. Skipping row as failure however some dam:Asset nodes for this asset may have been created."); } else if (!StringUtils.contains(relPropertyPath, "/")) { return metadataResource.adaptTo(Node.class); } else { ResourceResolver resourceResolver = assetResource.getResourceResolver(); String relPropertyPathPrefix = StringUtils.substringBeforeLast(relPropertyPath, "/"); String canonicalPath = com.day.text.Text .makeCanonicalPath(metadataResource.getPath() + "/" + relPropertyPathPrefix); Node node = JcrUtils.getOrCreateByPath(canonicalPath, JcrConstants.NT_UNSTRUCTURED, resourceResolver.adaptTo(Session.class)); Resource relativeResource = resourceResolver.getResource(node.getPath()); return relativeResource.adaptTo(Node.class); } }
From source file:info.magnolia.module.ModuleManagerImpl.java
/** * Loads a single repository plus its workspaces, register nodetypes and grant permissions to superuser. *//*from w w w . ja va 2 s . com*/ private void loadRepository(String repositoryNameFromModuleDescriptor, String nodeTypeFile, String[] workspaces) { if (workspaces == null || workspaces.length == 0) { log.error("Trying to register the repository {} without any workspace.", repositoryNameFromModuleDescriptor); return; } final String DEFAULT_REPOSITORY_NAME = "magnolia"; String repositoryName = repositoryNameFromModuleDescriptor; if (workspaces.length > 0) { // get the repository name from the mapping, users may want to manually add it here if needed info.magnolia.repository.definition.RepositoryDefinition repositoryMapping = ContentRepository .getRepositoryMapping(workspaces[0]); if (repositoryMapping != null) { repositoryName = repositoryMapping.getName(); } } info.magnolia.repository.definition.RepositoryDefinition rm = ContentRepository .getRepositoryMapping(repositoryName); if (rm == null) { final info.magnolia.repository.definition.RepositoryDefinition defaultRepositoryMapping = ContentRepository .getRepositoryMapping(DEFAULT_REPOSITORY_NAME); final Map<String, String> defaultParameters = defaultRepositoryMapping.getParameters(); rm = new info.magnolia.repository.definition.RepositoryDefinition(); rm.setName(repositoryName); rm.setProvider(defaultRepositoryMapping.getProvider()); rm.setLoadOnStartup(true); final Map<String, String> parameters = new HashMap<String, String>(); parameters.putAll(defaultParameters); // override changed parameters final String bindName = repositoryName + StringUtils.replace(defaultParameters.get("bindName"), "magnolia", ""); final String repositoryHome = StringUtils.substringBeforeLast(defaultParameters.get("configFile"), "/") + "/" + repositoryName; parameters.put("repositoryHome", repositoryHome); parameters.put("bindName", bindName); parameters.put("customNodeTypes", nodeTypeFile); rm.setParameters(parameters); try { ContentRepository.loadRepository(rm); } catch (Exception e) { log.error(e.getMessage(), e); } } if (nodeTypeFile != null) { // register nodetypes registerNodeTypeFile(repositoryName, nodeTypeFile); // if this repo is not the default one, register nodetypes on default repo (MAGNOLIA-3189) if (!DEFAULT_REPOSITORY_NAME.equals(repositoryName)) { registerNodeTypeFile(DEFAULT_REPOSITORY_NAME, nodeTypeFile); } } if (workspaces != null) { for (String workspace : workspaces) { if (!rm.getWorkspaces().contains(workspace)) { log.debug("Loading new workspace: {}", workspace); try { ContentRepository.loadWorkspace(repositoryName, workspace); } catch (RepositoryException e) { // should never happen, the only exception we can get here is during login log.error(e.getMessage(), e); } } } } }
From source file:adalid.commons.velocity.Writer.java
private void writeFile(WriterContext templateWriterContext, File templatePropertiesFile) { VelocityContext fileContext = templateWriterContext.getVelocityContextClone(); TLB.setProgrammers(templateWriterContext.programmers); TLB.setWrapperClasses(templateWriterContext.wrapperClasses); Properties properties = mergeProperties(fileContext, templatePropertiesFile); putStrings(fileContext, properties); // String rootPath = getRootPath(fileContext); String userPath = pathString(USER_DIR); String temptype = StringUtils.defaultIfBlank(properties.getProperty(TP_TYPE), TP_TYPE_VELOCITY); String template = StringUtils.trimToNull(properties.getProperty(TP_TEMPLATE)); String filePath = StringUtils.trimToNull(properties.getProperty(TP_PATH)); String filePack = StringUtils.trimToNull(properties.getProperty(TP_PACKAGE)); String fileName = StringUtils.trimToNull(properties.getProperty(TP_FILE)); String preserve = StringUtils.trimToNull(properties.getProperty(TP_PRESERVE)); String charset1 = StringUtils.trimToNull(properties.getProperty(TP_ENCODING)); String charset2 = StringUtils.trimToNull(properties.getProperty(TP_CHARSET)); String root = getRoot().getPath(); String raiz = root.replace('\\', '/'); String hint = "; check property \"{0}\" at file \"{1}\""; if (ArrayUtils.contains(TP_TYPE_ARRAY, temptype)) { } else {/*w w w .ja v a2 s .co m*/ String pattern = "failed to obtain a valid template type" + hint; String message = MessageFormat.format(pattern, TP_TYPE, templatePropertiesFile); logger.error(message); errors++; return; } if (template == null) { String pattern = "failed to obtain a valid template name" + hint; String message = MessageFormat.format(pattern, TP_TEMPLATE, templatePropertiesFile); logger.error(message); errors++; return; } if (fileName == null) { String pattern = "failed to obtain a valid file name" + hint; String message = MessageFormat.format(pattern, TP_FILE, templatePropertiesFile); logger.error(message); errors++; return; } String templatePathString = pathString(template); String templatePath = StringUtils.substringBeforeLast(templatePathString, FILE_SEPARATOR); fileContext.put(VC_TEMPLATE, StringEscapeUtils.escapeJava(templatePathString)); fileContext.put(VC_TEMPLATE_PATH, StringUtils.replace(templatePath, FILE_SEPARATOR, SLASH)); fileContext.put(VC_FILE, fileName); if (filePath == null) { // filePath = rootPath; filePath = userPath; } else { filePath = pathString(filePath); if (isRelativePath(filePath)) { if (filePath.startsWith(FILE_SEPARATOR)) { // filePath = rootPath + filePath; filePath = userPath + filePath; } else { // filePath = rootPath + FILE_SEPARATOR + filePath; filePath = userPath + FILE_SEPARATOR + filePath; } } } fileContext.put(VC_PATH, StringEscapeUtils.escapeJava(filePath)); if (filePack != null) { filePath += FILE_SEPARATOR + pathString(StringUtils.replace(filePack, DOT, SLASH)); fileContext.put(VC_PACKAGE, dottedString(filePack)); } File path = new File(filePath); if (path.exists()) { if (path.isDirectory() && path.canWrite()) { } else { String pattern = "{2} is not a valid directory" + hint; String message = MessageFormat.format(pattern, TP_PATH, templatePropertiesFile, path); logger.error(message); errors++; return; } } else if (path.mkdirs()) { } else { String pattern = "{2} is not a valid path" + hint; String message = MessageFormat.format(pattern, TP_PATH, templatePropertiesFile, path); logger.error(message); errors++; return; } String fullname = path.getPath() + FILE_SEPARATOR + fileName; String slashedPath = fullname.replace('\\', '/'); File file = new File(fullname); if (file.exists()) { String regex, pattern, message; for (Pattern fxp : fileExclusionPatterns) { regex = fxp.pattern(); if (slashedPath.matches(regex)) { excludedFiles++; pattern = "file {0} will be deleted; it matches exclusion expression \"{1}\""; message = MessageFormat.format(pattern, StringUtils.removeStartIgnoreCase(slashedPath, raiz), regex); log(_alertLevel, message); warnings++; FileUtils.deleteQuietly(file); return; } } if (BitUtils.valueOf(preserve)) { preservedFiles++; pattern = "file {2} will not be replaced" + hint; message = MessageFormat.format(pattern, TP_PRESERVE, templatePropertiesFile, fullname); log(_detailLevel, message); return; } for (Pattern fxp : filePreservationPatterns) { regex = fxp.pattern(); if (slashedPath.matches(regex)) { preservedFiles++; pattern = "file {0} will not be replaced; it matches preservation expression \"{1}\""; message = MessageFormat.format(pattern, StringUtils.removeStartIgnoreCase(slashedPath, raiz), regex); log(_alertLevel, message); warnings++; return; } } } else { String regex, pattern, message; for (Pattern fxp : fileExclusionPatterns) { regex = fxp.pattern(); if (slashedPath.matches(regex)) { excludedFiles++; pattern = "file {0} will not be written; it matches exclusion expression \"{1}\""; message = MessageFormat.format(pattern, StringUtils.removeStartIgnoreCase(slashedPath, raiz), regex); log(_alertLevel, message); warnings++; return; } } } if (charset1 != null && !Charset.isSupported(charset1)) { String pattern = "{2} is not a supported character set" + hint; String message = MessageFormat.format(pattern, TP_ENCODING, templatePropertiesFile, charset1); logger.error(message); errors++; return; } if (charset2 != null && !Charset.isSupported(charset2)) { String pattern = "{2} is not a supported character set" + hint; String message = MessageFormat.format(pattern, TP_CHARSET, templatePropertiesFile, charset2); logger.error(message); errors++; return; } fileContext.put(VC_FILE_PATH, StringEscapeUtils.escapeJava(filePath)); fileContext.put(VC_FILE_NAME, StringEscapeUtils.escapeJava(fileName)); fileContext.put(VC_FILE_PATH_NAME, StringEscapeUtils.escapeJava(fullname)); fileContext.put(VC_FILE_PATH_FILE, path); if (temptype.equals(TP_TYPE_VELOCITY)) { writeFile(fileContext, template, fullname, charset1, charset2); } else { writeFile(template, fullname); } executeFile(fileContext, templatePropertiesFile); }
From source file:eionet.cr.web.action.factsheet.FolderActionBean.java
/** * Returns parent folder uri. If it is home folder uri, current uri is returned. * * @return/* w w w. j a v a 2 s. c o m*/ */ public String getParentUri() { if (isHomeFolder()) { return uri; } return StringUtils.substringBeforeLast(uri, "/"); }
From source file:gov.nih.nci.caarray.web.action.project.ProjectFilesAction.java
/** * Calculates and returns the JSON for the nodes that are the children of * the passed in node. in the experiment tree * * @return null - the JSON is written directly to the response stream *//*from w ww. ja v a 2 s . co m*/ @SkipValidation public String importTreeNodesJson() { try { final JSONArray jsArray = new JSONArray(); if (this.nodeType == ExperimentDesignTreeNodeType.ROOT) { addJsonForExperimentRoots(jsArray); } else if (this.nodeType.isExperimentRootNode()) { addJsonForExperimentDesignNodes(jsArray, this.nodeType.getChildrenNodeType(), this.nodeType.getContainedNodes(getExperiment()), this.nodeId); } else if (this.nodeType.isBiomaterialRootNode()) { // the node id of an associated biomaterials container node will end in [number]_[type] // where [type] is the container type and [number] is the id of the biomaterial parent final Long biomaterialParentId = Long.parseLong( StringUtils.substringAfterLast(StringUtils.substringBeforeLast(this.nodeId, "_"), "_")); final AbstractBioMaterial bioMaterialParent = ServiceLocatorFactory.getGenericDataService() .getPersistentObject(AbstractBioMaterial.class, biomaterialParentId); addJsonForExperimentDesignNodes(jsArray, this.nodeType.getChildrenNodeType(), this.nodeType.getContainedNodes(bioMaterialParent), this.nodeId); } else if (this.nodeType.isBiomaterialNode()) { // note that we should never get requested for biomaterial or hybrdization nodes // since they are returned with their children already or marked as leaves throw new IllegalStateException("Unsupported node type" + this.nodeType); } ServletActionContext.getResponse().getWriter().write(jsArray.toString()); } catch (final IOException e) { LOG.error("unable to write response", e); } return null; }