问:
Deploying Spring Boot app to Weblogic -- Weblogic is trying to load my main class as an XML resource and failing
I'm moving my application from my dev environment to my test environment.

What is the same:

Weblogic version (10.3.6)

Weblogic-hosted libraries (none)

data source JNDI name

What is different:

dev is 1 server behind a proxy; test is 2 servers behind a proxy, both pointing to the same DB

different database instances (but same schema)

our application is isolated in dev, but colocated in test (several apps running on the server)

Stack trace and configuration files are below.

It looks to me like, WegLogic is trying to open my Main class (TctWebApplication) as an xml context file, and failing because A) it's not XML, and B) there is no file called TctWebApplication -- just a class definition on the classpath which a Java classloader would be able to find.

As far as we can tell, none of the other applications colocated with us are using Spring, so none of them should be setting any old Spring property that limits it to XML configuration.

What else could cause this?

This SO question looks superficially similar, but it isn't quite the same, and we're not running on the Weblogic version where that issue was introduced. I haven't found anything else that looks similar yet.

Note that although I have some Maven configuration for deploying directly to Weblogic, I am instead manually deploying through the Weglogic console. Just in case that's relevant.

The stack trace I'm getting in test:

```<code>15:48:26.612 [[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loadi
ng XML bean definitions from ServletContext resource [/<package name redacted>.TctWebApplication]
15:48:26.627 [[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] ERROR org.springframework.web.context.ContextLoader - Context initializati
on failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<package name redacted>.TctWebApplication
]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:349)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
        at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
        at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:481)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:181)
        at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1871)
        at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3173)
        at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1529)
        at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:488)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
        at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:247)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:27)
        at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:671)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:212)
        at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:44)
        at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:161)
        at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
        at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:573)
        at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
        at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
        at weblogic.deploy.internal.targetserver.operations.StartOperation.doCommit(StartOperation.java:149)
        at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:327)
        at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:844)
        at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1253)
        at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:440)
        at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:163)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
        at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:550)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:263)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:117)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        ... 50 common frames omitted
<Jun 7, 2017 3:48:26 PM EDT> <Warning> <HTTP> <BEA-101162> <User defined listener org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener failed: or
g.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<package name redacted>.TctWebApplication];
 nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication].
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<package name redacted>.TctWebApplication
]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:349)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        Truncated. see log file for complete stacktrace
Caused By: java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:117)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        Truncated. see log file for complete stacktrace
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value><-- package name redacted-->.TctWebApplication</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <!-- file to load -->
        <param-name>log4j-init-file</param-name>
        <param-value>log4j.xml</param-value>
    </context-param>
    <context-param>
        <!-- load from classpath -->
        <param-name>load-config-with-classloader</param-name>
        <param-value>true</param-value>
    </context-param>

    <listener>
        <listener-class><-- package name redacted-->.Log4jContextListener
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextAttribute</param-name>
            <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>SecurityFilter</filter-name>
        <filter-class><-- package name redacted-->.SecurityFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>SecurityFilter</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>
</web-app>
</code>```

weblogic.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd         http://xmlns.oracle.com/weblogic/weblogic-web-app         http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
    <wls:context-root>tct</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j</wls:package-name>
            <wls:package-name>javax.persistence</wls:package-name>
            <wls:package-name>org.eclipse.persistence.*</wls:package-name>
            <wls:package-name>org.joda.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>
</code>```

TctWebApplication.java:

```<code>@SpringBootApplication
@Import({ JpaConfiguration.class, ReportingConfiguration.class })
@ImportResource("classpath:applicationContext-security.xml")
public class TctWebApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
    private Logger logger = LoggerFactory.getLogger(TctWebApplication.class);

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(TctWebApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TctWebApplication.class);
    }
}
</code>```

web project pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tct-web</artifactId>
    <packaging>war</packaging>

    <name>TCT Web</name>
    <description>Web interface for the TCT application</description>

    <parent>
        <groupId><-- group id redacted --></groupId>
        <artifactId>travel-comp-time</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>..</relativePath>
    </parent>

    <properties>
        <start-class><-- package name redacted -->.TctWebApplication</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>tct-data</artifactId>
        </dependency>
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>tct-security</artifactId>
        </dependency>
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>tct-reporting</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-legacy</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
            <!-- This ensures that the Tomcat starter doesn't interfere with WebLogic's
                servlet container -->
        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports-fonts</artifactId>
            <version>5.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
        </dependency>

        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>ws-sec</artifactId>
            <version>2.5.10</version>
            <!-- <scope>provided</scope> -->
        </dependency>

        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>secapi-spring</artifactId>
            <version>1.2.0-BUILD-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Transient dependencies needed by the security library -->
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>CustomLogger</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>axis</groupId>
            <artifactId>axis-ant</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml</groupId>
            <artifactId>jaxrpc</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.soap</groupId>
            <artifactId>saaj</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-discovery</groupId>
            <artifactId>commons-discovery</artifactId>
            <version>0.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.0.4</version>
        </dependency>
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <!-- To get this working, make sure you install the weblogic-maven-plugin.jar.
                    Then you can run this command from a terminal: mvn com.oracle.weblogic:weblogic-maven-plugin:deploy -->
                <groupId>com.oracle.weblogic</groupId>
                <artifactId>weblogic-maven-plugin</artifactId>
                <version>10.3.6.0</version>
                <configuration>
                    <adminurl>t3://localhost:7001</adminurl>
                    <user>weblogic</user>
                    <password>weblogic1</password>
                    <upload>true</upload>
                    <action>deploy</action>
                    <remote>false</remote>
                    <verbose>true</verbose>
                    <source>${project.build.directory}/${project.build.finalName}.${project.packaging}</source>
                    <name>${project.build.finalName}</name>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Parent project pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId><-- group id redacted --></groupId>
    <artifactId>travel-comp-time</artifactId>
    <packaging>pom</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Travel Comp Time Application</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <modules>
        <module>tct-data</module>
        <module>tct-reporting</module>
        <module>tct-security</module>
        <module>tct-web</module>
    </modules>

    <properties>
        <!-- set versions here so all modules use same version of dependencies,
            etc -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.source>1.7</maven.compiler.source>
        <oracle.version>12.1.0.2</oracle.version>
        <eclipselink.version>2.6.4</eclipselink.version>
        <jasperreports.version>6.2.0</jasperreports.version>
        <spring-boot-legacy.version>1.0.2.RELEASE</spring-boot-legacy.version>
        <jquery.version>3.1.0</jquery.version>
        <jquery-ui.version>1.12.1</jquery-ui.version>
        <bootstrap.version>3.3.7</bootstrap.version>
    </properties>

    <dependencies>
        <!-- <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency> -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId><-- group id redacted --></groupId>
                <artifactId>tct-data</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId><-- group id redacted --></groupId>
                <artifactId>tct-security</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId><-- group id redacted --></groupId>
                <artifactId>tct-reporting</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc7</artifactId>
                <version>${oracle.version}</version>
            </dependency>
            <dependency>
                <groupId>org.eclipse.persistence</groupId>
                <artifactId>org.eclipse.persistence.jpa</artifactId>
                <version>${eclipselink.version}</version>
            </dependency>
            <dependency>
                <groupId>org.eclipse.persistence</groupId>
                <artifactId>org.eclipse.persistence.oracle</artifactId>
                <version>${eclipselink.version}</version>
            </dependency>
            <dependency>
                <groupId>net.sf.jasperreports</groupId>
                <artifactId>jasperreports</artifactId>
                <version>${jasperreports.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-legacy</artifactId>
                <version>${spring-boot-legacy.version}</version>
            </dependency>

            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>jquery</artifactId>
                <version>${jquery.version}</version>
            </dependency>
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>jquery-ui</artifactId>
                <version>${jquery-ui.version}</version>
            </dependency>
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>${bootstrap.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/*IntegrationTest.java</exclude>
                    </excludes>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*IntegrationTest.java</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <!-- Uncomment/comment this in order to fail the build if any integration
                        test fail -->
                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>3.0.3</version>
            </plugin>
            <!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId>
                <version>2.17</version> <reportSets> <reportSet> <reports> <report>checkstyle</report>
                </reports> </reportSet> </reportSets> </plugin> -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <instrumentation>
                        <ignoreTrivial>true</ignoreTrivial>
                    </instrumentation>
                </configuration>
            </plugin>

        </plugins>
    </reporting>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>
</code>```

