Example usage for org.springframework.util ObjectUtils nullSafeToString

List of usage examples for org.springframework.util ObjectUtils nullSafeToString

Introduction

In this page you can find the example usage for org.springframework.util ObjectUtils nullSafeToString.

Prototype

public static String nullSafeToString(@Nullable short[] array) 

Source Link

Document

Return a String representation of the contents of the specified array.

Usage

From source file:org.crazydog.util.spring.StringUtils.java

/**
 * Convert a {@code String} array into a delimited {@code String} (e.g. CSV).
 * <p>Useful for {@code toString()} implementations.
 * @param arr the array to display/*w  ww .  j av a  2 s. c o m*/
 * @param delim the delimiter to use (typically a ",")
 * @return the delimited {@code String}
 */
public static String arrayToDelimitedString(Object[] arr, String delim) {
    if (org.springframework.util.ObjectUtils.isEmpty(arr)) {
        return "";
    }
    if (arr.length == 1) {
        return ObjectUtils.nullSafeToString(arr[0]);
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < arr.length; i++) {
        if (i > 0) {
            sb.append(delim);
        }
        sb.append(arr[i]);
    }
    return sb.toString();
}

From source file:dstrelec.nats.listener.LoggingErrorHandler.java

@Override
public void handle(Exception thrownException, Message message) {
    log.error("Error while processing: " + ObjectUtils.nullSafeToString(message), thrownException);
}

From source file:gnete.card.web.merch.MerchAction.java

public String addMerchFile() throws Exception {

    Assert.isTrue(IOUtil.testFileFix(uploadFileName, Arrays.asList("txt", "csv")),
            "??");

    String[] regs = this.merchService.addMerchFile(upload, merchInfoReg, this.getSessionUser());

    String msg = "[" + ObjectUtils.nullSafeToString(regs) + "]?";

    this.addActionMessage("/pages/merch/regList.do?goBack=goBack", msg);
    this.log(msg, UserLogType.ADD);

    return SUCCESS;
}

From source file:org.broadleafcommerce.test.BroadleafGenericGroovyXmlWebContextLoader.java

/**
 * {@code BroadleafGenericGroovyXmlWebContextLoader} supports the XML merging that
 * Broadleaf's framework features, but this is handled during the .refresh() method
 * in the loadContext method so this method was only pulled from the original class
 * {@link GenericXmlWebContextLoader} in case of the Spring-Test framework requiring
 * this method to have a particular behavior.
 *
 * @see AbstractGenericWebContextLoader#validateMergedContextConfiguration
 *//*ww w . j  av  a  2 s .  c  o  m*/
protected void validateMergedContextConfiguration(WebMergedContextConfiguration webMergedConfig) {
    if (webMergedConfig.hasClasses()) {
        String msg = String.format(
                "Test class [%s] has been configured with @ContextConfiguration's 'classes' attribute %s, "
                        + "but %s does not support annotated classes.",
                webMergedConfig.getTestClass().getName(),
                ObjectUtils.nullSafeToString(webMergedConfig.getClasses()), getClass().getSimpleName());
        throw new IllegalStateException(msg);
    }
}

From source file:org.eclipse.gemini.blueprint.blueprint.container.support.BlueprintContainerServicePublisher.java

private void registerService(ApplicationContext applicationContext) {
    final Dictionary<String, Object> serviceProperties = new Hashtable<String, Object>();

    Bundle bundle = bundleContext.getBundle();
    String symName = bundle.getSymbolicName();
    serviceProperties.put(Constants.BUNDLE_SYMBOLICNAME, symName);
    serviceProperties.put(BLUEPRINT_SYMNAME, symName);

    Version version = OsgiBundleUtils.getBundleVersion(bundle);
    serviceProperties.put(Constants.BUNDLE_VERSION, version);
    serviceProperties.put(BLUEPRINT_VERSION, version);

    log.info("Publishing BlueprintContainer as OSGi service with properties " + serviceProperties);

    // export just the interface
    final String[] serviceNames = new String[] { BlueprintContainer.class.getName() };

    if (log.isDebugEnabled())
        log.debug("Publishing service under classes " + ObjectUtils.nullSafeToString(serviceNames));

    AccessControlContext acc = SecurityUtils.getAccFrom(applicationContext);

    // publish service
    if (System.getSecurityManager() != null) {
        registration = AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() {
            public ServiceRegistration run() {
                return bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties);
            }/*w  w  w.j  av a  2 s .com*/
        }, acc);
    } else {
        registration = bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties);
    }
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.support.BlueprintContainerCreator.java

