List of usage examples for org.apache.commons.lang3 StringUtils defaultIfEmpty
public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr)
Returns either the passed in CharSequence, or if the CharSequence is empty or null , the value of defaultStr .
StringUtils.defaultIfEmpty(null, "NULL") = "NULL" StringUtils.defaultIfEmpty("", "NULL") = "NULL" StringUtils.defaultIfEmpty(" ", "NULL") = " " StringUtils.defaultIfEmpty("bat", "NULL") = "bat" StringUtils.defaultIfEmpty("", null) = null
From source file:info.magnolia.photoreview.app.action.AddToAssetsAction.java
@Override protected void executeTask(TasksManager taskManager, Task task) { // first resolve item properties from task String assetName = (String) task.getContent().get("itemId"); String urlString = (String) task.getContent().get("images.standardResolution.url"); String extension = StringUtils.substringAfterLast(urlString, "."); InputStream inputStream = null; try {// ww w . j a v a 2 s .co m URL url = new URL((String) urlString); inputStream = url.openStream(); } catch (IOException e) { e.printStackTrace(); } // then import to dam try { // create root folder if it does not exist Node damRoot = MgnlContext.getInstance().getJCRSession(DamConstants.WORKSPACE).getRootNode(); Node folder = null; if (!damRoot.hasNode(DAM_FOLDER_NAME)) { folder = damRoot.addNode(DAM_FOLDER_NAME, NodeTypes.Folder.NAME); } else { folder = damRoot.getNode(DAM_FOLDER_NAME); } // create asset and binary property Node asset = folder.addNode(assetName, AssetNodeTypes.Asset.NAME); Node jcrContent = asset.addNode(JcrConstants.JCR_CONTENT, NodeTypes.Resource.NAME); Binary binary = ValueFactoryImpl.getInstance().createBinary(inputStream); jcrContent.setProperty(JcrConstants.JCR_DATA, binary); jcrContent.setProperty(JcrConstants.JCR_MIMETYPE, StringUtils.defaultIfEmpty(MIMEMapping.getMIMEType(extension), "application/octet-stream")); folder.getSession().save(); // finally resolve task super.executeTask(taskManager, task); } catch (RepositoryException e) { e.printStackTrace(); } }
From source file:info.magnolia.ui.admincentral.shellapp.favorites.FavoritesPresenterTest.java
@Before public void setUp() throws RegistrationException, URISyntaxException { ctx = new MockWebContext(); MgnlContext.setInstance(ctx);//from ww w. ja va2s.co m session = new MockSession(FavoriteStore.WORKSPACE_NAME); ctx.addSession(FavoriteStore.WORKSPACE_NAME, session); FavoritesView view = mock(FavoritesView.class); FavoritesManager favoritesManager = mock(FavoritesManager.class); doAnswer(new Answer<JcrNewNodeAdapter>() { @Override public JcrNewNodeAdapter answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); JcrNewNodeAdapter newFavorite = new JcrNewNodeAdapter(session.getRootNode(), NAME); newFavorite.addItemProperty(TITLE, new ObjectProperty<String>((String) args[1])); newFavorite.addItemProperty(URL, new ObjectProperty<String>((String) args[0])); newFavorite.addItemProperty(ICON, new ObjectProperty<String>(StringUtils.defaultIfEmpty((String) args[2], "icon-app"))); return newFavorite; } }).when(favoritesManager).createFavoriteSuggestion(anyString(), anyString(), anyString()); /** * We mock a sample descriptor that would be returned when favorites presenter will ask. * We do not set the name/title for sake of testing the i18n functionality. */ AppDescriptorRegistry registry = mock(AppDescriptorRegistry.class); ConfiguredAppDescriptor descriptor = new ConfiguredAppDescriptor(); descriptor.setName("favoritesRandomApp"); doReturn(descriptor).when(registry).getAppDescriptor(anyString()); I18nizer i18nizer = mock(I18nizer.class); // simple I18nizer mock which only decorates based on appDescriptor name doAnswer(new Answer<AppDescriptor>() { @Override public AppDescriptor answer(InvocationOnMock invocation) throws Throwable { ConfiguredAppDescriptor appDescriptor = (ConfiguredAppDescriptor) invocation.getArguments()[0]; appDescriptor.setIcon("icon-" + appDescriptor.getName()); appDescriptor.setLabel(StringUtils.capitalize(appDescriptor.getName())); return appDescriptor; } }).when(i18nizer).decorate(any()); presenter = new FavoritesPresenter(view, favoritesManager, registry, i18nizer); }
From source file:com.adobe.acs.commons.wcm.vanity.impl.VanityURLServiceImpl.java
/** * Checks if the provided vanity path is a valid redirect * * @param pathScope The content path to scope the vanity path too. * @param vanityPath Vanity path that needs to be validated. * @param request SlingHttpServletRequest object used for performing query/lookup * @return return true if the vanityPath is a registered sling:vanityPath under /content *//*from ww w .j av a 2 s.co m*/ protected boolean isVanityPath(String pathScope, String vanityPath, SlingHttpServletRequest request) throws RepositoryException { final Resource vanityResource = request.getResourceResolver().resolve(vanityPath); if (vanityResource != null) { String targetPath = null; if (vanityResource.isResourceType("sling:redirect")) { targetPath = vanityResource.getValueMap().get("sling:target", String.class); } else if (!StringUtils.equals(vanityPath, vanityResource.getPath())) { targetPath = vanityResource.getPath(); } if (targetPath != null && StringUtils.startsWith(targetPath, StringUtils.defaultIfEmpty(pathScope, DEFAULT_PATH_SCOPE))) { log.debug("Found vanity resource at [ {} ] for sling:vanityPath [ {} ]", targetPath, vanityPath); return true; } } return false; }
From source file:de.micromata.genome.gwiki.controls.GWikiPluginDownloadActionBean.java
protected void initPluginAttachment(GWikiElementInfo atel) { GWikiElement el = wikiContext.getWikiWeb().getElement(atel); byte[] data = (byte[]) el.getMainPart().getCompiledObject(); if (data == null) { GWikiLog.warn("Plugin zip has no attachment bytes: " + el.getElementInfo().getId()); return;/*w ww. jav a 2 s . c o m*/ } ZipRamFileSystem fs = new ZipRamFileSystem("", new ByteArrayInputStream(data)); if (fs.exists("gwikiplugin.xml") == false) { return; } GWikiPluginDescriptor desc = GWikiPluginRepository.loadDescriptor(fs, "gwikiplugin.xml"); if (desc == null) { return; } String versionState = desc.getVersionState(); if (StringUtils.equals(versionState, "Final") == true && finalRelease == false) { return; } if (StringUtils.equals(versionState, "Beta") == true && betaRelease == false) { return; } if (StringUtils.equals(versionState, "Alpha") == true && alphaRelease == false) { return; } if (StringUtils.equals(versionState, "Experimental") == true && experimentalRelease == false) { return; } PDesc pdesc = new PDesc(atel, desc); if (desc.getDescriptionPath() == null) { desc.setDescriptionPath(getDetailPage(wikiContext, pdesc.getDescriptor())); } String cat = StringUtils.defaultIfEmpty(desc.getCategory(), "Standard"); List<PDesc> ld = plugins.get(cat); if (ld == null) { ld = new ArrayList<PDesc>(); plugins.put(cat, ld); } ld.add(pdesc); }
From source file:info.magnolia.ui.framework.action.async.DefaultAsyncActionExecutor.java
@Override public boolean execute(JcrItemAdapter item, Map<String, Object> params) throws Exception { Calendar cal = Calendar.getInstance(); // wait for requested period of time before invocation cal.add(Calendar.SECOND, definition.getDelay()); // init waiting time before job is started to avoid issues (when job is finished before timeToWait is initialized) int timeToWait = definition.getTimeToWait(); String jobName = "UI Action triggered execution of [" + (StringUtils.isNotEmpty(catalogName) ? (catalogName + ":") : "") + commandName + "] by user [" + StringUtils.defaultIfEmpty(user.getName(), "") + "]."; // allowParallel jobs false/true => remove index, or keep index if (definition.isParallel()) { jobName += " (" + idx.getAndIncrement() + ")"; }/*from w ww .j a va 2 s. c om*/ SimpleTrigger trigger = new SimpleTrigger(jobName, SchedulerConsts.SCHEDULER_GROUP_NAME, cal.getTime()); trigger.addTriggerListener(jobName + "_trigger"); // create job definition final JobDetail jd = new JobDetail(jobName, SchedulerConsts.SCHEDULER_GROUP_NAME, info.magnolia.module.scheduler.CommandJob.class); jd.getJobDataMap().put(SchedulerConsts.CONFIG_JOB_COMMAND, commandName); jd.getJobDataMap().put(SchedulerConsts.CONFIG_JOB_COMMAND_CATALOG, catalogName); jd.getJobDataMap().put(SchedulerConsts.CONFIG_JOB_PARAMS, params); Scheduler scheduler = schedulerModuleProvider.get().getScheduler(); scheduler.addTriggerListener(getListener(jobName, item)); try { scheduler.scheduleJob(jd, trigger); } catch (SchedulerException e) { throw new ParallelExecutionException(e); } // wait until job has been executed Thread.sleep(definition.getDelay() * 1000 + 100); int timeToSleep = 500; // check every 500ms if job is running while (timeToWait > 0) { List<JobExecutionContext> jobs = scheduler.getCurrentlyExecutingJobs(); if (isJobRunning(jobs, jobName)) { Thread.sleep(timeToSleep); } else { break; } timeToWait -= timeToSleep; } // action execution is running in background return (timeToWait == 0); }
From source file:com.gargoylesoftware.htmlunit.javascript.DebugFrameImpl.java
private String stringValue(final Object arg) { if (arg instanceof NativeFunction) { // Don't return the string value of the function, because it's usually // multiple lines of content and messes up the log. final String name = StringUtils.defaultIfEmpty(((NativeFunction) arg).getFunctionName(), "anonymous"); return "[function " + name + "]"; } else if (arg instanceof IdFunctionObject) { return "[function " + ((IdFunctionObject) arg).getFunctionName() + "]"; } else if (arg instanceof Function) { return "[function anonymous]"; }//from ww w. ja v a2s.co m String asString = null; try { // try to get the js representation asString = Context.toString(arg); if (arg instanceof Event) { asString += "<" + ((Event) arg).getType() + ">"; } } catch (final Throwable e) { // seems to be a bug (many bugs) in rhino (TODO: investigate it) asString = String.valueOf(arg); } return asString; }
From source file:io.cloudslang.content.database.utils.SQLInputs.java
@java.beans.ConstructorProperties({ "sqlCommand", "dbServer", "dbName", "dbPort", "dbType", "key", "username", "password", "authenticationType", "instance", "ignoreCase", "timeout", "dbUrl", "dbClass", "isNetcool", "lRowsFiles", "lRowsNames", "skip", "strDelim", "strColumns", "lRows", "iUpdateCount", "databasePoolingProperties", "trustStore", "trustStorePassword", "trustAllRoots", "authLibraryPath", "colDelimiter", "rowDelimiter", "resultSetType", "resultSetConcurrency", "sqlCommands" }) SQLInputs(String sqlCommand, String dbServer, String dbName, int dbPort, String dbType, String key, String username, String password, String authenticationType, String instance, boolean ignoreCase, int timeout, String dbUrl, String dbClass, boolean isNetcool, List<List<String>> lRowsFiles, List<List<String>> lRowsNames, long skip, String strDelim, String strColumns, List<String> lRows, int iUpdateCount, Properties databasePoolingProperties, String trustStore, String trustStorePassword, boolean trustAllRoots, String authLibraryPath, String colDelimiter, String rowDelimiter, Integer resultSetType, Integer resultSetConcurrency, List<String> sqlCommands) { this.sqlCommand = sqlCommand; this.dbServer = dbServer; this.dbName = dbName; this.dbPort = dbPort; this.dbType = dbType; this.key = key; this.username = username; this.password = password; this.authenticationType = authenticationType; this.instance = instance; this.ignoreCase = ignoreCase; this.timeout = timeout; this.dbUrl = dbUrl; this.dbClass = dbClass; this.isNetcool = isNetcool; this.lRowsFiles = lRowsFiles == null ? new ArrayList<List<String>>() : lRowsFiles; this.lRowsNames = lRowsNames == null ? new ArrayList<List<String>>() : lRowsNames; this.skip = skip; this.strDelim = strDelim; this.strColumns = StringUtils.defaultIfEmpty(strColumns, EMPTY); this.lRows = lRows == null ? new ArrayList<String>() : lRows; this.iUpdateCount = iUpdateCount; this.databasePoolingProperties = databasePoolingProperties; this.trustStore = trustStore; this.trustStorePassword = trustStorePassword; this.trustAllRoots = trustAllRoots; this.authLibraryPath = authLibraryPath; this.colDelimiter = colDelimiter; this.rowDelimiter = rowDelimiter; this.resultSetType = resultSetType; this.resultSetConcurrency = resultSetConcurrency; this.sqlCommands = sqlCommands == null ? new ArrayList<String>() : sqlCommands; }
From source file:com.xpn.xwiki.web.sx.AbstractSxAction.java
/** * This method must be called by render(XWikiContext). Render is in charge of creating the proper source and * extension type, and pass it as an argument to this method which will forge the proper response using those. * /* w ww . j av a2 s . c om*/ * @param sxSource the source of the extension. * @param sxType the type of extension * @param context the XWiki context when rendering the skin extension. * @throws XWikiException when an error occurs when building the response. */ public void renderExtension(SxSource sxSource, Extension sxType, XWikiContext context) throws XWikiException { XWikiRequest request = context.getRequest(); XWikiResponse response = context.getResponse(); String extensionContent = sxSource.getContent(); response.setContentType(sxType.getContentType()); if (sxSource.getLastModifiedDate() > 0) { response.setDateHeader(LAST_MODIFIED_HEADER, sxSource.getLastModifiedDate()); } CachePolicy cachePolicy = sxSource.getCachePolicy(); if (cachePolicy != CachePolicy.FORBID) { response.setHeader(CACHE_CONTROL_HEADER, "public"); } if (cachePolicy == CachePolicy.LONG) { // Cache for one month (30 days) response.setDateHeader(CACHE_EXPIRES_HEADER, (new Date()).getTime() + LONG_CACHE_DURATION); } else if (cachePolicy == CachePolicy.SHORT) { // Cache for one day response.setDateHeader(CACHE_EXPIRES_HEADER, (new Date()).getTime() + SHORT_CACHE_DURATION); } else if (cachePolicy == CachePolicy.FORBID) { response.setHeader(CACHE_CONTROL_HEADER, "no-cache, no-store, must-revalidate"); } if (BooleanUtils .toBoolean(StringUtils.defaultIfEmpty(request.get(COMPRESS_SCRIPT_REQUEST_PARAMETER), "true"))) { extensionContent = sxType.getCompressor().compress(extensionContent); } try { response.setContentLength(extensionContent.getBytes(RESPONSE_CHARACTER_SET).length); response.getOutputStream().write(extensionContent.getBytes(RESPONSE_CHARACTER_SET)); } catch (IOException ex) { getLogger().warn("Failed to send SX content: [{}]", ex.getMessage()); } }
From source file:com.gst.infrastructure.sms.domain.SmsMessage.java
public Map<String, Object> update(final JsonCommand command) { final Map<String, Object> actualChanges = new LinkedHashMap<>(1); if (command.isChangeInStringParameterNamed(SmsApiConstants.messageParamName, this.message)) { final String newValue = command.stringValueOfParameterNamed(SmsApiConstants.messageParamName); actualChanges.put(SmsApiConstants.messageParamName, newValue); this.message = StringUtils.defaultIfEmpty(newValue, null); }//from w w w . j av a2 s. c om return actualChanges; }
From source file:com.adobe.cq.wcm.core.components.internal.models.v1.TeaserImpl.java
@PostConstruct private void initModel() { actionsEnabled = properties.get(Teaser.PN_ACTIONS_ENABLED, actionsEnabled); populateStyleProperties();/*from w w w . j ava 2 s .com*/ titleFromPage = properties.get(Teaser.PN_TITLE_FROM_PAGE, titleFromPage); descriptionFromPage = properties.get(Teaser.PN_DESCRIPTION_FROM_PAGE, descriptionFromPage); linkURL = properties.get(ImageResource.PN_LINK_URL, String.class); if (actionsEnabled) { hiddenImageResourceProperties.add(ImageResource.PN_LINK_URL); linkURL = null; populateActions(); if (actions.size() > 0) { ListItem firstAction = actions.get(0); if (firstAction != null) { targetPage = pageManager.getPage(firstAction.getPath()); } } } else { targetPage = pageManager.getPage(linkURL); } if (titleHidden) { title = null; } else { title = properties.get(JcrConstants.JCR_TITLE, String.class); if (titleFromPage) { if (targetPage != null) { title = StringUtils.defaultIfEmpty(targetPage.getPageTitle(), targetPage.getTitle()); } else { title = null; } } } if (descriptionHidden) { description = null; } else { description = properties.get(JcrConstants.JCR_DESCRIPTION, String.class); if (descriptionFromPage) { if (targetPage != null) { description = targetPage.getDescription(); } else { description = null; } } } String fileReference = properties.get(DownloadResource.PN_REFERENCE, String.class); boolean hasImage = true; if (StringUtils.isEmpty(linkURL)) { LOGGER.debug("Teaser component from " + request.getResource().getPath() + " does not define a link."); } if (StringUtils.isEmpty(fileReference)) { if (request.getResource().getChild(DownloadResource.NN_FILE) == null) { LOGGER.debug("Teaser component from " + request.getResource().getPath() + " does not have an asset or an image file " + "configured."); hasImage = false; } } else { if (request.getResourceResolver().getResource(fileReference) == null) { LOGGER.error("Asset " + fileReference + " configured for the teaser component from " + request.getResource().getPath() + " doesn't exist."); hasImage = false; } } if (hasImage) { if (targetPage != null) { linkURL = Utils.getURL(request, targetPage); } setImageResource(component, request.getResource(), hiddenImageResourceProperties); } }