We do have some xml config for our spring security stuff, because the organization has some custom things that I didn't want to try to modernize just yet, but it's never even getting to the point of importing it in my Main class up there, and once I redacted it there would be little useful information, so I'm not posting it at the moment.

答:
Add this line <wls:package-name>org.springframework.*</wls:package-name> to weblogic.xml should fix the issue.

```<code><?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd         http://xmlns.oracle.com/weblogic/weblogic-web-app         http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
    <wls:context-root>tct</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j</wls:package-name>
            <wls:package-name>javax.persistence</wls:package-name>
            <wls:package-name>org.eclipse.persistence.*</wls:package-name>
            <wls:package-name>org.joda.*</wls:package-name>
            <wls:package-name>org.springframework.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>
</code>```

Body:
I'm moving my application from my dev environment to my test environment.

What is the same:

Weblogic version (10.3.6)

Weblogic-hosted libraries (none)

data source JNDI name

What is different:

dev is 1 server behind a proxy; test is 2 servers behind a proxy, both pointing to the same DB

different database instances (but same schema)

our application is isolated in dev, but colocated in test (several apps running on the server)

Stack trace and configuration files are below.

It looks to me like, WegLogic is trying to open my Main class (TctWebApplication) as an xml context file, and failing because A) it's not XML, and B) there is no file called TctWebApplication -- just a class definition on the classpath which a Java classloader would be able to find.

As far as we can tell, none of the other applications colocated with us are using Spring, so none of them should be setting any old Spring property that limits it to XML configuration.

What else could cause this?

This SO question looks superficially similar, but it isn't quite the same, and we're not running on the Weblogic version where that issue was introduced. I haven't found anything else that looks similar yet.

Note that although I have some Maven configuration for deploying directly to Weblogic, I am instead manually deploying through the Weglogic console. Just in case that's relevant.

The stack trace I'm getting in test:

15:48:26.612 [[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loadi
ng XML bean definitions from ServletContext resource [/<package name redacted>.TctWebApplication]
15:48:26.627 [[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] ERROR org.springframework.web.context.ContextLoader - Context initializati
on failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<package name redacted>.TctWebApplication
]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:349)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
        at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
        at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:481)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:181)
        at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1871)
        at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3173)
        at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1529)
        at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:488)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
        at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:247)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:27)
        at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:671)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:212)
        at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:44)
        at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:161)
        at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
        at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:573)
        at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
        at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
        at weblogic.deploy.internal.targetserver.operations.StartOperation.doCommit(StartOperation.java:149)
        at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:327)
        at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:844)
        at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1253)
        at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:440)
        at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:163)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
        at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:550)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:263)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:117)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        ... 50 common frames omitted
<Jun 7, 2017 3:48:26 PM EDT> <Warning> <HTTP> <BEA-101162> <User defined listener org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener failed: or
g.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<package name redacted>.TctWebApplication];
 nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication].
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<package name redacted>.TctWebApplication
]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:349)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        Truncated. see log file for complete stacktrace
Caused By: java.io.FileNotFoundException: Could not open ServletContext resource [/<package name redacted>.TctWebApplication]
        at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:117)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        Truncated. see log file for complete stacktrace

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value><-- package name redacted-->.TctWebApplication</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener</listener-class>
    </listener>

    <context-param>

        <param-name>log4j-init-file</param-name>
        <param-value>log4j.xml</param-value>
    </context-param>
    <context-param>

        <param-name>load-config-with-classloader</param-name>
        <param-value>true</param-value>
    </context-param>

    <listener>
        <listener-class><-- package name redacted-->.Log4jContextListener
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextAttribute</param-name>
            <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>SecurityFilter</filter-name>
        <filter-class><-- package name redacted-->.SecurityFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>SecurityFilter</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>
</web-app>