public DelegatedExecutionOsgiBundleApplicationContext createApplicationContext(BundleContext bundleContext)
        throws Exception {
    Bundle bundle = bundleContext.getBundle();
    ApplicationContextConfiguration config = new BlueprintContainerConfig(bundle);
    String bundleName = OsgiStringUtils.nullSafeNameAndSymName(bundle);
    if (log.isTraceEnabled())
        log.trace("Created configuration " + config + " for bundle " + bundleName);

    // it's not a spring bundle, ignore it
    if (!config.isSpringPoweredBundle()) {
        if (log.isDebugEnabled())
            log.debug("No blueprint configuration found in bundle " + bundleName + "; ignoring it...");
        return null;
    }//  w  w  w .j a  v a2s  . c  o m

    log.info("Discovered configurations " + ObjectUtils.nullSafeToString(config.getConfigurationLocations())
            + " in bundle [" + bundleName + "]");

    DelegatedExecutionOsgiBundleApplicationContext sdoac = new OsgiBundleXmlApplicationContext(
            config.getConfigurationLocations());
    sdoac.setBundleContext(bundleContext);
    sdoac.setPublishContextAsService(config.isPublishContextAsService());

    return sdoac;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.ExtenderConfiguration.java

/**
* Constructs a new <code>ExtenderConfiguration</code> instance. Locates the extender configuration, creates an
* application context which will returned the extender items.
* 
* @param extenderBundleContext extender OSGi bundle context
*///from  w  w  w  .  j  a  v a  2s.  c  om
public void start(BundleContext extenderBundleContext) {
    Bundle bundle = extenderBundleContext.getBundle();
    Properties properties = new Properties(createDefaultProperties());

    Enumeration<?> enm = bundle.findEntries(EXTENDER_CFG_LOCATION, XML_PATTERN, false);

    if (enm == null) {
        log.info("No custom extender configuration detected; using defaults...");
        synchronized (lock) {
            taskExecutor = createDefaultTaskExecutor();
            shutdownTaskExecutor = createDefaultShutdownTaskExecutor();
            eventMulticaster = createDefaultEventMulticaster();
            contextEventListener = createDefaultApplicationContextListener();
        }
        classLoader = BundleDelegatingClassLoader.createBundleClassLoaderFor(bundle);
    } else {
        String[] configs = copyEnumerationToList(enm);

        log.info("Detected extender custom configurations at " + ObjectUtils.nullSafeToString(configs));
        // create OSGi specific XML context
        ConfigurableOsgiBundleApplicationContext extenderAppCtx = new OsgiBundleXmlApplicationContext(configs);
        extenderAppCtx.setBundleContext(extenderBundleContext);
        extenderAppCtx.refresh();

        synchronized (lock) {
            extenderConfiguration = extenderAppCtx;
            // initialize beans
            taskExecutor = extenderConfiguration.containsBean(TASK_EXECUTOR_NAME)
                    ? extenderConfiguration.getBean(TASK_EXECUTOR_NAME, TaskExecutor.class)
                    : createDefaultTaskExecutor();

            shutdownTaskExecutor = extenderConfiguration.containsBean(SHUTDOWN_TASK_EXECUTOR_NAME)
                    ? extenderConfiguration.getBean(SHUTDOWN_TASK_EXECUTOR_NAME, TaskExecutor.class)
                    : createDefaultShutdownTaskExecutor();

            eventMulticaster = extenderConfiguration.containsBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
                    ? extenderConfiguration.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
                            OsgiBundleApplicationContextEventMulticaster.class)
                    : createDefaultEventMulticaster();

            contextCreator = extenderConfiguration.containsBean(CONTEXT_CREATOR_NAME)
                    ? extenderConfiguration.getBean(CONTEXT_CREATOR_NAME, OsgiApplicationContextCreator.class)
                    : null;

            contextEventListener = extenderConfiguration.containsBean(CONTEXT_LISTENER_NAME)
                    ? extenderConfiguration.getBean(CONTEXT_LISTENER_NAME,
                            OsgiBundleApplicationContextListener.class)
                    : createDefaultApplicationContextListener();
        }

        // get post processors
        postProcessors
                .addAll(extenderConfiguration.getBeansOfType(OsgiBeanFactoryPostProcessor.class).values());

        // get dependency factories
        dependencyFactories
                .addAll(extenderConfiguration.getBeansOfType(OsgiServiceDependencyFactory.class).values());

        classLoader = extenderConfiguration.getClassLoader();
        // extender properties using the defaults as backup
        if (extenderConfiguration.containsBean(PROPERTIES_NAME)) {
            Properties customProperties = extenderConfiguration.getBean(PROPERTIES_NAME, Properties.class);
            Enumeration<?> propertyKey = customProperties.propertyNames();
            while (propertyKey.hasMoreElements()) {
                String property = (String) propertyKey.nextElement();
                properties.setProperty(property, customProperties.getProperty(property));
            }
        }
    }

    synchronized (lock) {
        shutdownWaitTime = getShutdownWaitTime(properties);
        shutdownAsynchronously = getShutdownAsynchronously(properties);
        dependencyWaitTime = getDependencyWaitTime(properties);
        processAnnotation = getProcessAnnotations(properties);
    }

    // load default dependency factories
    addDefaultDependencyFactories();

    // allow post processing
    contextCreator = postProcess(contextCreator);
}

