List of usage examples for org.apache.commons.lang StringUtils defaultString
public static String defaultString(String str, String defaultStr)
Returns either the passed in String, or if the String is null
, the value of defaultStr
.
From source file:com.adobe.acs.commons.wcm.impl.PropertyMergePostProcessor.java
protected static String getFieldTypeHint(RequestParameterMap params, String field) { return StringUtils.defaultString(getParamValue(params, IGNORE_PREFIX + field + TYPE_HINT_SUFFIX), String.class.getSimpleName()); }
From source file:br.com.ingenieux.mojo.beanstalk.env.ReplaceEnvironmentMojo.java
@Override protected Object executeInternal() throws Exception { solutionStack = lookupSolutionStack(solutionStack); /*// w ww. j av a2s. c o m * Is the desired cname not being used by other environments? If so, * just launch the environment */ if (!hasEnvironmentFor(applicationName, cnamePrefix)) { if (getLog().isInfoEnabled()) { getLog().info("Just launching a new environment."); } return super.executeInternal(); } /* * Gets the current environment using this cname */ EnvironmentDescription curEnv = getEnvironmentFor(applicationName, cnamePrefix); if (curEnv.getVersionLabel().equals(versionLabel) && skipIfSameVersion) { getLog().warn(format("Environment is running version %s and skipIfSameVersion is true. Returning", versionLabel)); return null; } /* * Decides on a environmentRef, and launches a new environment */ String cnamePrefixToCreate = getCNamePrefixToCreate(); if (getLog().isInfoEnabled()) { getLog().info("Creating a new environment on " + cnamePrefixToCreate + ".elasticbeanstalk.com"); } if (copyOptionSettings) { copyOptionSettings(curEnv); if (!solutionStack.equals(curEnv.getSolutionStackName())) { if (getLog().isInfoEnabled()) { getLog().warn(format( "(btw, we're launching with solutionStack/ set to '%s' instead of the default ('%s'). " + "If this is not the case, then we kindly ask you to file a bug report on the mailing list :)", curEnv.getSolutionStackName(), solutionStack)); } solutionStack = curEnv.getSolutionStackName(); } } String newEnvironmentName = getNewEnvironmentName( StringUtils.defaultString(this.environmentName, curEnv.getEnvironmentName())); if (getLog().isInfoEnabled()) { getLog().info("And it'll be named " + newEnvironmentName); } CreateEnvironmentResult createEnvResult = createEnvironment(cnamePrefixToCreate, newEnvironmentName); /* * Waits for completion */ EnvironmentDescription newEnvDesc = null; try { newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId()); } catch (Exception exc) { /* * Terminates the failed launched environment */ terminateEnvironment(createEnvResult.getEnvironmentId()); handleException(exc); return null; } /* * Swaps. Due to beanstalker-25, we're doing some extra logic we * actually woudln't want to. */ { boolean swapped = false; for (int i = 1; i <= maxAttempts; i++) { try { swapEnvironmentCNames(newEnvDesc.getEnvironmentId(), curEnv.getEnvironmentId(), cnamePrefix, newEnvDesc); swapped = true; break; } catch (Throwable exc) { if (exc instanceof MojoFailureException) { exc = Throwable.class.cast(MojoFailureException.class.cast(exc).getCause()); } getLog().warn(format("Attempt #%d/%d failed. Sleeping and retrying. Reason: %s (type: %s)", i, maxAttempts, exc.getMessage(), exc.getClass())); sleepInterval(attemptRetryInterval); } } if (!swapped) { getLog().info( "Failed to properly Replace Environment. Finishing the new one. And throwing you a failure"); terminateEnvironment(newEnvDesc.getEnvironmentId()); String message = "Unable to swap cnames. btw, see https://github.com/ingenieux/beanstalker/issues/25 and help us improve beanstalker"; getLog().warn(message); throw new MojoFailureException(message); } } /* * Terminates the previous environment */ terminateEnvironment(curEnv.getEnvironmentId()); return createEnvResult; }
From source file:com.frameworkset.orm.engine.model.Domain.java
/** * Replaces the default value if the new value is not null. * /* w w w. j a v a 2 s . co m*/ * @param value The defaultValue to set. */ public void replaceDefaultValue(String value) { this.defaultValue = StringUtils.defaultString(value, getDefaultValue()); }
From source file:it.openutils.mgnlaws.magnolia.init.ClasspathProviderImpl.java
/** * @see info.magnolia.repository.Provider#init(info.magnolia.repository.RepositoryMapping) *///from w w w. j a v a 2 s.c om public void init(RepositoryMapping repositoryMapping) throws RepositoryNotInitializedException { checkXmlSettings(); this.repositoryMapping = repositoryMapping; /* connect to repository */ Map params = this.repositoryMapping.getParameters(); String configFile = (String) params.get(CONFIG_FILENAME_KEY); if (!StringUtils.startsWith(configFile, ClasspathPropertiesInitializer.CLASSPATH_PREFIX)) { configFile = Path.getAbsoluteFileSystemPath(configFile); } String repositoryHome = (String) params.get(REPOSITORY_HOME_KEY); repositoryHome = getRepositoryHome(repositoryHome); // cleanup the path, to remove eventual ../.. and make it absolute try { File repoHomeFile = new File(repositoryHome); repositoryHome = repoHomeFile.getCanonicalPath(); } catch (IOException e1) { // should never happen and it's not a problem at this point, just pass it to jackrabbit and see } String clusterid = SystemProperty.getProperty(MAGNOLIA_CLUSTERID_PROPERTY); if (StringUtils.isNotBlank(clusterid)) { System.setProperty(JACKRABBIT_CLUSTER_ID_PROPERTY, clusterid); } // get it back from system properties, if it has been set elsewhere clusterid = System.getProperty(JACKRABBIT_CLUSTER_ID_PROPERTY); log.info("Loading repository at {} (config file: {}) - cluster id: \"{}\"", new Object[] { repositoryHome, configFile, StringUtils.defaultString(clusterid, "<unset>") }); bindName = (String) params.get(BIND_NAME_KEY); jndiEnv = new Hashtable<String, Object>(); jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, params.get(CONTEXT_FACTORY_CLASS_KEY)); jndiEnv.put(Context.PROVIDER_URL, params.get(PROVIDER_URL_KEY)); try { InitialContext ctx = new InitialContext(jndiEnv); // first try to find the existing object if any try { this.repository = (Repository) ctx.lookup(bindName); } catch (NameNotFoundException ne) { log.debug("No JNDI bound Repository found with name {}, trying to initialize a new Repository", bindName); ClasspathRegistryHelper.registerRepository(ctx, bindName, configFile, repositoryHome, true); this.repository = (Repository) ctx.lookup(bindName); } this.validateWorkspaces(); } catch (NamingException e) { log.error("Unable to initialize repository: " + e.getMessage(), e); throw new RepositoryNotInitializedException(e); } catch (RepositoryException e) { log.error("Unable to initialize repository: " + e.getMessage(), e); throw new RepositoryNotInitializedException(e); } catch (TransformerFactoryConfigurationError e) { log.error("Unable to initialize repository: " + e.getMessage(), e); throw new RepositoryNotInitializedException(e); } }
From source file:mitm.common.pdf.MessagePDFBuilder.java
private void addAttachment(final Part part, PdfWriter pdfWriter) throws IOException, MessagingException { byte[] content = IOUtils.toByteArray(part.getInputStream()); String filename = StringUtils .defaultString(HeaderUtils.decodeTextQuietly(MimeUtils.getFilenameQuietly(part)), "attachment.bin"); String baseType;/*from w w w . java 2 s . c o m*/ String contentType = null; try { contentType = part.getContentType(); MimeType mimeType = new MimeType(contentType); baseType = mimeType.getBaseType(); } catch (MimeTypeParseException e) { /* * Can happen when the content-type is not correct. Example with missing ; between charset and name: * * Content-Type: application/pdf; * charset="Windows-1252" name="postcard2010.pdf" */ logger.warn("Unable to infer MimeType from content type. Fallback to application/octet-stream. " + "Content-Type: " + contentType); baseType = MimeTypes.OCTET_STREAM; } PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(pdfWriter, null, filename, content, true /* compress */, baseType, null); pdfWriter.addFileAttachment(fileSpec); }
From source file:info.magnolia.cms.taglibs.util.SimpleNavigationTag.java
/** * Draws page children as an unordered list. * @param page current page/* w w w.j a va 2 s . co m*/ * @param activePage active page * @param out jsp writer * @throws IOException jspwriter exception * @throws RepositoryException any exception thrown during repository reading */ private void drawChildren(Content page, Content activePage, JspWriter out) throws IOException, RepositoryException { Collection children = page.getChildren(ItemType.CONTENT); if (children.size() == 0) { return; } out.print("<ul class=\"level"); //$NON-NLS-1$ out.print(page.getLevel()); if (style != null && page.getLevel() == startLevel) { out.print(" "); out.print(style); } out.print("\">"); //$NON-NLS-1$ Iterator it = children.iterator(); while (it.hasNext()) { Content child = (Content) it.next(); if (expandAll.equalsIgnoreCase(EXPAND_NONE) || expandAll.equalsIgnoreCase(EXPAND_SHOW)) { if (child.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)) .getBoolean()) { continue; } } List cssClasses = new ArrayList(3); String title = child.getNodeData(NODEDATA_NAVIGATIONTITLE).getString(StringUtils.EMPTY); // if nav title is not set, the main title is taken if (StringUtils.isEmpty(title)) { title = child.getTitle(); } // if main title is not set, the name of the page is taken if (StringUtils.isEmpty(title)) { title = child.getName(); } boolean showChildren = false; boolean self = false; if (!expandAll.equalsIgnoreCase(EXPAND_NONE)) { showChildren = true; } if (activePage.getHandle().equals(child.getHandle())) { // self showChildren = true; self = true; cssClasses.add(CSS_LI_ACTIVE); //$NON-NLS-1$ } else if (!showChildren) { showChildren = (child.getLevel() <= activePage.getAncestors().size() && activePage.getAncestor(child.getLevel()).getHandle().equals(child.getHandle())); } if (!showChildren) { showChildren = child .getNodeData(StringUtils.defaultString(this.openMenu, DEFAULT_OPENMENU_NODEDATA)) .getBoolean(); } if (endLevel > 0) { showChildren &= child.getLevel() < endLevel; } cssClasses.add(hasVisibleChildren(child) ? (showChildren ? CSS_LI_OPEN : CSS_LI_CLOSED) : CSS_LI_LEAF); if (child.getLevel() < activePage.getLevel() && activePage.getAncestor(child.getLevel()).getHandle().equals(child.getHandle())) { cssClasses.add(CSS_LI_TRAIL); } StringBuffer css = new StringBuffer(cssClasses.size() * 10); Iterator iterator = cssClasses.iterator(); while (iterator.hasNext()) { css.append(iterator.next()); if (iterator.hasNext()) { css.append(" "); //$NON-NLS-1$ } } out.print("<li class=\""); //$NON-NLS-1$ out.print(css.toString()); out.print("\">"); //$NON-NLS-1$ if (self) { out.println("<strong>"); //$NON-NLS-1$ } String accesskey = child.getNodeData(NODEDATA_ACCESSKEY).getString(StringUtils.EMPTY); out.print("<a href=\""); //$NON-NLS-1$ out.print(((HttpServletRequest) this.pageContext.getRequest()).getContextPath()); out.print(child.getHandle()); out.print(".html\""); //$NON-NLS-1$ if (StringUtils.isNotEmpty(accesskey)) { out.print(" accesskey=\""); //$NON-NLS-1$ out.print(accesskey); out.print("\""); //$NON-NLS-1$ } out.print(">"); //$NON-NLS-1$ out.print(StringEscapeUtils.escapeHtml(title)); out.print(" </a>"); //$NON-NLS-1$ if (self) { out.println("</strong>"); //$NON-NLS-1$ } if (showChildren) { drawChildren(child, activePage, out); } out.print("</li>"); //$NON-NLS-1$ } out.print("</ul>"); //$NON-NLS-1$ }
From source file:com.bstek.dorado.web.loader.DoradoLoader.java
public synchronized void preload(ServletContext servletContext, boolean processOriginContextConfigLocation) throws Exception { if (preloaded) { throw new IllegalStateException("Dorado base configurations already loaded."); }//from w ww . ja v a 2s . co m preloaded = true; // ? ConsoleUtils.outputLoadingInfo("Initializing " + DoradoAbout.getProductTitle() + " engine..."); ConsoleUtils.outputLoadingInfo("[Vendor: " + DoradoAbout.getVendor() + "]"); ConfigureStore configureStore = Configure.getStore(); doradoHome = System.getenv("DORADO_HOME"); // ?DoradoHome String intParam; intParam = servletContext.getInitParameter("doradoHome"); if (intParam != null) { doradoHome = intParam; } if (doradoHome == null) { doradoHome = DEFAULT_DORADO_HOME; } configureStore.set(HOME_PROPERTY, doradoHome); ConsoleUtils.outputLoadingInfo("[Home: " + StringUtils.defaultString(doradoHome, "<not assigned>") + "]"); // ResourceLoader ResourceLoader resourceLoader = new ServletContextResourceLoader(servletContext) { @Override public Resource getResource(String resourceLocation) { if (resourceLocation != null && resourceLocation.startsWith(HOME_LOCATION_PREFIX)) { resourceLocation = ResourceUtils.concatPath(doradoHome, resourceLocation.substring(HOME_LOCATION_PREFIX_LEN)); } return super.getResource(resourceLocation); } }; String runMode = null; if (StringUtils.isNotEmpty(doradoHome)) { String configureLocation = HOME_LOCATION_PREFIX + "configure.properties"; loadConfigureProperties(configureStore, resourceLoader, configureLocation, false); } runMode = configureStore.getString("core.runMode"); if (StringUtils.isNotEmpty(runMode)) { loadConfigureProperties(configureStore, resourceLoader, CORE_PROPERTIES_LOCATION_PREFIX + "configure-" + runMode + ".properties", true); if (StringUtils.isNotEmpty(doradoHome)) { loadConfigureProperties(configureStore, resourceLoader, HOME_LOCATION_PREFIX + "configure-" + runMode + ".properties", true); } } ConsoleUtils.outputConfigureItem("core.runMode"); ConsoleUtils.outputConfigureItem("core.addonLoadMode"); File tempDir; String tempDirPath = configureStore.getString("core.tempDir"); if (StringUtils.isNotBlank(tempDirPath)) { tempDir = new File(tempDirPath); } else { tempDir = new File(WebUtils.getTempDir(servletContext), ".dorado"); } boolean supportsTempFile = configureStore.getBoolean("core.supportsTempFile"); TempFileUtils.setSupportsTempFile(supportsTempFile); if (supportsTempFile) { if ((tempDir.exists() && tempDir.isDirectory()) || tempDir.mkdir()) { TempFileUtils.setTempDir(tempDir); } ConsoleUtils.outputLoadingInfo("[TempDir: " + TempFileUtils.getTempDir().getPath() + "]"); } else { ConsoleUtils.outputLoadingInfo("Temp file is forbidden."); } // File storeDir; String storeDirSettring = configureStore.getString("core.storeDir"); if (StringUtils.isNotEmpty(storeDirSettring)) { storeDir = new File(storeDirSettring); File testFile = new File(storeDir, ".test"); if (!testFile.mkdirs()) { throw new IllegalStateException( "Store directory [" + storeDir.getAbsolutePath() + "] is not writable in actually."); } testFile.delete(); } else { storeDir = new File(tempDir, "dorado-store"); configureStore.set("core.storeDir", storeDir.getAbsolutePath()); } ConsoleUtils.outputConfigureItem("core.storeDir"); // gothrough packages String addonLoadMode = Configure.getString("core.addonLoadMode"); String[] enabledAddons = StringUtils.split(Configure.getString("core.enabledAddons"), ",; \n\r"); String[] disabledAddon = StringUtils.split(Configure.getString("core.disabledAddon"), ",; \n\r"); Collection<PackageInfo> packageInfos = PackageManager.getPackageInfoMap().values(); int addonNumber = 0; for (PackageInfo packageInfo : packageInfos) { String packageName = packageInfo.getName(); if (packageName.equals("dorado-core")) { continue; } if (addonNumber > 9999) { packageInfo.setEnabled(false); } else if (StringUtils.isEmpty(addonLoadMode) || "positive".equals(addonLoadMode)) { packageInfo.setEnabled(!ArrayUtils.contains(disabledAddon, packageName)); } else { // addonLoadMode == negative packageInfo.setEnabled(ArrayUtils.contains(enabledAddons, packageName)); } if (packageInfo.isEnabled()) { addonNumber++; } } // print packages int i = 0; for (PackageInfo packageInfo : packageInfos) { ConsoleUtils.outputLoadingInfo( StringUtils.rightPad(String.valueOf(++i) + '.', 4) + "Package [" + packageInfo.getName() + " - " + StringUtils.defaultIfBlank(packageInfo.getVersion(), "<Unknown Version>") + "] found." + ((packageInfo.isEnabled() ? "" : " #DISABLED# "))); } // load packages for (PackageInfo packageInfo : packageInfos) { if (!packageInfo.isEnabled()) { pushLocations(contextLocations, packageInfo.getComponentLocations()); continue; } PackageListener packageListener = packageInfo.getListener(); if (packageListener != null) { packageListener.beforeLoadPackage(packageInfo, resourceLoader); } PackageConfigurer packageConfigurer = packageInfo.getConfigurer(); if (StringUtils.isNotEmpty(packageInfo.getPropertiesLocations())) { for (String location : org.springframework.util.StringUtils.tokenizeToStringArray( packageInfo.getPropertiesLocations(), ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)) { loadConfigureProperties(configureStore, resourceLoader, location, false); } } String[] locations; if (packageConfigurer != null) { locations = packageConfigurer.getPropertiesConfigLocations(resourceLoader); if (locations != null) { for (String location : locations) { loadConfigureProperties(configureStore, resourceLoader, location, false); } } } // ?Spring? pushLocations(contextLocations, packageInfo.getContextLocations()); if (packageConfigurer != null) { locations = packageConfigurer.getContextConfigLocations(resourceLoader); if (locations != null) { for (String location : locations) { pushLocation(contextLocations, location); } } } pushLocations(servletContextLocations, packageInfo.getServletContextLocations()); if (packageConfigurer != null) { locations = packageConfigurer.getServletContextConfigLocations(resourceLoader); if (locations != null) { for (String location : locations) { pushLocation(servletContextLocations, location); } } } packageInfo.setLoaded(true); } // ?dorado-homepropertiesaddon if (StringUtils.isNotEmpty(doradoHome)) { String configureLocation = HOME_LOCATION_PREFIX + "configure.properties"; loadConfigureProperties(configureStore, resourceLoader, configureLocation, true); if (StringUtils.isNotEmpty(runMode)) { loadConfigureProperties(configureStore, resourceLoader, CORE_PROPERTIES_LOCATION_PREFIX + "configure-" + runMode + ".properties", true); loadConfigureProperties(configureStore, resourceLoader, HOME_LOCATION_PREFIX + "configure-" + runMode + ".properties", true); } } Resource resource; // context if (processOriginContextConfigLocation) { intParam = servletContext.getInitParameter(CONTEXT_CONFIG_LOCATION); if (intParam != null) { pushLocations(contextLocations, intParam); } } resource = resourceLoader.getResource(HOME_CONTEXT_XML); if (resource.exists()) { pushLocations(contextLocations, HOME_CONTEXT_XML); } if (StringUtils.isNotEmpty(runMode)) { String extHomeContext = HOME_CONTEXT_PREFIX + '-' + runMode + CONTEXT_FILE_EXT; resource = resourceLoader.getResource(extHomeContext); if (resource.exists()) { pushLocations(contextLocations, extHomeContext); } } // servlet-context intParam = servletContext.getInitParameter(SERVLET_CONTEXT_CONFIG_LOCATION); if (intParam != null) { pushLocations(servletContextLocations, intParam); } resource = resourceLoader.getResource(HOME_SERVLET_CONTEXT_XML); if (resource.exists()) { pushLocations(servletContextLocations, HOME_SERVLET_CONTEXT_XML); } if (StringUtils.isNotEmpty(runMode)) { String extHomeContext = HOME_SERVLET_CONTEXT_PREFIX + '-' + runMode + CONTEXT_FILE_EXT; resource = resourceLoader.getResource(extHomeContext); if (resource.exists()) { pushLocations(servletContextLocations, extHomeContext); } } ConsoleUtils.outputConfigureItem(RESOURCE_LOADER_PROPERTY); ConsoleUtils.outputConfigureItem(BYTE_CODE_PROVIDER_PROPERTY); String contextLocationsFromProperties = configureStore.getString(CONTEXT_CONFIG_PROPERTY); if (contextLocationsFromProperties != null) { pushLocations(contextLocations, contextLocationsFromProperties); } configureStore.set(CONTEXT_CONFIG_PROPERTY, StringUtils.join(getRealResourcesPath(contextLocations), ';')); ConsoleUtils.outputConfigureItem(CONTEXT_CONFIG_PROPERTY); String serlvetContextLocationsFromProperties = configureStore.getString(SERVLET_CONTEXT_CONFIG_PROPERTY); if (serlvetContextLocationsFromProperties != null) { pushLocations(servletContextLocations, serlvetContextLocationsFromProperties); } configureStore.set(SERVLET_CONTEXT_CONFIG_PROPERTY, StringUtils.join(getRealResourcesPath(servletContextLocations), ';')); ConsoleUtils.outputConfigureItem(SERVLET_CONTEXT_CONFIG_PROPERTY); // ?WebContext DoradoContext context = DoradoContext.init(servletContext, false); Context.setFailSafeContext(context); }
From source file:com.flexive.faces.components.tree.dojo.DojoTreeRenderer.java
/** * {@inheritDoc}//w ww.ja v a 2s . c o m */ @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { DojoTree tree = (DojoTree) component; ResponseWriter writer = context.getResponseWriter(); TreeNodeWriter nodeWriter = ((DojoTree) component).getNodeWriter(); nodeWriter.finishResponse(); // close "tree.setChildren" writer.write(";\n"); // init tree reporter (ignoring the context menu listener) writer.write("initializeTreeReporter(_listeners, " + StringUtils.defaultString(tree.getClickHandler(), "null") + ");\n"); String widgetId = tree.getName(); if (tree.getContextMenu() != null) { DojoMenuWriter.writeMenu(writer, widgetId + "Menu", "contextMenu", "TreeContextMenuV3", "TreeMenuItemV3", tree.getContextMenu(), new JsfRelativeUriMapper(), null, tree.getContextMenu().getShowHandler()); // add to tree listeners writer.write("_listeners.push(contextMenu.widgetId);\n"); } writer.write("var tree = dojo.widget.createWidget(\"TreeV3\", " + "{widgetId: \"" + widgetId + "\", listeners: _listeners\n" + (tree.isDragAndDrop() ? ", DndAcceptTypes:\"" + widgetId + "\", DndMode:\"between;onto\"" : "") + "});\n" + "tree.fxController = controller;\n" + (tree.isSelector() ? "tree.fxSelector = selector;\n" : "") + (tree.isDragAndDrop() ? "tree.dndController = dnd;\n" : "") + "tree.setChildren(children);\n" + (tree.isExpandFirstNode() ? "if (children.length > 0) tree.children[0].expand();\n" : "")); writer.write("document.getElementById(\"" + tree.getTargetId() + "\").appendChild(tree.domNode);\n"); // close "addOnLoad" writer.write("});\n"); FxJavascriptUtils.endJavascript(writer); }
From source file:hudson.ivy.IvyModule.java
public String getRelativePathToModuleRoot() { return StringUtils.removeEnd(relativePathToDescriptorFromWorkspace, StringUtils.defaultString(getRelativePathToDescriptorFromModuleRoot(), IVY_XML_PATH)); }
From source file:com.bstek.dorado.data.config.xml.DataParseContext.java
/** * ????//from ww w .j av a 2 s .c o m */ public String setPrivateObjectNameSection(String section) { String prefix = getPrivateObjectName(); prefix = StringUtils.defaultString(prefix, ""); String name = prefix + section; setPrivateObjectName(name); return name; }