Example usage for org.springframework.util StringUtils capitalize

List of usage examples for org.springframework.util StringUtils capitalize

Introduction

In this page you can find the example usage for org.springframework.util StringUtils capitalize.

Prototype

public static String capitalize(String str) 

Source Link

Document

Capitalize a String , changing the first letter to upper case as per Character#toUpperCase(char) .

Usage

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private void startPU(String springXml) throws IOException, ClassNotFoundException {
    if (logger.isDebugEnabled()) {
        logger.debug(logMessage("Starting PU with [" + springXml + "]"));
    }//from   w ww  .ja v  a  2s.  c  o m

    String puName = (String) context.getInitParameter("puName");
    String puPath = (String) context.getInitParameter("puPath");
    String codeserver = context.getExportCodebase();

    org.openspaces.pu.sla.SLA sla = getSLA(getServiceBeanContext());

    Integer instanceId = this.instanceId;
    Integer backupId = this.backupId;

    // Derive instanceId and backupId if not explicitly set
    if (instanceId == null) {
        boolean hasBackups = sla.getNumberOfBackups() > 0;
        if (hasBackups) {
            instanceId = clusterGroup;
            //the first instance is primary so no backupid
            if (context.getServiceBeanConfig().getInstanceID().intValue() > 1) {
                backupId = (context.getServiceBeanConfig().getInstanceID().intValue() - 1);
            }
        } else {
            instanceId = context.getServiceBeanConfig().getInstanceID().intValue();
        }
    }

    //set cluster info
    clusterInfo = new ClusterInfo();
    String clusterSchema = sla.getClusterSchema();
    if (clusterSchema != null) {
        clusterInfo.setSchema(clusterSchema);
        int slaMax = getSLAMax(context);
        int numberOfInstances = Math.max(slaMax, sla.getNumberOfInstances());
        clusterInfo.setNumberOfInstances(numberOfInstances);
    } else {
        clusterInfo.setNumberOfInstances(sla.getNumberOfInstances());
    }
    clusterInfo.setNumberOfBackups(sla.getNumberOfBackups());
    clusterInfo.setInstanceId(instanceId);
    clusterInfo.setBackupId(backupId);
    clusterInfo.setName(puName);

    ClusterInfoParser.guessSchema(clusterInfo);

    logger.info(logMessage("ClusterInfo [" + clusterInfo + "]"));

    MarshalledObject beanLevelPropertiesMarshObj = (MarshalledObject) getServiceBeanContext()
            .getInitParameter("beanLevelProperties");
    BeanLevelProperties beanLevelProperties;
    if (beanLevelPropertiesMarshObj != null) {
        beanLevelProperties = (BeanLevelProperties) beanLevelPropertiesMarshObj.get();
        logger.info(logMessage("BeanLevelProperties " + beanLevelProperties));
    } else {
        beanLevelProperties = new BeanLevelProperties();
    }
    beanLevelProperties.getContextProperties()
            .putAll(ClusterInfoPropertyPlaceholderConfigurer.createProperties(clusterInfo));

    // set a generic work location that can be used by container providers
    File workLocation = new File(SystemInfo.singleton().locations().work());
    workLocation.mkdirs();

    beanLevelProperties.getContextProperties().setProperty("com.gs.work", workLocation.getAbsolutePath());

    boolean downloadPU = false;
    //create PU Container
    ProcessingUnitContainerProvider factory;
    // identify if this is a web app
    final InputStream webXml = openUrlStream(codeserver + puPath + "/WEB-INF/web.xml");
    // identify if this is a .NET one
    final InputStream puConfig = openUrlStream(codeserver + puPath + "/pu.config");
    // identify if this is a .NET interop one
    final InputStream puInteropConfig = openUrlStream(codeserver + puPath + "/pu.interop.config");

    String processingUnitContainerProviderClass;
    if (webXml != null) {
        webXml.close();
        downloadPU = true;
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        String[] classesToLoad = null;
        if ("jetty".equals(jeeContainer)) {
            // pre load the jetty server class so the static shutdown thread will be loaded under it
            classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        }
        // setup class loaders correcly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(
                    new String[] { JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer) }));
            ((ServiceClassLoader) contextClassLoader)
                    .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure JEE class loader", e);
        } finally {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }

        String className = StringUtils.capitalize(jeeContainer) + "JeeProcessingUnitContainerProvider";
        processingUnitContainerProviderClass = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + className;
    } else if (puConfig != null) {
        puConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = DotnetProcessingUnitContainerProvider.class.getName();
    } else if (puInteropConfig != null) {
        puInteropConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
    } else {
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
        if (beanLevelProperties.getContextProperties().getProperty("pu.download", "true")
                .equalsIgnoreCase("true")) {
            downloadPU = true;
        }
    }

    if (beanLevelProperties != null) {
        processingUnitContainerProviderClass = beanLevelProperties.getContextProperties().getProperty(
                ProcessingUnitContainerProvider.CONTAINER_CLASS_PROP, processingUnitContainerProviderClass);
    }

    if (downloadPU) {
        String deployName = puName + "_" + clusterInfo.getRunningNumberOffset1();

        String deployedProcessingUnitsLocation = workLocation.getAbsolutePath() + "/processing-units";

        int uuid = Math.abs(new Random().nextInt());

        deployPath = new File(
                deployedProcessingUnitsLocation + "/" + deployName.replace('.', '_') + "_" + uuid);
        FileSystemUtils.deleteRecursively(deployPath);
        deployPath.mkdirs();

        // backward compatible
        beanLevelProperties.getContextProperties().setProperty("jee.deployPath", deployPath.getAbsolutePath());
        beanLevelProperties.getContextProperties().setProperty("dotnet.deployPath",
                deployPath.getAbsolutePath());

        beanLevelProperties.getContextProperties().setProperty(
                ProcessingUnitContainerProvider.CONTEXT_PROPERTY_DEPLOY_PATH, deployPath.getAbsolutePath());

        try {
            if (isOnGsmHost()) {
                copyPu(puPath, deployPath);
            } else {
                long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                        new File(deployedProcessingUnitsLocation));
                logDownloadSize(size);
            }
        } catch (MalformedURLException mle) {
            logger.warn("Could not determine if GSC and GSM are on the same host", mle);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (UnknownHostException unhe) {
            logger.warn("Could not determine if GSC and GSM are on the same host", unhe);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (RemoteException re) {
            logger.warn("Could not determine if GSC and GSM are on the same host", re);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        }

        // go over listed files that needs to be resolved with properties
        for (Map.Entry entry : beanLevelProperties.getContextProperties().entrySet()) {
            String key = (String) entry.getKey();
            if (key.startsWith("com.gs.resolvePlaceholder")) {
                String path = (String) entry.getValue();
                File input = new File(deployPath, path);
                if (logger.isDebugEnabled()) {
                    logger.debug("Resolving placeholder for file [" + input.getAbsolutePath() + "]");
                }
                BeanLevelPropertiesUtils.resolvePlaceholders(beanLevelProperties, input);
            }
        }
    }

    boolean sharedLibEnabled;
    if (beanLevelProperties.getContextProperties().containsKey("pu.shared-lib.enable")) {
        sharedLibEnabled = beanLevelProperties.getContextProperties().getProperty("pu.shared-lib")
                .equals("true");
    } else {
        sharedLibEnabled = System.getProperty("com.gs.pu.shared-lib.enable", "false").equals("true");
    }

    final boolean disableManifestClassPathJars = Boolean.getBoolean("com.gs.pu.manifest.classpath.disable");
    final boolean disableManifestClassPathCommonPuJars = Boolean
            .getBoolean("com.gs.pu.manifest.classpath.common.disable");

    // this is used to inject the manifest jars to the webapp classloader (if exists)
    List<URL> manifestClassPathJars = new ArrayList<URL>();

    CommonClassLoader commonClassLoader = CommonClassLoader.getInstance();
    // handles class loader libraries
    if (downloadPU) {
        List<URL> libUrls = new ArrayList<URL>();
        File libDir = new File(deployPath, "lib");
        if (libDir.exists()) {
            File[] libFiles = BootIOUtils.listFiles(libDir);
            for (File libFile : libFiles) {
                libUrls.add(libFile.toURI().toURL());
            }
        }

        if (!disableManifestClassPathJars) {
            File manifestFile = new File(deployPath, JarFile.MANIFEST_NAME);

            if (manifestFile.isFile()) {
                try {
                    InputStream manifestStream = new FileInputStream(manifestFile);
                    manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                    libUrls.addAll(manifestClassPathJars);
                } catch (IOException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(failedReadingManifest(puName), e);
                    }
                }
            }

        }

        // add to common class loader
        List<URL> sharedlibUrls = new ArrayList<URL>();
        File sharedlibDir = new File(deployPath, "shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }
        sharedlibDir = new File(deployPath, "WEB-INF/shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }

        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }

            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);

            // add pu-common jar files
            String gsLibOpt = Locator.getLibOptional();
            String gsPuCommon = System.getProperty("com.gs.pu-common", gsLibOpt + "pu-common");

            final String gsLibOptSecurity = Locator.getLibOptionalSecurity();
            libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsPuCommon, gsLibOptSecurity })));

            if (ScalaIdentifier.isScalaLibInClassPath()) {
                String gsLibPlatform = Locator.getLibPlatform();
                // note that we assume BootUtil.toURLs does not work recursively here
                // i.e, only gs-openspaces-scala.jar will be added and not all the files under /lib
                String gsLibPlatformScala = gsLibPlatform + "scala";
                libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsLibPlatformScala })));
            }

            if (!disableManifestClassPathJars && !disableManifestClassPathCommonPuJars) {
                URLClassLoader urlClassLoader = new URLClassLoader(BootUtil.toURLs(new String[] { gsPuCommon }),
                        null /* parent */);
                InputStream puCommonManifestMF = urlClassLoader.getResourceAsStream(JarFile.MANIFEST_NAME);
                if (puCommonManifestMF != null) {
                    List<URL> manifestClassPathComonPuJars = getManifestClassPathJars(puName,
                            puCommonManifestMF);
                    manifestClassPathJars.addAll(manifestClassPathComonPuJars);
                    libUrls.addAll(manifestClassPathComonPuJars);
                }
            }

            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
        try {
            prepareWebApplication(deployPath, clusterInfo, beanLevelProperties);
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to bootstrap web application", e);
        }
    } else {
        // add to service class loader
        List<URL> libUrls = new ArrayList<URL>();
        WebsterFile libDir = new WebsterFile(new URL(codeserver + puPath + "/lib"));
        File[] libFiles = libDir.listFiles();
        for (int i = 0; i < libFiles.length; i++) {
            libUrls.add(new URL(codeserver + puPath + "/lib/" + libFiles[i].getName()));
        }

        if (!disableManifestClassPathJars) {
            InputStream manifestStream = readManifestFromCodeServer(puName, puPath, codeserver, workLocation);
            if (manifestStream != null) {
                manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                libUrls.addAll(manifestClassPathJars);
            }
        }

        // add to common class loader
        WebsterFile sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/shared-lib"));
        File[] sharedlibFiles = sharedlibDir.listFiles();
        List<URL> sharedlibUrls = new ArrayList<URL>();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/shared-lib/" + sharedlibFile.getName()));
        }
        sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/WEB-INF/shared-lib"));
        sharedlibFiles = sharedlibDir.listFiles();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/WEB-INF/shared-lib/" + sharedlibFile.getName()));
        }

        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }

            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
    }

    // handle mule os if there is one class loader
    try {
        contextClassLoader.loadClass("org.mule.api.MuleContext");
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] {
                SystemInfo.singleton().locations().lib() + "/optional/openspaces/mule-os.jar" }));
    } catch (Throwable e) {
        // no mule
    }

    //apply the following only if the pu has the rest element
    if (springXml.contains("<os-core:rest")) {
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        // pre load the jetty server class so the static shutdown thread will be loaded under it

        String[] classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        String jettyJars = System.getProperty("com.gigaspaces.rest.jetty",
                JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer));
        // setup class loaders correctly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { jettyJars,
                    SystemInfo.singleton().locations().lib()
                            + "/platform/jetty/org.apache.jasper.glassfish-2.2.2.v201112011158.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/spring/spring-web-4.1.1.RELEASE.jar",
                    SystemInfo.singleton().locations().lib()
                            + "/optional/spring/spring-webmvc-4.1.1.RELEASE.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-core-2.3.0.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-databind-2.3.0.jar",
                    SystemInfo.singleton().locations().lib()
                            + "/optional/jackson/jackson-annotations-2.3.0.jar",
                    SystemInfo.singleton().locations().lib() + "/platform/rest/xap-rest.jar" }));
            ((ServiceClassLoader) contextClassLoader)
                    .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure class loader", e);
        } finally {
            //TODO check if we need this
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }

    //apply the following only if the pu has the mapdb-blob-store element
    if (springXml.contains("<blob-store:mapdb-blob-store")) {
        String mapdbJar = System.getProperty("com.gigaspaces.blobstore.mapdb",
                SystemInfo.singleton().locations().lib() + "/optional/blobstore/mapdb-blobstore.jar");

        Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { mapdbJar }));
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    //apply the following only if the pu has the rocksdb-blob-store element
    if (springXml.contains("<blob-store:rocksdb-blob-store")
            || springXml.contains("class=\"com.gigaspaces.blobstore.rocksdb.RocksDBBlobStoreHandler\"")) {
        String rocksdbJar = System.getProperty("com.gigaspaces.blobstore.rocksdb",
                SystemInfo.singleton().locations().lib() + "/optional/blobstore/rocksdb-blobstore.jar");

        Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { rocksdbJar }));
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    final Map<String, String> puTags = buildPuTags(clusterInfo);
    MetricRegistrator puMetricRegistrator = metricManager.createRegistrator("pu", puTags);
    this.metricRegistrators = metricManager.registerProcessMetrics(puTags);
    this.metricRegistrators.add(puMetricRegistrator);
    for (Map.Entry<String, String> entry : puTags.entrySet())
        beanLevelProperties.getContextProperties().setProperty("metrics." + entry.getKey(), entry.getValue());
    //inject quiesce state changed event in order let space know to be initialized in quiesced mode
    if (quiesceDetails != null && quiesceDetails.getStatus() == QuiesceState.QUIESCED) {
        beanLevelProperties.getContextProperties().setProperty("quiesce.token",
                quiesceDetails.getToken().toString());
        beanLevelProperties.getContextProperties().setProperty("quiesce.description",
                quiesceDetails.getDescription());
    }
    factory = createContainerProvider(processingUnitContainerProviderClass);
    factory.setDeployPath(deployPath);
    factory.setClassLoader(contextClassLoader);
    factory.setManifestUrls(manifestClassPathJars);

    // only load the spring xml file if it is not a web application (if it is a web application, we will load it with the Bootstrap servlet context loader)
    if (webXml == null && factory instanceof ApplicationContextProcessingUnitContainerProvider) {
        if (StringUtils.hasText(springXml)) {
            // GS-9350: if this is a processing unit with gateway declarations, always try to
            // re-load the pu.xml to support "hot-deploy" (refresh)
            if (springXml.contains("os-gateway:")) {
                String deployPath = beanLevelProperties.getContextProperties().getProperty("deployPath");
                if (StringUtils.hasText(deployPath)) {
                    String newSpringXml = readFile(deployPath + "/META-INF/spring/pu.xml");
                    if (StringUtils.hasText(newSpringXml)) {
                        springXml = newSpringXml; //override with new one
                    }
                }
            }
            Resource resource = new ByteArrayResource(springXml.getBytes());
            ((ApplicationContextProcessingUnitContainerProvider) factory).addConfigLocation(resource);
        }
    }
    factory.setClusterInfo(clusterInfo);
    factory.setBeanLevelProperties(beanLevelProperties);
    factory.setMetricRegistrator(puMetricRegistrator);

    container = factory.createContainer();

    // set the context class loader to the web app class loader if there is one
    // this menas that from now on, and the exported service, will use the context class loader
    ClassLoader webAppClassLoader = SharedServiceData.removeWebAppClassLoader(clusterInfo.getUniqueName());
    if (webAppClassLoader != null) {
        contextClassLoader = webAppClassLoader;
    }
    Thread.currentThread().setContextClassLoader(contextClassLoader);

    buildMembersAliveIndicators();
    buildUndeployingEventListeners();
    buildDumpProcessors();

    ArrayList<Object> serviceDetails = buildServiceDetails();

    buildServiceMonitors();

    buildInvocableServices();

    this.puDetails = new PUDetails(context.getParentServiceID(), clusterInfo, beanLevelProperties,
            serviceDetails.toArray(new Object[serviceDetails.size()]));

    if (container instanceof ApplicationContextProcessingUnitContainer) {
        ApplicationContext applicationContext = ((ApplicationContextProcessingUnitContainer) container)
                .getApplicationContext();

        // inject the application context to all the monitors and schedule them
        // currently use the number of threads in relation to the number of monitors
        int numberOfThreads = watchTasks.size() / 5;
        if (numberOfThreads == 0) {
            numberOfThreads = 1;
        }
        executorService = Executors.newScheduledThreadPool(numberOfThreads);
        for (WatchTask watchTask : watchTasks) {
            if (watchTask.getMonitor() instanceof ApplicationContextMonitor) {
                ((ApplicationContextMonitor) watchTask.getMonitor()).setApplicationContext(applicationContext);
            }
            executorService.scheduleAtFixedRate(watchTask, watchTask.getMonitor().getPeriod(),
                    watchTask.getMonitor().getPeriod(), TimeUnit.MILLISECONDS);
        }
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.command.AssociationCommandFactory.java

/**
 * //from  www .  j av a  2s .com
 * @see org.shept.org.springframework.web.servlet.mvc.delegation.command.CommandFactory#getCommand(org.shept.org.springframework.web.servlet.mvc.delegation.ComponentConfiguration, java.lang.Object, java.lang.String)
 * 
 * @param model
 * @param jp
 * @param mth
 * @return
 */
@Override
public Object getCommand(TargetConfiguration config, Object model) {

    if (model == null) {
        throw new ChainConfigurationException("Configuration error in '" + config.getChainNameDisplay()
                + "'. <Null> model is not allowed for associations");
    }

    // param contains the subForm name that will be overriden if there is an relation defined
    String assoc = relation == null ? config.getTo().getBeanName() : relation;
    if (assoc != null && assoc.startsWith("get")) {
        assoc = relation.substring("get".length());
    }
    String methodGetter = "get" + StringUtils.capitalize(assoc);
    Method mth = ReflectionUtils.findMethod(model.getClass(), methodGetter);
    if (mth == null) {
        return null;
    }
    Class<?> rt = Object.class;
    if (null != mth) {
        rt = mth.getReturnType();
    }
    if (List.class.isAssignableFrom(rt)) {
        return createWrappedList(config, mth, model);
    }
    // TODO better checks for the different result conditions ...
    else if (Collection.class.isAssignableFrom(rt)) {
        throw new ChainConfigurationException("Collection types other than 'List' are currently not supported. "
                + "Type " + rt.getClass().toString() + " is not supported. Use List instead");
    }
    // load a single entity object
    else {
        return createWrappedEntity(config, mth, model);
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.ComponentUtils.java

/**
 * @param ctx/*from  www  .  j a  va 2  s.  co  m*/
 * @param linkName
 * @param sourceName
 * @return
 */
private static TargetConfiguration getChainConfiguration(ApplicationContext ctx, String linkName,
        String sourceName) {
    // TODO introduce a ChainConfigurationHolder instead
    // ChainConfigurationHolder should do initialization checks (duplicate names ...)

    List<TargetConfiguration> chains = getChainConfigurations(ctx, sourceName);

    // check configuration bean names
    for (TargetConfiguration cc : chains) {
        if (StringUtils.hasText(cc.getBeanName())) {
            if (cc.getBeanName().equals(linkName)) {
                logger.info("Chain configuration found for (chain-)bean named '" + linkName + "' from source '"
                        + sourceName + "'");
                return cc;
            }
        }
    }

    // check relation values (w getter)
    String relName = linkName;
    if (!relName.startsWith("get")) {
        relName = "get" + StringUtils.capitalize(relName);
    }
    for (TargetConfiguration cc : chains) {
        if (cc instanceof ChainConfiguration) {
            String rel = ((ChainConfiguration) cc).getRelation();
            if (StringUtils.hasText(rel)) {
                if (rel.equals(relName)) {
                    logger.info("Chain configuration found for relation named '" + linkName + "' from source '"
                            + sourceName + "'");
                    return cc;
                }
            }

        }
    }

    // last but not least check for destination name
    for (TargetConfiguration cc : chains) {
        if (StringUtils.hasText(cc.getTo().getBeanName())) {
            if (cc.getTo().getBeanName().equals(linkName)) {
                logger.info("Chain configuration found for target bean named '" + linkName + "' from source '"
                        + sourceName + "'");
                return cc;
            }
        }
    }
    return null;
}

From source file:org.springbyexample.mvc.method.annotation.ServiceHandlerMapping.java

/**
 * Process and setup any converter handlers if one is configured on <code>RestRequestResource</code>.
 *///  w  ww .j  a va  2s. c o m
private void processConverters(RestRequestResource restRequestResource, RequestMappingInfo mapping,
        Method serviceMethod) {
    ApplicationContext ctx = getApplicationContext();
    Class<?> converterClass = (restRequestResource != null ? restRequestResource.converter() : null);

    if (converterClass != null && converterClass != ServiceValueConstants.DEFAULT_CONVERTER_CLASS) {
        @SuppressWarnings("rawtypes")
        ListConverter converter = (ListConverter) ctx.getBean(converterClass);

        String[] pathPatterns = mapping.getPatternsCondition().getPatterns()
                .toArray(ArrayUtils.EMPTY_STRING_ARRAY);

        String methodSuffix = StringUtils.capitalize(converterHandlerInfo.getPropertyName());
        String getterMethodName = "get" + methodSuffix;
        final String setterMethodName = "set" + methodSuffix;

        final Class<?> returnTypeClass = serviceMethod.getReturnType();
        Method getResultsMethod = ReflectionUtils.findMethod(returnTypeClass, getterMethodName);
        final Class<?> resultReturnTypeClass = getResultsMethod.getReturnType();
        Method setResultsMethod = ReflectionUtils.findMethod(returnTypeClass, setterMethodName,
                resultReturnTypeClass);
        final AtomicReference<Method> altSetResultsMethod = new AtomicReference<Method>();

        // issue with ReflectionUtils, setterResultsMethod sometimes null from the command line (not getter?)
        if (setResultsMethod == null) {
            ReflectionUtils.doWithMethods(returnTypeClass, new MethodCallback() {
                @Override
                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    if (setterMethodName.equals(method.getName())) {
                        altSetResultsMethod.set(method);
                        logger.debug(
                                "Unable to use ReflectionUtils to find setter. returnTypeClass={}  method={} resultReturnTypeClass={}",
                                new Object[] { returnTypeClass, method, resultReturnTypeClass });
                    }
                }
            });
        }

        HandlerInterceptor interceptor = new ConverterHandlerInterceptor(converter, returnTypeClass,
                getResultsMethod, (setResultsMethod != null ? setResultsMethod : altSetResultsMethod.get()));

        MappedInterceptor mappedInterceptor = new MappedInterceptor(pathPatterns, interceptor);
        setInterceptors(new Object[] { mappedInterceptor });

        logger.info("Registered converter post handler for {} with {}.", pathPatterns,
                converterClass.getCanonicalName());
    }
}

From source file:org.springframework.beans.CachedIntrospectionResults.java

@Nullable
PropertyDescriptor getPropertyDescriptor(String name) {
    PropertyDescriptor pd = this.propertyDescriptorCache.get(name);
    if (pd == null && StringUtils.hasLength(name)) {
        // Same lenient fallback checking as in Property...
        pd = this.propertyDescriptorCache.get(StringUtils.uncapitalize(name));
        if (pd == null) {
            pd = this.propertyDescriptorCache.get(StringUtils.capitalize(name));
        }/*from   w w  w .  jav a 2  s. c o  m*/
    }
    return (pd == null || pd instanceof GenericTypeAwarePropertyDescriptor ? pd
            : buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd));
}

From source file:org.springframework.beans.GenericTypeAwarePropertyDescriptor.java

public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName, @Nullable Method readMethod,
        @Nullable Method writeMethod, Class<?> propertyEditorClass) throws IntrospectionException {

    super(propertyName, null, null);
    this.beanClass = beanClass;

    Method readMethodToUse = (readMethod != null ? BridgeMethodResolver.findBridgedMethod(readMethod) : null);
    Method writeMethodToUse = (writeMethod != null ? BridgeMethodResolver.findBridgedMethod(writeMethod)
            : null);/*from  www .j av  a2 s  .c  om*/
    if (writeMethodToUse == null && readMethodToUse != null) {
        // Fallback: Original JavaBeans introspection might not have found matching setter
        // method due to lack of bridge method resolution, in case of the getter using a
        // covariant return type whereas the setter is defined for the concrete property type.
        Method candidate = ClassUtils.getMethodIfAvailable(this.beanClass,
                "set" + StringUtils.capitalize(getName()), (Class<?>[]) null);
        if (candidate != null && candidate.getParameterCount() == 1) {
            writeMethodToUse = candidate;
        }
    }
    this.readMethod = readMethodToUse;
    this.writeMethod = writeMethodToUse;

    if (this.writeMethod != null) {
        if (this.readMethod == null) {
            // Write method not matched against read method: potentially ambiguous through
            // several overloaded variants, in which case an arbitrary winner has been chosen
            // by the JDK's JavaBeans Introspector...
            Set<Method> ambiguousCandidates = new HashSet<>();
            for (Method method : beanClass.getMethods()) {
                if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse)
                        && !method.isBridge()
                        && method.getParameterCount() == writeMethodToUse.getParameterCount()) {
                    ambiguousCandidates.add(method);
                }
            }
            if (!ambiguousCandidates.isEmpty()) {
                this.ambiguousWriteMethods = ambiguousCandidates;
            }
        }
        this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
        GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
    }

    if (this.readMethod != null) {
        this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
    } else if (this.writeMethodParameter != null) {
        this.propertyType = this.writeMethodParameter.getParameterType();
    }

    this.propertyEditorClass = propertyEditorClass;
}

