List of usage examples for org.apache.commons.lang StringUtils lastIndexOf
public static int lastIndexOf(String str, String searchStr)
Finds the last index within a String, handling null
.
From source file:org.eclipse.wb.internal.swt.model.property.editor.AcceleratorPropertyEditor.java
/** * @return the source for given accelerator. *///ww w . ja v a2s . co m private static String getSource(int accelerator) { String source = getText(accelerator); source = StringUtils.replace(source, "ALT+", "org.eclipse.swt.SWT.ALT | "); source = StringUtils.replace(source, "CTRL+", "org.eclipse.swt.SWT.CTRL | "); source = StringUtils.replace(source, "SHIFT+", "org.eclipse.swt.SWT.SHIFT | "); // check for character/keyCode int length = source.length(); int index = StringUtils.lastIndexOf(source, ' '); if (index == length - 2) { source = source.substring(0, index) + " '" + source.substring(index + 1) + "'"; } else if (index > 0) { source = source.substring(0, index) + " org.eclipse.swt.SWT." + source.substring(index + 1); } else { source = "org.eclipse.swt.SWT." + source; } // final resource return source; }
From source file:org.gradle.api.internal.artifacts.dsl.ArtifactFile.java
public ArtifactFile(File file, String version) { name = file.getName();//from w w w . j ava2 s .co m extension = ""; classifier = ""; boolean done = false; int startVersion = StringUtils.lastIndexOf(name, "-" + version); if (startVersion >= 0) { int endVersion = startVersion + version.length() + 1; if (endVersion == name.length()) { name = name.substring(0, startVersion); done = true; } else if (endVersion < name.length() && name.charAt(endVersion) == '-') { String tail = name.substring(endVersion + 1); name = name.substring(0, startVersion); classifier = StringUtils.substringBeforeLast(tail, "."); extension = StringUtils.substringAfterLast(tail, "."); done = true; } else if (endVersion < name.length() && StringUtils.lastIndexOf(name, ".") == endVersion) { extension = name.substring(endVersion + 1); name = name.substring(0, startVersion); done = true; } } if (!done) { extension = StringUtils.substringAfterLast(name, "."); name = StringUtils.substringBeforeLast(name, "."); } if (extension.length() == 0) { extension = null; } if (classifier.length() == 0) { classifier = null; } }
From source file:org.gytheio.content.handler.FileContentReferenceHandlerImpl.java
@Override public ContentReference createContentReference(String fileName, String mediaType) throws ContentIOException { String suffix = fileName.substring(StringUtils.lastIndexOf(fileName, "."), fileName.length()); String prefix = fileName.substring(0, StringUtils.lastIndexOf(fileName, ".")); File tempFile = fileProvider.createFile(prefix, suffix); if (logger.isDebugEnabled()) { logger.debug("Created file content reference for " + "mediaType=" + mediaType + ": " + tempFile.getAbsolutePath()); }// w w w . j a v a 2s . com return new ContentReference(tempFile.toURI().toString(), mediaType); }
From source file:org.gytheio.content.handler.FileContentReferenceHandlerImplTest.java
protected void checkReference(String fileName, String mediaType) { ContentReference reference = handler.createContentReference(fileName, mediaType); assertEquals(mediaType, reference.getMediaType()); String uri = reference.getUri(); String createdFileName = uri.split("\\/")[uri.split("\\/").length - 1]; String origPrefix = fileName.substring(0, StringUtils.lastIndexOf(fileName, ".")); String origSuffix = fileName.substring(StringUtils.lastIndexOf(fileName, "."), fileName.length()); assertTrue("ContentReference file name '" + createdFileName + "' did not contain original file name prefix '" + origPrefix + "'", createdFileName.contains(origPrefix)); assertTrue("ContentReference file name '" + createdFileName + "' did not contain original file name suffix '" + origPrefix + "'", createdFileName.contains(origSuffix)); }
From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java
/** * Get edit configuration/*from w ww .ja va2s . c o m*/ * * @return * @throws GWTJahiaServiceException */ public GWTEditConfiguration getGWTEditConfiguration(String name, String contextPath, JahiaUser jahiaUser, Locale locale, Locale uiLocale, HttpServletRequest request, JCRSessionWrapper session) throws GWTJahiaServiceException { try { EditConfiguration config = (EditConfiguration) SpringContextSingleton.getBean(name); if (config != null) { GWTEditConfiguration gwtConfig = new GWTEditConfiguration(); gwtConfig.setName(config.getName()); String defaultLocation = config.getDefaultLocation(); if (defaultLocation.contains("$defaultSiteHome")) { JahiaSitesService siteService = JahiaSitesService.getInstance(); JahiaSite resolvedSite = !Url.isLocalhost(request.getServerName()) ? siteService.getSiteByServerName(request.getServerName(), session) : null; if (resolvedSite == null) { resolvedSite = JahiaSitesService.getInstance().getDefaultSite(session); if (resolvedSite != null && !((JCRSiteNode) resolvedSite).hasPermission(config.getRequiredPermission())) { resolvedSite = null; } if (resolvedSite == null) { List<JCRSiteNode> sites = JahiaSitesService.getInstance().getSitesNodeList(session); for (JCRSiteNode site : sites) { if (!"systemsite".equals(site.getName()) && (site.hasPermission(config.getRequiredPermission()))) { resolvedSite = site; break; } } } } if (resolvedSite != null) { JCRSiteNode siteNode = (JCRSiteNode) session .getNode(((JCRSiteNode) resolvedSite).getPath()); if (siteNode.getHome() != null) { defaultLocation = defaultLocation.replace("$defaultSiteHome", siteNode.getHome().getPath()); } else { defaultLocation = null; } } else { defaultLocation = null; } } else if (defaultLocation.contains("$user")) { defaultLocation = defaultLocation.replace("$user", jahiaUser.getLocalPath()); } gwtConfig.setDefaultLocation(defaultLocation); JCRNodeWrapper contextNode = null; JCRSiteNode site = null; if (contextPath == null) { int nodeNameIndex = StringUtils.indexOf(defaultLocation, ".", StringUtils.lastIndexOf(defaultLocation, "/")); contextPath = StringUtils.substring(defaultLocation, 0, nodeNameIndex); if (defaultLocation != null && session.nodeExists(contextPath)) { contextNode = session.getNode(contextPath); site = contextNode.getResolveSite(); } } else { if (session.nodeExists(contextPath)) { contextNode = session.getNode(contextPath); site = contextNode.getResolveSite(); } } if (config.getForcedSite() != null) { site = (JCRSiteNode) session.getNode(config.getForcedSite()); } if (site == null) { contextNode = session.getNode("/sites/systemsite"); site = contextNode.getResolveSite(); } // check locale final List<Locale> languagesAsLocales = site.getLanguagesAsLocales(); if (languagesAsLocales != null && !languagesAsLocales.contains(locale)) { final String defaultLanguage = site.getDefaultLanguage(); if (StringUtils.isNotEmpty(defaultLanguage)) { locale = LanguageCodeConverters.languageCodeToLocale(defaultLanguage); } } gwtConfig.setTopToolbar(createGWTToolbar(contextNode, site, jahiaUser, locale, uiLocale, request, config.getTopToolbar())); gwtConfig.setSidePanelToolbar(createGWTToolbar(contextNode, site, jahiaUser, locale, uiLocale, request, config.getSidePanelToolbar())); gwtConfig.setMainModuleToolbar(createGWTToolbar(contextNode, site, jahiaUser, locale, uiLocale, request, config.getMainModuleToolbar())); gwtConfig.setContextMenu(createGWTToolbar(contextNode, site, jahiaUser, locale, uiLocale, request, config.getContextMenu())); gwtConfig.setTabs(createGWTSidePanelTabList(contextNode, site, jahiaUser, locale, uiLocale, request, config.getTabs())); gwtConfig.setEngineConfigurations(createGWTEngineConfigurations(contextNode, site, jahiaUser, locale, uiLocale, request, config.getEngineConfigurations())); gwtConfig.setSitesLocation(config.getSitesLocation()); gwtConfig.setEnableDragAndDrop(config.isEnableDragAndDrop()); gwtConfig.setDefaultUrlMapping(config.getDefaultUrlMapping()); gwtConfig.setComponentsPaths(config.getComponentsPaths()); gwtConfig.setEditableTypes(config.getEditableTypes()); gwtConfig.setNonEditableTypes(config.getNonEditableTypes()); gwtConfig.setSkipMainModuleTypesDomParsing(config.getSkipMainModuleTypesDomParsing()); gwtConfig.setVisibleTypes(config.getVisibleTypes()); gwtConfig.setNonVisibleTypes(config.getNonVisibleTypes()); gwtConfig.setExcludedNodeTypes(config.getExcludedNodeTypes()); List<String> configsList = new ArrayList<String>(); // configsList will define the list of modes that share the same configuration to avoid reloading the main resource // when switching from edit to preview or live or any mode that has the same default location. // An exception has been added for system site that is used for dashboard or administration. for (EditConfiguration configuration : SpringContextSingleton.getInstance().getContext() .getBeansOfType(EditConfiguration.class).values()) { if (StringUtils.equals(configuration.getSitesLocation(), (config.getSitesLocation())) && !StringUtils.equals(config.getSitesLocation(), "/sites/systemsite")) { configsList.add(configuration.getName()); } } gwtConfig.setSamePathConfigsList(configsList); gwtConfig.setSiteNode(navigation.getGWTJahiaNode(site, GWTJahiaNode.DEFAULT_SITE_FIELDS, uiLocale)); if (config.isLoadSitesList()) { List<GWTJahiaNode> sites = navigation.retrieveRoot(Arrays.asList(config.getSitesLocation()), Arrays.asList("jnt:virtualsite"), null, null, GWTJahiaNode.DEFAULT_SITEMAP_FIELDS, null, null, site, session, uiLocale, false, false, null, null); String permission = ((EditConfiguration) SpringContextSingleton.getBean(name)) .getRequiredPermission(); Map<String, GWTJahiaNode> sitesMap = new HashMap<String, GWTJahiaNode>(); for (GWTJahiaNode aSite : sites) { if (session.getNodeByUUID(aSite.getUUID()).hasPermission(permission)) { sitesMap.put(aSite.getSiteUUID(), aSite); } } GWTJahiaNode systemSite = navigation.getGWTJahiaNode(session.getNode("/sites/systemsite"), GWTJahiaNode.DEFAULT_SITEMAP_FIELDS); if (!sitesMap.containsKey(systemSite.getUUID())) { sitesMap.put(systemSite.getUUID(), systemSite); } gwtConfig.setSitesMap(sitesMap); } gwtConfig.setPermissions(JahiaPrivilegeRegistry.getRegisteredPrivilegeNames()); gwtConfig.setChannels(channelHelper.getChannels()); gwtConfig.setUseFullPublicationInfoInMainAreaModules( config.isUseFullPublicationInfoInMainAreaModules()); gwtConfig.setSupportChannelsDisplay(config.isSupportChannelsDisplay()); return gwtConfig; } else { throw new GWTJahiaServiceException(Messages .getInternal("label.gwt.error.bean.editconfig.not.found.in.spring.config.file", uiLocale)); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); throw new GWTJahiaServiceException(Messages.getInternalWithArguments("label.gwt.error.config.not.found", uiLocale, name, e.getLocalizedMessage())); } }
From source file:org.jahia.services.content.JCRSessionWrapper.java
private boolean checkCyclicReference(String path, String reference) { try {/* w w w.j a va 2 s . 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.jasig.schedassist.impl.oraclecalendar.AbstractOracleCalendarDao.java
/** * This function encapsulates the processing of the output from Oracle Calendar * by iCal4j.//from ww w. j av a 2 s . c o m * * This method currently inspects the end of the agenda argument for the presence * of the complete string "END:VCALENDAR" (a known bug with the Oracle Calendar APIs presents * itself in this fashion) and attempts to repair the agenda before sending to iCal4J. * * {@link CalendarBuilder#build(java.io.Reader)} can throw an {@link IOException}; this method wraps the call * in try-catch and throws any caught {@link IOException}s wrapped in a {@link ParseException} instead. * * @param agenda * @return * @throws ParserException */ protected Calendar parseAgenda(String agenda) throws ParserException { final String chomped = StringUtils.chomp(agenda); if (!StringUtils.endsWith(chomped, "END:VCALENDAR")) { // Oracle for an unknown reason sometimes does not properly end the iCalendar LOG.warn("agenda does not end in END:VCALENDAR"); // find out how much is missing from the end int indexOfLastNewline = StringUtils.lastIndexOf(chomped, CRLF); if (indexOfLastNewline == -1) { throw new ParserException("oracle calendar data is malformed ", -1); } String agendaWithoutLastLine = agenda.substring(0, indexOfLastNewline); StringBuilder agendaBuilder = new StringBuilder(); agendaBuilder.append(agendaWithoutLastLine); agendaBuilder.append(CRLF); agendaBuilder.append("END:VCALENDAR"); agenda = agendaBuilder.toString(); } StringReader reader = new StringReader(agenda); CalendarBuilder builder = new CalendarBuilder(); try { Calendar result = builder.build(reader); if (LOG.isTraceEnabled()) { LOG.trace(result.toString()); } return result; } catch (IOException e) { LOG.error("ical4j threw IOException attempting to build Calendar; rethrowing as ParserException", e); throw new ParserException(e.getMessage(), -1, e); } }
From source file:org.kuali.kfs.sys.batch.SemaphoreInputFileType.java
/** * Validate that the first line of the file contains a job name and a valid Step (the bean id) * in the format jobName.stepName/*from ww w . j a v a 2 s . co m*/ * * @see org.kuali.kfs.sys.batch.BatchInputFileType#validate(Object) */ @Override public boolean validate(Object parsedFileContents) { List<String> content = getParsedFileContent(parsedFileContents); if (content.size() <= 0) { MessageMap errors = new MessageMap(); errors.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.Semaphore.ERROR_BATCH_UPLOAD_INVALID_STEP); GlobalVariables.mergeErrorMap(errors); return false; } String firstLine = content.get(0); String stepName = StringUtils.substring(firstLine, StringUtils.lastIndexOf(firstLine, BatchStepFileDescriptor.STEP_FILE_NAME_SEPARATOR) + 1); Step step = BatchSpringContext.getStep(stepName); if (step == null) { LOG.error("Unable to find bean for step: " + stepName); MessageMap errors = new MessageMap(); errors.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.Semaphore.ERROR_BATCH_UPLOAD_INVALID_STEP); GlobalVariables.mergeErrorMap(errors); return false; } return true; }
From source file:org.kuali.kra.common.specialreview.service.impl.SpecialReviewServiceImpl.java
/** * {@inheritDoc}/*from w w w. jav a 2 s . c o m*/ * @see org.kuali.kra.common.specialreview.service.SpecialReviewService#getProtocolIndex(java.lang.String) */ public int getProtocolIndex(String prefix) { int index = -1; int lastLeftBracketIndex = StringUtils.lastIndexOf(prefix, '['); int lastRightBracketIndex = StringUtils.lastIndexOf(prefix, ']'); if (lastLeftBracketIndex != -1 && lastRightBracketIndex != -1) { String lineNumber = prefix.substring(lastLeftBracketIndex + 1, lastRightBracketIndex); if (NumberUtils.isDigits(lineNumber)) { index = Integer.parseInt(lineNumber); } } return index; }
From source file:org.kuali.rice.kns.web.struts.action.KualiMaintenanceDocumentAction.java
/** * Adds a line to a collection being maintained in a many section. *///w w w.j av a2 s. co m public ActionForward addLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { KualiMaintenanceForm maintenanceForm = (KualiMaintenanceForm) form; MaintenanceDocument document = (MaintenanceDocument) maintenanceForm.getDocument(); Maintainable oldMaintainable = document.getOldMaintainableObject(); Maintainable newMaintainable = document.getNewMaintainableObject(); String collectionName = extractCollectionName(request, KRADConstants.ADD_LINE_METHOD); if (collectionName == null) { LOG.error("Unable to get find collection name and class in request."); throw new RuntimeException("Unable to get find collection name and class in request."); } // if dealing with sub collection it will have a "[" if ((StringUtils.lastIndexOf(collectionName, "]") + 1) == collectionName.length()) { collectionName = StringUtils.substringBeforeLast(collectionName, "["); } Object bo = newMaintainable.getBusinessObject(); Collection maintCollection = extractCollection(bo, collectionName); Class collectionClass = extractCollectionClass(((MaintenanceDocument) maintenanceForm.getDocument()) .getDocumentHeader().getWorkflowDocument().getDocumentTypeName(), collectionName); // TODO: sort of collection, new instance should be first // get the BO from the new collection line holder PersistableBusinessObject addBO = newMaintainable.getNewCollectionLine(collectionName); if (LOG.isDebugEnabled()) { LOG.debug("obtained addBO from newCollectionLine: " + addBO); } // link up the user fields, if any getBusinessObjectService().linkUserFields(addBO); //KULRICE-4264 - a hook to change the state of the business object, which is the "new line" of a collection, before it is validated newMaintainable.processBeforeAddLine(collectionName, collectionClass, addBO); // apply rules to the addBO boolean rulePassed = false; if (LOG.isDebugEnabled()) { LOG.debug("about to call AddLineEvent applyRules: document=" + document + "\ncollectionName=" + collectionName + "\nBO=" + addBO); } rulePassed = getKualiRuleService().applyRules(new KualiAddLineEvent(document, collectionName, addBO)); // if the rule evaluation passed, let's add it if (rulePassed) { if (LOG.isInfoEnabled()) { LOG.info("********************doing editing 4 in addline()***********************."); } // if edit or copy action, just add empty instance to old maintainable boolean isEdit = KRADConstants.MAINTENANCE_EDIT_ACTION.equals(maintenanceForm.getMaintenanceAction()); boolean isCopy = KRADConstants.MAINTENANCE_COPY_ACTION.equals(maintenanceForm.getMaintenanceAction()); if (isEdit || isCopy) { Object oldBo = oldMaintainable.getBusinessObject(); Collection oldMaintCollection = (Collection) ObjectUtils.getPropertyValue(oldBo, collectionName); if (oldMaintCollection == null) { oldMaintCollection = new ArrayList(); } if (PersistableBusinessObject.class.isAssignableFrom(collectionClass)) { PersistableBusinessObject placeholder = (PersistableBusinessObject) collectionClass .newInstance(); // KULRNE-4538: must set it as a new collection record, because the maintainable will set the BO that gets added // to the new maintainable as a new collection record // if not set, then the subcollections of the newly added object will appear as read only // see FieldUtils.getContainerRows on how the delete button is rendered placeholder.setNewCollectionRecord(true); ((List) oldMaintCollection).add(placeholder); } else { LOG.warn("Should be a instance of PersistableBusinessObject"); ((List) oldMaintCollection).add(collectionClass.newInstance()); } // update collection in maintenance business object ObjectUtils.setObjectProperty(oldBo, collectionName, List.class, oldMaintCollection); } newMaintainable.addNewLineToCollection(collectionName); int subCollectionIndex = 0; for (Object aSubCollection : maintCollection) { subCollectionIndex += getSubCollectionIndex(aSubCollection, maintenanceForm.getDocTypeName()); } //TODO: Should we keep this logic and continue using currentTabIndex as the key in the tabStates HashMap ? // // String parameter = (String) request.getAttribute(Constants.METHOD_TO_CALL_ATTRIBUTE); // String indexStr = StringUtils.substringBetween(parameter, Constants.METHOD_TO_CALL_PARM13_LEFT_DEL, Constants.METHOD_TO_CALL_PARM13_RIGHT_DEL); // // + 1 is for the fact that the first element of a collection is on the next tab // int index = Integer.parseInt(indexStr) + subCollectionIndex + 1; // Map<String, String> tabStates = maintenanceForm.getTabStates(); // Map<String, String> copyOfTabStates = new HashMap<String, String>(); // // int incrementor = 0; // for (String tabState : tabStates.keySet()) { // String originalValue = maintenanceForm.getTabState(Integer.toString(incrementor)); // copyOfTabStates.put(Integer.toString(incrementor), originalValue); // incrementor++; // } // // int i = index; // if (tabStates.containsKey(Integer.toString(i-1))) { // tabStates.remove(Integer.toString(i-1)); // } // while (i < copyOfTabStates.size() + 1) { // String originalValue = copyOfTabStates.get(Integer.toString(i-1)); // if (tabStates.containsKey(Integer.toString(i))) { // tabStates.remove(Integer.toString(i)); // } // tabStates.put(Integer.toString(i), originalValue); // i++; // } // End of whether we should continue to keep this logic and use currentTabIndex as the key } doProcessingAfterPost((KualiMaintenanceForm) form, request); return mapping.findForward(RiceConstants.MAPPING_BASIC); }