From source file:org.eclipse.gemini.blueprint.extender.support.DefaultOsgiApplicationContextCreator.java

public DelegatedExecutionOsgiBundleApplicationContext createApplicationContext(BundleContext bundleContext)
        throws Exception {
    Bundle bundle = bundleContext.getBundle();
    ApplicationContextConfiguration config = new ApplicationContextConfiguration(bundle, configurationScanner);
    if (log.isTraceEnabled())
        log.trace("Created configuration " + config + " for bundle "
                + OsgiStringUtils.nullSafeNameAndSymName(bundle));

    // it's not a spring bundle, ignore it
    if (!config.isSpringPoweredBundle()) {
        return null;
    }//from www .ja  v  a 2s  .  co m

    log.info("Discovered configurations " + ObjectUtils.nullSafeToString(config.getConfigurationLocations())
            + " in bundle [" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]");

    DelegatedExecutionOsgiBundleApplicationContext sdoac = new OsgiBundleXmlApplicationContext(
            config.getConfigurationLocations());
    sdoac.setBundleContext(bundleContext);
    sdoac.setPublishContextAsService(config.isPublishContextAsService());

    return sdoac;
}

From source file:org.eclipse.gemini.blueprint.extender.support.internal.ConfigUtils.java

public static boolean matchExtenderVersionRange(Bundle bundle, String header, Version versionToMatch) {
    Assert.notNull(bundle);/*from  w  ww .  j  av  a 2s.c  om*/
    // get version range
    String range = bundle.getHeaders().get(header);

    boolean trace = log.isTraceEnabled();

    // empty value = empty version = *
    if (!StringUtils.hasText(range))
        return true;

    if (trace)
        log.trace("discovered " + header + " header w/ value=" + range);

    // do we have a range or not ?
    range = StringUtils.trimWhitespace(range);

    // a range means one comma
    int commaNr = StringUtils.countOccurrencesOf(range, COMMA);

    // no comma, no intervals
    if (commaNr == 0) {
        Version version = Version.parseVersion(range);

        return versionToMatch.equals(version);
    }

    if (commaNr == 1) {

        // sanity check
        if (!((range.startsWith(LEFT_CLOSED_INTERVAL) || range.startsWith(LEFT_OPEN_INTERVAL))
                && (range.endsWith(RIGHT_CLOSED_INTERVAL) || range.endsWith(RIGHT_OPEN_INTERVAL)))) {
            throw new IllegalArgumentException("range [" + range + "] is invalid");
        }

        boolean equalMin = range.startsWith(LEFT_CLOSED_INTERVAL);
        boolean equalMax = range.endsWith(RIGHT_CLOSED_INTERVAL);

        // remove interval brackets
        range = range.substring(1, range.length() - 1);

        // split the remaining string in two pieces
        String[] pieces = StringUtils.split(range, COMMA);

        if (trace)
            log.trace("discovered low/high versions : " + ObjectUtils.nullSafeToString(pieces));

        Version minVer = Version.parseVersion(pieces[0]);
        Version maxVer = Version.parseVersion(pieces[1]);

        if (trace)
            log.trace("comparing version " + versionToMatch + " w/ min=" + minVer + " and max=" + maxVer);

        boolean result = true;

        int compareMin = versionToMatch.compareTo(minVer);

        if (equalMin)
            result = (result && (compareMin >= 0));
        else
            result = (result && (compareMin > 0));

        int compareMax = versionToMatch.compareTo(maxVer);

        if (equalMax)
            result = (result && (compareMax <= 0));
        else
            result = (result && (compareMax < 0));

        return result;
    }

    // more then one comma means incorrect range

    throw new IllegalArgumentException("range [" + range + "] is invalid");
}