From source file:org.springframework.boot.web.servlet.DynamicRegistrationBean.java

@Override
protected final void register(String description, ServletContext servletContext) {
    D registration = addRegistration(description, servletContext);
    if (registration == null) {
        logger.info(StringUtils.capitalize(description) + " was not registered "
                + "(possibly already registered?)");
        return;/*from   w  w w  . j  ava2 s  .c o m*/
    }
    configure(registration);
}

From source file:org.springframework.boot.web.servlet.RegistrationBean.java

@Override
public final void onStartup(ServletContext servletContext) throws ServletException {
    String description = getDescription();
    if (!isEnabled()) {
        logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
        return;// w ww .  j a  va 2s.co  m
    }
    register(description, servletContext);
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Determine jar file references from the "java.class.path." manifest property and add them
 * to the given set of resources in the form of pointers to the root of the jar file content.
 * @param result the set of resources to add jar roots to
 * @since 4.3//from  w ww .  j a  v  a 2 s  .  co  m
 */
protected void addClassPathManifestEntries(Set<Resource> result) {
    try {
        String javaClassPathProperty = System.getProperty("java.class.path");
        for (String path : StringUtils.delimitedListToStringArray(javaClassPathProperty,
                System.getProperty("path.separator"))) {
            try {
                String filePath = new File(path).getAbsolutePath();
                int prefixIndex = filePath.indexOf(':');
                if (prefixIndex == 1) {
                    // Possibly "c:" drive prefix on Windows, to be upper-cased for proper duplicate detection
                    filePath = StringUtils.capitalize(filePath);
                }
                UrlResource jarResource = new UrlResource(ResourceUtils.JAR_URL_PREFIX
                        + ResourceUtils.FILE_URL_PREFIX + filePath + ResourceUtils.JAR_URL_SEPARATOR);
                // Potentially overlapping with URLClassLoader.getURLs() result above!
                if (!result.contains(jarResource) && !hasDuplicate(filePath, result) && jarResource.exists()) {
                    result.add(jarResource);
                }
            } catch (MalformedURLException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Cannot search for matching files underneath [" + path
                            + "] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to evaluate 'java.class.path' manifest entries: " + ex);
        }
    }
}

From source file:org.springframework.data.jdbc.support.oracle.BeanPropertyStructMapper.java

public STRUCT toStruct(T source, Connection conn, String typeName) throws SQLException {
    StructDescriptor descriptor = new StructDescriptor(typeName, conn);
    ResultSetMetaData rsmd = descriptor.getMetaData();
    int columns = rsmd.getColumnCount();
    Object[] values = new Object[columns];
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PropertyDescriptor fieldMeta = (PropertyDescriptor) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(source);
            if (bw.isReadableProperty(fieldMeta.getName())) {
                try {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Mapping column named \"" + column + "\"" + " to property \""
                                + fieldMeta.getName() + "\"");
                    }// w w  w. java  2 s .  c o m
                    values[i - 1] = bw.getPropertyValue(fieldMeta.getName());
                } catch (NotReadablePropertyException ex) {
                    throw new DataRetrievalFailureException(
                            "Unable to map column " + column + " to property " + fieldMeta.getName(), ex);
                }
            } else {
                logger.warn("Unable to access the getter for " + fieldMeta.getName() + ".  Check that " + "get"
                        + StringUtils.capitalize(fieldMeta.getName()) + " is declared and has public access.");
            }
        }
    }
    STRUCT struct = new STRUCT(descriptor, conn, values);
    return struct;
}