weblogic.xml:

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd         http://xmlns.oracle.com/weblogic/weblogic-web-app         http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
    <wls:context-root>tct</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j</wls:package-name>
            <wls:package-name>javax.persistence</wls:package-name>
            <wls:package-name>org.eclipse.persistence.*</wls:package-name>
            <wls:package-name>org.joda.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>

TctWebApplication.java:

@SpringBootApplication
@Import({ JpaConfiguration.class, ReportingConfiguration.class })
@ImportResource("classpath:applicationContext-security.xml")
public class TctWebApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
    private Logger logger = LoggerFactory.getLogger(TctWebApplication.class);

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(TctWebApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TctWebApplication.class);
    }
}

web project pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tct-web</artifactId>
    <packaging>war</packaging>

    <name>TCT Web</name>
    <description>Web interface for the TCT application</description>

    <parent>
        <groupId><-- group id redacted --></groupId>
        <artifactId>travel-comp-time</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>..</relativePath>
    </parent>

    <properties>
        <start-class><-- package name redacted -->.TctWebApplication</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>tct-data</artifactId>
        </dependency>
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>tct-security</artifactId>
        </dependency>
        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>tct-reporting</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-legacy</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>

        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports-fonts</artifactId>
            <version>5.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
        </dependency>

        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>ws-sec</artifactId>
            <version>2.5.10</version>

        </dependency>

        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>secapi-spring</artifactId>
            <version>1.2.0-BUILD-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId><-- group id redacted --></groupId>
            <artifactId>CustomLogger</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>axis</groupId>
            <artifactId>axis-ant</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml</groupId>
            <artifactId>jaxrpc</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.soap</groupId>
            <artifactId>saaj</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-discovery</groupId>
            <artifactId>commons-discovery</artifactId>
            <version>0.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.0.4</version>
        </dependency>
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>

                <groupId>com.oracle.weblogic</groupId>
                <artifactId>weblogic-maven-plugin</artifactId>
                <version>10.3.6.0</version>
                <configuration>
                    <adminurl>t3://localhost:7001</adminurl>
                    <user>weblogic</user>
                    <password>weblogic1</password>
                    <upload>true</upload>
                    <action>deploy</action>
                    <remote>false</remote>
                    <verbose>true</verbose>
                    <source>${project.build.directory}/${project.build.finalName}.${project.packaging}</source>
                    <name>${project.build.finalName}</name>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Parent project pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId><-- group id redacted --></groupId>
    <artifactId>travel-comp-time</artifactId>
    <packaging>pom</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Travel Comp Time Application</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath />
    </parent>

    <modules>
        <module>tct-data</module>
        <module>tct-reporting</module>
        <module>tct-security</module>
        <module>tct-web</module>
    </modules>

    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.source>1.7</maven.compiler.source>
        <oracle.version>12.1.0.2</oracle.version>
        <eclipselink.version>2.6.4</eclipselink.version>
        <jasperreports.version>6.2.0</jasperreports.version>
        <spring-boot-legacy.version>1.0.2.RELEASE</spring-boot-legacy.version>
        <jquery.version>3.1.0</jquery.version>
        <jquery-ui.version>1.12.1</jquery-ui.version>
        <bootstrap.version>3.3.7</bootstrap.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId><-- group id redacted --></groupId>
                <artifactId>tct-data</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId><-- group id redacted --></groupId>
                <artifactId>tct-security</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId><-- group id redacted --></groupId>
                <artifactId>tct-reporting</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc7</artifactId>
                <version>${oracle.version}</version>
            </dependency>
            <dependency>
                <groupId>org.eclipse.persistence</groupId>
                <artifactId>org.eclipse.persistence.jpa</artifactId>
                <version>${eclipselink.version}</version>
            </dependency>
            <dependency>
                <groupId>org.eclipse.persistence</groupId>
                <artifactId>org.eclipse.persistence.oracle</artifactId>
                <version>${eclipselink.version}</version>
            </dependency>
            <dependency>
                <groupId>net.sf.jasperreports</groupId>
                <artifactId>jasperreports</artifactId>
                <version>${jasperreports.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-legacy</artifactId>
                <version>${spring-boot-legacy.version}</version>
            </dependency>

            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>jquery</artifactId>
                <version>${jquery.version}</version>
            </dependency>
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>jquery-ui</artifactId>
                <version>${jquery-ui.version}</version>
            </dependency>
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>${bootstrap.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/*IntegrationTest.java</exclude>
                    </excludes>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*IntegrationTest.java</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>

                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>3.0.3</version>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <instrumentation>
                        <ignoreTrivial>true</ignoreTrivial>
                    </instrumentation>
                </configuration>
            </plugin>

        </plugins>
    </reporting>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

We do have some xml config for our spring security stuff, because the organization has some custom things that I didn't want to try to modernize just yet, but it's never even getting to the point of importing it in my Main class up there, and once I redacted it there would be little useful information, so I'm not posting it at the moment.

Body:
Add this line <wls:package-name>org.springframework.*</wls:package-name> to weblogic.xml should fix the issue.

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd         http://xmlns.oracle.com/weblogic/weblogic-web-app         http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
    <wls:context-root>tct</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j</wls:package-name>
            <wls:package-name>javax.persistence</wls:package-name>
            <wls:package-name>org.eclipse.persistence.*</wls:package-name>
            <wls:package-name>org.joda.*</wls:package-name>
            <wls:package-name>org.springframework.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>


来源: stackexchange

问:
sparse autoencoder cost function in tensorflow
I've been going through a variety of TensorFlow tutorials to try to familiarize myself with how it works; and I've become interested in utilizing autoencoders.

I started by using the model autoencoder in Tensorflow's models repository:

https://github.com/tensorflow/models/tree/master/autoencoder

I got it working, and while visualizing the weights, expected to see something like this:

however, my autoencoder gives me garbage-looking weights (despite accurately recreating the input image).

Further reading suggests that what I'm missing is that my autoencoder is not sparse, so I need to enforce a sparsity cost to the weights.

I've tried to add a sparsity cost to the original code (based off of this example3), but it doesn't seem to change the weights to looking like the model ones.

How can I properly change the cost to get features that look like the ones that a typically found in the autoencoded MNIST dataset?  My modified model is here:

```<code>import numpy as np
import random
import math
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt

def xavier_init(fan_in, fan_out, constant = 1):
    low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
    high = constant * np.sqrt(6.0 / (fan_in + fan_out))
    return tf.random_uniform((fan_in, fan_out), minval = low, maxval = high, dtype = tf.float32)

class AdditiveGaussianNoiseAutoencoder(object):
    def __init__(self, n_input, n_hidden, transfer_function = tf.nn.sigmoid, optimizer = tf.train.AdamOptimizer(),
                 scale = 0.1):
        self.n_input = n_input
        self.n_hidden = n_hidden
        self.transfer = transfer_function
        self.scale = tf.placeholder(tf.float32)
        self.training_scale = scale
        network_weights = self._initialize_weights()
        self.weights = network_weights
        self.sparsity_level= 0.1#np.repeat([0.05], self.n_hidden).astype(np.float32)
        self.sparse_reg = 10

        # model
        self.x = tf.placeholder(tf.float32, [None, self.n_input])
        self.hidden = self.transfer(tf.add(tf.matmul(self.x + scale * tf.random_normal((n_input,)),
                self.weights['w1']),
                self.weights['b1']))
        self.reconstruction = tf.add(tf.matmul(self.hidden, self.weights['w2']), self.weights['b2'])

        # cost
        self.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0)) + self.sparse_reg \
                        * self.kl_divergence(self.sparsity_level, self.hidden)

        self.optimizer = optimizer.minimize(self.cost)

        init = tf.global_variables_initializer()
        self.sess = tf.Session()
        self.sess.run(init)

    def _initialize_weights(self):
        all_weights = dict()
        all_weights['w1'] = tf.Variable(xavier_init(self.n_input, self.n_hidden))
        all_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden], dtype = tf.float32))
        all_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden, self.n_input], dtype = tf.float32))
        all_weights['b2'] = tf.Variable(tf.zeros([self.n_input], dtype = tf.float32))
        return all_weights

    def partial_fit(self, X):
        cost, opt = self.sess.run((self.cost, self.optimizer), feed_dict = {self.x: X,
                                                                            self.scale: self.training_scale
                                                                            })
        return cost

    def kl_divergence(self, p, p_hat):
        return tf.reduce_mean(p * tf.log(p) - p * tf.log(p_hat) + (1 - p) * tf.log(1 - p) - (1 - p) * tf.log(1 - p_hat))

    def calc_total_cost(self, X):
        return self.sess.run(self.cost, feed_dict = {self.x: X,
                                                     self.scale: self.training_scale
                                                     })

    def transform(self, X):
        return self.sess.run(self.hidden, feed_dict = {self.x: X,
                                                       self.scale: self.training_scale
                                                       })

    def generate(self, hidden = None):
        if hidden is None:
            hidden = np.random.normal(size = self.weights["b1"])
        return self.sess.run(self.reconstruction, feed_dict = {self.hidden: hidden})

    def reconstruct(self, X):
        return self.sess.run(self.reconstruction, feed_dict = {self.x: X,
                                                               self.scale: self.training_scale
                                                               })

    def getWeights(self):
        return self.sess.run(self.weights['w1'])

    def getBiases(self):
        return self.sess.run(self.weights['b1'])

mnist = input_data.read_data_sets('MNIST_data', one_hot = True)

def get_random_block_from_data(data, batch_size):
    start_index = np.random.randint(0, len(data) - batch_size)
    return data[start_index:(start_index + batch_size)]

X_train = mnist.train.images
X_test = mnist.test.images

n_samples = int(mnist.train.num_examples)
training_epochs = 50
batch_size = 128
display_step = 1

autoencoder = AdditiveGaussianNoiseAutoencoder(n_input = 784,
                                               n_hidden = 200,
                                               transfer_function = tf.nn.sigmoid,
                                               optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01),
                                               scale = 0.01)

for epoch in range(training_epochs):
    avg_cost = 0.
    total_batch = int(n_samples / batch_size)
    # Loop over all batches
    for i in range(total_batch):
        batch_xs = get_random_block_from_data(X_train, batch_size)

        # Fit training using batch data
        cost = autoencoder.partial_fit(batch_xs)
        # Compute average loss
        avg_cost += cost / n_samples * batch_size

    # Display logs per epoch step
    if epoch % display_step == 0:
        print("Epoch:", '%04d' % (epoch + 1), "cost=", avg_cost)

print("Total cost: " + str(autoencoder.calc_total_cost(X_test)))

imageToUse = random.choice(mnist.test.images)

plt.imshow(np.reshape(imageToUse,[28,28]), interpolation="nearest", cmap="gray", clim=(0, 1.0))
plt.show()

# input weights
wts = autoencoder.getWeights()
dim = math.ceil(math.sqrt(autoencoder.n_hidden))
plt.figure(1, figsize=(dim, dim))
for i in range(0,autoencoder.n_hidden):
    im = wts.flatten()[i::autoencoder.n_hidden].reshape((28,28))
    plt.subplot(dim, dim, i+1)
    #plt.title('Feature Weights ' + str(i))
    plt.imshow(im, cmap="gray", clim=(-1.0, 1.0))
    plt.colorbar()
plt.show()

predicted_imgs = autoencoder.reconstruct(X_test[:100])

# plot the reconstructed images
plt.figure(1, figsize=(10, 10))
plt.title('Autoencoded Images')
for i in range(0,100):
    im = predicted_imgs[i].reshape((28,28))
    plt.subplot(10, 10, i+1)
    plt.imshow(im, cmap="gray", clim=(0.0, 1.0))
plt.show()
</code>```

答:
I don't know that this will work for you, but I have seen it promote some sparsity in my own networks. I would recommend modifying your loss to use a combination of softmax cross entropy (or KL divergence if you wish) and l2 regularization loss on the weights. I calculate the l2 loss with:

```<code>l2 = sum(tf.nn.l2_loss(var) for var in tf.trainable_variables() if not 'biases' in var.name)
</code>```

This makes me regularize only on the weights, not biases, assuming that you have "biases" in the name of your bias tensors (lots of the tf.contrib.rnn library names bias tensors so that this works). The overall cost function I use is then:

```<code>cost = tf.nn.softmax_or_kl_divergence_or_whatever(labels=labels, logits=logits)
cost = tf.reduce_mean(cost)
cost = cost + beta * l2
</code>```

where beta is a hyperparameter of the network that I then vary when exploring my hyperparameter space.

Another option, very similar to this, is to use l1 regularization instead. This is supposed to promote sparsity more than l2 regularization. In my own examples I was not explicitly trying to promote sparsity, but saw it as a consequence of l2 regularization, but maybe l1 will give you more luck. You can implement l1 regularization with something like:

```<code>l1 = sum(tf.reduce_sum(tf.abs(var)) for var in tf.trainable_variables() if not 'biases' in var.name)
</code>```

followed by the cost definition above, substituting l1 for l2.

ContentLicense: CC BY-SA 3.0

Body:
I've been going through a variety of TensorFlow tutorials to try to familiarize myself with how it works; and I've become interested in utilizing autoencoders.

I started by using the model autoencoder in Tensorflow's models repository:

https://github.com/tensorflow/models/tree/master/autoencoder

I got it working, and while visualizing the weights, expected to see something like this:

however, my autoencoder gives me garbage-looking weights (despite accurately recreating the input image).

Further reading suggests that what I'm missing is that my autoencoder is not sparse, so I need to enforce a sparsity cost to the weights.

I've tried to add a sparsity cost to the original code (based off of this example3), but it doesn't seem to change the weights to looking like the model ones.

How can I properly change the cost to get features that look like the ones that a typically found in the autoencoded MNIST dataset?  My modified model is here:

import numpy as np
import random
import math
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt

def xavier_init(fan_in, fan_out, constant = 1):
    low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
    high = constant * np.sqrt(6.0 / (fan_in + fan_out))
    return tf.random_uniform((fan_in, fan_out), minval = low, maxval = high, dtype = tf.float32)

class AdditiveGaussianNoiseAutoencoder(object):
    def __init__(self, n_input, n_hidden, transfer_function = tf.nn.sigmoid, optimizer = tf.train.AdamOptimizer(),
                 scale = 0.1):
        self.n_input = n_input
        self.n_hidden = n_hidden
        self.transfer = transfer_function
        self.scale = tf.placeholder(tf.float32)
        self.training_scale = scale
        network_weights = self._initialize_weights()
        self.weights = network_weights
        self.sparsity_level= 0.1#np.repeat([0.05], self.n_hidden).astype(np.float32)
        self.sparse_reg = 10

        # model
        self.x = tf.placeholder(tf.float32, [None, self.n_input])
        self.hidden = self.transfer(tf.add(tf.matmul(self.x + scale * tf.random_normal((n_input,)),
                self.weights['w1']),
                self.weights['b1']))
        self.reconstruction = tf.add(tf.matmul(self.hidden, self.weights['w2']), self.weights['b2'])

        # cost
        self.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0)) + self.sparse_reg \
                        * self.kl_divergence(self.sparsity_level, self.hidden)

        self.optimizer = optimizer.minimize(self.cost)

        init = tf.global_variables_initializer()
        self.sess = tf.Session()
        self.sess.run(init)

    def _initialize_weights(self):
        all_weights = dict()
        all_weights['w1'] = tf.Variable(xavier_init(self.n_input, self.n_hidden))
        all_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden], dtype = tf.float32))
        all_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden, self.n_input], dtype = tf.float32))
        all_weights['b2'] = tf.Variable(tf.zeros([self.n_input], dtype = tf.float32))
        return all_weights

    def partial_fit(self, X):
        cost, opt = self.sess.run((self.cost, self.optimizer), feed_dict = {self.x: X,
                                                                            self.scale: self.training_scale
                                                                            })
        return cost

    def kl_divergence(self, p, p_hat):
        return tf.reduce_mean(p * tf.log(p) - p * tf.log(p_hat) + (1 - p) * tf.log(1 - p) - (1 - p) * tf.log(1 - p_hat))

    def calc_total_cost(self, X):
        return self.sess.run(self.cost, feed_dict = {self.x: X,
                                                     self.scale: self.training_scale
                                                     })

    def transform(self, X):
        return self.sess.run(self.hidden, feed_dict = {self.x: X,
                                                       self.scale: self.training_scale
                                                       })

    def generate(self, hidden = None):
        if hidden is None:
            hidden = np.random.normal(size = self.weights["b1"])
        return self.sess.run(self.reconstruction, feed_dict = {self.hidden: hidden})

    def reconstruct(self, X):
        return self.sess.run(self.reconstruction, feed_dict = {self.x: X,
                                                               self.scale: self.training_scale
                                                               })

    def getWeights(self):
        return self.sess.run(self.weights['w1'])

    def getBiases(self):
        return self.sess.run(self.weights['b1'])

mnist = input_data.read_data_sets('MNIST_data', one_hot = True)

def get_random_block_from_data(data, batch_size):
    start_index = np.random.randint(0, len(data) - batch_size)
    return data[start_index:(start_index + batch_size)]

X_train = mnist.train.images
X_test = mnist.test.images

n_samples = int(mnist.train.num_examples)
training_epochs = 50
batch_size = 128
display_step = 1

autoencoder = AdditiveGaussianNoiseAutoencoder(n_input = 784,
                                               n_hidden = 200,
                                               transfer_function = tf.nn.sigmoid,
                                               optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01),
                                               scale = 0.01)

for epoch in range(training_epochs):
    avg_cost = 0.
    total_batch = int(n_samples / batch_size)
    # Loop over all batches
    for i in range(total_batch):
        batch_xs = get_random_block_from_data(X_train, batch_size)

        # Fit training using batch data
        cost = autoencoder.partial_fit(batch_xs)
        # Compute average loss
        avg_cost += cost / n_samples * batch_size

    # Display logs per epoch step
    if epoch % display_step == 0:
        print("Epoch:", '%04d' % (epoch + 1), "cost=", avg_cost)

print("Total cost: " + str(autoencoder.calc_total_cost(X_test)))

imageToUse = random.choice(mnist.test.images)

plt.imshow(np.reshape(imageToUse,[28,28]), interpolation="nearest", cmap="gray", clim=(0, 1.0))
plt.show()

# input weights
wts = autoencoder.getWeights()
dim = math.ceil(math.sqrt(autoencoder.n_hidden))
plt.figure(1, figsize=(dim, dim))
for i in range(0,autoencoder.n_hidden):
    im = wts.flatten()[i::autoencoder.n_hidden].reshape((28,28))
    plt.subplot(dim, dim, i+1)
    #plt.title('Feature Weights ' + str(i))
    plt.imshow(im, cmap="gray", clim=(-1.0, 1.0))
    plt.colorbar()
plt.show()

predicted_imgs = autoencoder.reconstruct(X_test[:100])

# plot the reconstructed images
plt.figure(1, figsize=(10, 10))
plt.title('Autoencoded Images')
for i in range(0,100):
    im = predicted_imgs[i].reshape((28,28))
    plt.subplot(10, 10, i+1)
    plt.imshow(im, cmap="gray", clim=(0.0, 1.0))
plt.show()

Body:
I don't know that this will work for you, but I have seen it promote some sparsity in my own networks. I would recommend modifying your loss to use a combination of softmax cross entropy (or KL divergence if you wish) and l2 regularization loss on the weights. I calculate the l2 loss with:

l2 = sum(tf.nn.l2_loss(var) for var in tf.trainable_variables() if not 'biases' in var.name)

This makes me regularize only on the weights, not biases, assuming that you have "biases" in the name of your bias tensors (lots of the tf.contrib.rnn library names bias tensors so that this works). The overall cost function I use is then:

cost = tf.nn.softmax_or_kl_divergence_or_whatever(labels=labels, logits=logits)
cost = tf.reduce_mean(cost)
cost = cost + beta * l2

where beta is a hyperparameter of the network that I then vary when exploring my hyperparameter space.

Another option, very similar to this, is to use l1 regularization instead. This is supposed to promote sparsity more than l2 regularization. In my own examples I was not explicitly trying to promote sparsity, but saw it as a consequence of l2 regularization, but maybe l1 will give you more luck. You can implement l1 regularization with something like:

l1 = sum(tf.reduce_sum(tf.abs(var)) for var in tf.trainable_variables() if not 'biases' in var.name)

followed by the cost definition above, substituting l1 for l2.


问:
Disable Variable Product Price Range on the WooCommerce Single Product Pages Only
I'm looking to hide variable products price range only on the single product pages for the product that is currently being viewed. I do not want the price range to be disabled for all the products listed in the "Related Products" below and any products listed in the widgets in the footer as well.

Everyone of the snippets I've found so far hides the price range for every product listed on the single products page. It also hides the price completely from view from the variable products that have the exact same price for all of them since they do not display below the drop down when selected.

Here is an example of a snippet I've found:

```<code>/*
Disable Variable Product Price Range completely:
*/

add_filter( 'woocommerce_variable_sale_price_html', 'my_remove_variation_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'my_remove_variation_price', 10, 2 );

function my_remove_variation_price( $price ) {
  $price = '';
  return $price;
}
</code>```

Example of price issue below:

答:
Let's look on the Visual Hook Guide. The price range is a part of the single product summary. The woocommerce_single_product_summary hook consists of:

```<code> * @hooked woocommerce_template_single_title - 5
 * @hooked woocommerce_template_single_rating - 10
 * @hooked woocommerce_template_single_price - 10
 * @hooked woocommerce_template_single_excerpt - 20
 * @hooked woocommerce_template_single_add_to_cart - 30
 * @hooked woocommerce_template_single_meta - 40
 * @hooked woocommerce_template_single_sharing - 50
</code>```

And the woocommerce_template_single_price function adds the single-product/price.php template-part.

So we have two ways:

1. Remove this template part for variable products only

```<code>add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
  global $product;
  if ( $product->is_type( 'variable' ) ) {
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
  }
}
</code>```

2. Or edit the template part itself

Copy wp-content/plugins/woocommerce/templates/single-product/price.php to wp-content/themes/YOUR_THEME/woocommerce/single-product/price.php and replace this code fragment

```<code>  <p class="price"><?php echo $product->get_price_html(); ?></p>
</code>```

with this one

```<code><?php if ( ! $product->is_type( 'variable' ) ) : ?>
  <p class="price"><?php echo $product->get_price_html(); ?></p>
<?php endif; ?>
</code>```

Body:
I'm looking to hide variable products price range only on the single product pages for the product that is currently being viewed. I do not want the price range to be disabled for all the products listed in the "Related Products" below and any products listed in the widgets in the footer as well.

Everyone of the snippets I've found so far hides the price range for every product listed on the single products page. It also hides the price completely from view from the variable products that have the exact same price for all of them since they do not display below the drop down when selected.

Here is an example of a snippet I've found:

/*
Disable Variable Product Price Range completely:
*/

add_filter( 'woocommerce_variable_sale_price_html', 'my_remove_variation_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'my_remove_variation_price', 10, 2 );

function my_remove_variation_price( $price ) {
  $price = '';
  return $price;
}

Example of price issue below:

Body:
Let's look on the Visual Hook Guide. The price range is a part of the single product summary. The woocommerce_single_product_summary hook consists of:

 * @hooked woocommerce_template_single_title - 5
 * @hooked woocommerce_template_single_rating - 10
 * @hooked woocommerce_template_single_price - 10
 * @hooked woocommerce_template_single_excerpt - 20
 * @hooked woocommerce_template_single_add_to_cart - 30
 * @hooked woocommerce_template_single_meta - 40
 * @hooked woocommerce_template_single_sharing - 50

And the woocommerce_template_single_price function adds the single-product/price.php template-part.

So we have two ways:

1. Remove this template part for variable products only

add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
  global $product;
  if ( $product->is_type( 'variable' ) ) {
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
  }
}

2. Or edit the template part itself

Copy wp-content/plugins/woocommerce/templates/single-product/price.php to wp-content/themes/YOUR_THEME/woocommerce/single-product/price.php and replace this code fragment

  <p class="price"><?php echo $product->get_price_html(); ?></p>

with this one

<?php if ( ! $product->is_type( 'variable' ) ) : ?>
  <p class="price"><?php echo $product->get_price_html(); ?></p>
<?php endif; ?>


问:
How does append() work behind the scenes that's causing this?
I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

```<code>func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v\n", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v\n", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors
</code>```

Try it here

So, what the heck is really going on here?

答:
If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array.

Breaking it down, s here is foo[:0], which has a capacity of at least 3, since the length of foo is 3. s has 0 elements, and append wants to add two elements, [b c], so there is room, and append will re-use the underlying array of foo[:0] which is the same as the underlying array of foo.

So it places the items [b c] at the beginning of the array, and returns a new slice of that array with a length of 2.

But you're still looking at foo, which is a slice of that same array, but still has a length of 3; the third item is the c which hasn't been touched, so foo is now [b c c].

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v\n", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v\n", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors

Try it here

So, what the heck is really going on here?


问:
Trying to store Bukkit ItemStack field to a file but ItemStack is not Serrializable
ItemStack is not serializable and I'm trying to save an object called Objective with an ItemStack field to a file but since ItemStack is not serializable this does not work. I tried extending ItemStack and implementing Serializable and changing the field to my new serializable sub class but this also did not work. Here are the relevant parts of my original code:

```<code>import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;

import org.bukkit.inventory.ItemStack;

public class Objective implements Serializable {

private static final long serialVersionUID = -2018456670240873538L;

private static ArrayList<Requirement> requirements = new ArrayList<>();

private String name;
private Requirement requirement;
private ItemStack reward;

private int tillComplete;

private boolean complete;

public Objective(String name, int requirementIndex, int tillComplete, ItemStack reward) {

    if(requirements.isEmpty()) {
        requirements.add(Requirement.kill_Skeletons);
        requirements.add(Requirement.kill_Spiders);
        requirements.add(Requirement.kill_Zombies);
    }

    this.name = name;
    this.requirement = requirements.get(requirementIndex);
    this.tillComplete = tillComplete;
    this.reward = reward;
    complete = false;
}

public String getName() {
    return name;
}

public Object getRequirement() {
    return requirement;
}

public static ArrayList<Requirement> getRequirements() {
    return requirements;
}

public static void setRequirements(ArrayList<Requirement> requirements) {
    Objective.requirements = requirements;
}

public int getTillComplete() {
    return tillComplete;
}

public void setTillComplete(int tillComplete) {
    this.tillComplete = tillComplete;
}

public void setName(String name) {
    this.name = name;
}

public void setRequirement(Requirement requirement) {
    this.requirement = requirement;
}

public void setReward(ItemStackSerializable reward) {
    this.reward = reward;
}

public void setComplete(boolean complete) {
    this.complete = complete;
}

public ItemStack getReward() {
    return reward;
}

public boolean isComplete() {
    return complete;
}
</code>```

}

Elsewhere in my code this line of code:

```<code>ItemStack reward = new ItemStack(Material.DIAMOND_SWORD);
                        Objective objective = new Objective(args[1] ,Integer.parseInt(args[2]), Integer.parseInt(args[3]), reward);
</code>```

is giving me this error:

```<code>java.io.NotSerializableException: org.bukkit.inventory.ItemStack
</code>```

How can I serialize this object? I need to store it but Java wont let me. Thanks for your help. If you need anymore code snippets or other information please let me know.

答:
This is most likely an XY problem. ItemStack is not serializable, as it represents an actual stack of items at runtime. This would not make sense to store in a file. It might be worth looking at the ConfigurationSerializable interface, which is implemented by ItemStack, but I don't think you need that here.

In your example, the ItemStack that you are trying to serialize doesn't have any metadata. It is a single diamond sword. If all your rewards are just a single item, all you need to save is the Material and you can create a new ItemStack from that Material every time you want to give a player a reward. Since Material is an enum, it is serializable by default.

You could also serialize an int for stack size if some of your rewards require a stack of multiple items. If you need any metadata, serialize the data needed to construct that at runtime. For example, to give an item lore, you would store a List<String> (with a serializable implementation of List).

Body:
ItemStack is not serializable and I'm trying to save an object called Objective with an ItemStack field to a file but since ItemStack is not serializable this does not work. I tried extending ItemStack and implementing Serializable and changing the field to my new serializable sub class but this also did not work. Here are the relevant parts of my original code:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;

import org.bukkit.inventory.ItemStack;

public class Objective implements Serializable {

private static final long serialVersionUID = -2018456670240873538L;

private static ArrayList<Requirement> requirements = new ArrayList<>();

private String name;
private Requirement requirement;
private ItemStack reward;

private int tillComplete;

private boolean complete;

public Objective(String name, int requirementIndex, int tillComplete, ItemStack reward) {

    if(requirements.isEmpty()) {
        requirements.add(Requirement.kill_Skeletons);
        requirements.add(Requirement.kill_Spiders);
        requirements.add(Requirement.kill_Zombies);
    }

    this.name = name;
    this.requirement = requirements.get(requirementIndex);
    this.tillComplete = tillComplete;
    this.reward = reward;
    complete = false;
}

public String getName() {
    return name;
}

public Object getRequirement() {
    return requirement;
}

public static ArrayList<Requirement> getRequirements() {
    return requirements;
}

public static void setRequirements(ArrayList<Requirement> requirements) {
    Objective.requirements = requirements;
}

public int getTillComplete() {
    return tillComplete;
}

public void setTillComplete(int tillComplete) {
    this.tillComplete = tillComplete;
}

public void setName(String name) {
    this.name = name;
}

public void setRequirement(Requirement requirement) {
    this.requirement = requirement;
}

public void setReward(ItemStackSerializable reward) {
    this.reward = reward;
}

public void setComplete(boolean complete) {
    this.complete = complete;
}

public ItemStack getReward() {
    return reward;
}

public boolean isComplete() {
    return complete;
}

}

Elsewhere in my code this line of code:

ItemStack reward = new ItemStack(Material.DIAMOND_SWORD);
                        Objective objective = new Objective(args[1] ,Integer.parseInt(args[2]), Integer.parseInt(args[3]), reward);

is giving me this error:

java.io.NotSerializableException: org.bukkit.inventory.ItemStack

How can I serialize this object? I need to store it but Java wont let me. Thanks for your help. If you need anymore code snippets or other information please let me know.


问:
How do I move this search bar to the top right of the screen?
enter image description here

How do I move the search bar to the top right corner (html/css) of the screen. Please give me some examples.

答:
Here's a working example, you can read more about forms here :
https://www.w3schools.com/html/html_forms.asp

    <object align= right>
      <form method="POST" action="#">
        <input type="text" name="search" placeholder="type ..">
        <input type="submit" value="search here">
      </form>
    </object>

```

Body:
Here's a working example, you can read more about forms here :
https://www.w3schools.com/html/html_forms.asp

<div class="search">
  <div id="search1">
    <object align= right>
      <form method="POST" action="#">
        <input type="text" name="search" placeholder="type ..">
        <input type="submit" value="search here">
      </form>
    </object>
  </div>
</div>


问:
Use adb over tcpip in Android Studio?
Is it possible to show the adb logcat for a tcpip device in Android Studio? I am writing a application that utilizes the USB port and I cannot use it for adb usb.

Currently, I am using the following instruction to view the logcat in Command Prompt, but it would be nice if this was integrated into AS:
http://developer.android.com/tools/help/adb.html#wireless

答:
adb devices

adb tcpip 5555

adb connect 192.168.4.23

Unplug you device  and run the adb connect 192.128.4.23  command again

For further details Check this article

Title: Use adb over tcpip in Android Studio?


问:
C# Weird Encoding.Default.GetString output converting camera photo to string
I have an image called in byte array form called imageAsBytes that I am trying to convert into a string stored in machine.photos using Encoding.Default.GetString(image). The conversion is going wrong and I am getting some weird output.

System.Text.Encoding.Default.GetString(image); is returning this

Why is it not converting correctly? Here is the code I'm using to create the picture

```<code>var file = await CrossMedia.Current.TakePhotoAsync(
            new StoreCameraMediaOptions
            {
                SaveToAlbum = true,
            });

 using (var memoryStream = new MemoryStream())
            {
                file.GetStream().CopyTo(memoryStream);
                //file.Dispose();
                imageAsBytes = memoryStream.ToArray();
                file.Dispose();
            }
</code>```

答:
Based on your comment, I think you want a Base 64 string encoding. You can get that with this:

```<code>string encoding = Convert.ToBase64String(image);
</code>```

This format is useful to convert binary data in a readable and printable string. It will however occupy more as you are using a base 64 system instead of a base 256 one (bytes!). This will increase your data size in approximately 33%.

According to the MSDN:

The base-64 digits in ascending order from zero are the uppercase
  characters "A" to "Z", the lowercase characters "a" to "z", the
  numerals "0" to "9", and the symbols "+" and "/". The valueless
  character, "=", is used for trailing padding.

For example, iVBORw0KGgoA (the first 12 characters of your sample) represent 9 bytes. If you use any of the Encoding methods, those bytes will be converted to the corresponding encoding, which can be one character per byte (ASCII or UTF8), per 2 bytes (Unicode) or even per 4 bytes (UTF32). This means that 2 or 4 of your bytes can end up as one single Chinese symbol, which apparently is not what you want.

Body:
I have an image called in byte array form called imageAsBytes that I am trying to convert into a string stored in machine.photos using Encoding.Default.GetString(image). The conversion is going wrong and I am getting some weird output.

System.Text.Encoding.Default.GetString(image); is returning this

Why is it not converting correctly? Here is the code I'm using to create the picture

var file = await CrossMedia.Current.TakePhotoAsync(
            new StoreCameraMediaOptions
            {
                SaveToAlbum = true,
            });

 using (var memoryStream = new MemoryStream())
            {
                file.GetStream().CopyTo(memoryStream);
                //file.Dispose();
                imageAsBytes = memoryStream.ToArray();
                file.Dispose();
            }

Body:
Based on your comment, I think you want a Base 64 string encoding. You can get that with this:

string encoding = Convert.ToBase64String(image);

This format is useful to convert binary data in a readable and printable string. It will however occupy more as you are using a base 64 system instead of a base 256 one (bytes!). This will increase your data size in approximately 33%.

According to the MSDN:

The base-64 digits in ascending order from zero are the uppercase
  characters "A" to "Z", the lowercase characters "a" to "z", the
  numerals "0" to "9", and the symbols "+" and "/". The valueless
  character, "=", is used for trailing padding.

For example, iVBORw0KGgoA (the first 12 characters of your sample) represent 9 bytes. If you use any of the Encoding methods, those bytes will be converted to the corresponding encoding, which can be one character per byte (ASCII or UTF8), per 2 bytes (Unicode) or even per 4 bytes (UTF32). This means that 2 or 4 of your bytes can end up as one single Chinese symbol, which apparently is not what you want.


问:
How to use secrets.yml for API_KEYS in Rails 4.1?
In one of my recent projects I started out by .gitignoring the files containing secrets and environment variables. So the entire project is committed to the repo except the files that contain third party secrets such as that of Stripe, Twitter API or Facebook Graph or internal api_keys, ala the ./config/initializers/secret_token.rb file.

Now I am at a point where the project is about to go live (excited!) and I need to port all the environment variables on to the production server using Capistrano i.e. cap production deploy.

[Edit 4: Yr, 2018]
In case of initializers/secret_token.rb it is clear that Rails 4.1 has a new way of handling secrets.yml file that pulls in the :secret_key_base value to the production server. Here, I recommend using the capistrano-secrets-yml gem which works right out of the box and is dead simple to use.

What is left is the way to carry other secrets like API_KEYS, APP_IDs etc. to the production server without checking any of those into the repo. How to do this, what is the most recommended/securest way or the best practices?

NOTE: I'll be editing the question as it progresses/I get more clarity.

EDIT1: Server is a Ubuntu/Linux VPS on DigitalOcean [Answer to Denise, below].

EDIT2: Can the env_variables/secrets be carried over to the server via secrets.yml? Secret_token for sessions is not the only secret after all! [Answered on Edit3]

EDIT3: Yes! It's possible to send in the API_keys via secrets.yml according to this blog. Will share my findings in sometime. :-)

答:
I know this question is specific to Rails 4.1, but those who upgrade to Rails 5.1 it now includes built in secret generation. Which seems a much better way to handle sensitive data in your rails app.

See: http://edgeguides.rubyonrails.org/5_1_release_notes.html#encrypted-secrets