From source file:org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver.java

/**
 * Searches for the given pattern inside the imported bundle. This translates to pattern matching on the imported
 * packages./*from w w w. j  a va2  s  .c  o m*/
 * 
 * @param importedBundle imported bundle
 * @param path path used for pattern matching
 * @param foundPaths collection of found results
 */
@SuppressWarnings("unchecked")
private void findImportedBundleMatchingResource(final ImportedBundle importedBundle, String rootPath,
        String path, final Collection<String> foundPaths) throws IOException {

    final boolean trace = logger.isTraceEnabled();

    String[] packages = importedBundle.getImportedPackages();

    if (trace)
        logger.trace("Searching path [" + path + "] on imported pkgs " + ObjectUtils.nullSafeToString(packages)
                + "...");

    final boolean startsWithSlash = rootPath.startsWith(FOLDER_SEPARATOR);

    for (int i = 0; i < packages.length; i++) {
        // transform the package name into a path
        String pkg = packages[i].replace(DOT, SLASH) + SLASH;

        if (startsWithSlash) {
            pkg = FOLDER_SEPARATOR + pkg;
        }

        final PathMatcher matcher = getPathMatcher();
        // if the imported package matches the path
        if (matcher.matchStart(path, pkg)) {
            Bundle bundle = importedBundle.getBundle();
            // 1. look at the Bundle jar root
            Enumeration<String> entries = bundle.getEntryPaths(pkg);
            while (entries != null && entries.hasMoreElements()) {
                String entry = entries.nextElement();
                if (startsWithSlash)
                    entry = FOLDER_SEPARATOR + entry;

                if (matcher.match(path, entry)) {
                    if (trace)
                        logger.trace("Found entry [" + entry + "]");
                    foundPaths.add(entry);
                }
            }
            // 2. Do a Bundle-Classpath lookup (since the jar might use a different classpath)
            Collection<String> cpMatchingPaths = findBundleClassPathMatchingPaths(bundle, path);
            foundPaths.addAll(cpMatchingPaths);
        }
    }
}