I am trying to run Task scheduler but I get below error:
"C:\Program Files\Java\jdk1.8.0_121\bin\java" com.mthree.util.App
Error: Could not find or load main class com.mthree.util.App
Process finished with exit code 1
FixedRateScheduler code
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
public class FixedRateScheduler {
#Scheduled(fixedRate = 1000)
public void run() throws InterruptedException{
System.out.println("livePrice: "+ new Date());
Thread.sleep(3000);
}
}
LivePrice-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<task:annotation-driven />
<mvc:annotation-driven />
<context:annotation-config />
<bean id="fixedRateScheduler" class="com.mthree.util.FixedRateScheduler" ></bean>
<context:component-scan base-package="com.mthree.*" />
Main Class - App.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String [] args){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("LivePrice-servlet.xml");
}
}
directory structure
Related
I am trying to migrate a project from a traditional (working) Java servlet application to Spring MVC in the NetBeans IDE, but my program absolutely refuses to ping the Controller. On the client side, I see the following 404 errors:
index.do?displayType=table:1 Failed to load resource: the server responded with a status of 404 (Not Found)
index.do?displayType=table:1 Failed to load resource: the server responded with a status of 404 (Not Found)
I invoke the controller methods like so:
$.get("index.do","displayType=table", function( data ) {
jstring = JSON.parse(data.substr(12).slice(0, -1));
});
$.get("index.do","displayType=pivot",function(unparsedJSON) {});
$.post("index.do","jsonString=" + JSON.stringify(hot.getData()));
Below are my controller and xml configuration files:
MappingControl.java
package controllers;
import infoLoader.JsonWriter;
import infoLoader.getJSON;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.springframework.http.HttpMethod.GET;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
#RequestMapping("/")
public class MappingControl {
#RequestMapping(value="/index.do", method=RequestMethod.GET)
public String populatePivotAndSheet(#RequestParam("displayType") String type) {
String returnedJSON = "";
try {
returnedJSON = getJSON.getJSON(type);
} catch (Exception ex) {
System.out.println("Unable to retrieve JSON");
}
return returnedJSON;
}
#RequestMapping(value="/index.do", method=RequestMethod.POST)
public void deliverSheet(#RequestParam("jsonString") String writableJSON) {
String returnedJSON = "";
JsonWriter.writeJSON(writableJSON);
}
}
applicationContext.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
</beans>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" xmlns:mvc="http://www.springframework.org/schema/mvc">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<mvc:resources mapping="/resources/**" location="/resources" />
<context:component-scan base-package="controllers" />
</beans>
I've been building this based on the default Spring-MVC template provided by NetBeans, so if any of you believe the template is poorly formatted and should be changed in some way, I would appreciate any input you might have.
Thanks so much for your time, guys, and let me know if anything is unclear.
You need add #ResponseBody to your method,due to in your case,you want to return the json data,if you missing #ResponseBody it will return to the view page,however you do not specify any view page in your code,thus will cause 404 error
#ResponseBody
#RequestMapping(value="/index.do", method=RequestMethod.GET)
public String populatePivotAndSheet(#RequestParam("displayType") String type) {
String returnedJSON = "";
try {
returnedJSON = getJSON.getJSON(type);
} catch (Exception ex) {
System.out.println("Unable to retrieve JSON");
}
return returnedJSON;
}
#ResponseBody
#RequestMapping(value="/index.do", method=RequestMethod.POST)
public void deliverSheet(#RequestParam("jsonString") String writableJSON) {
String returnedJSON = "";
JsonWriter.writeJSON(writableJSON);
}
This question has already an answer here but i've checked and the component:scan is set roperly for me so i don't really get what is the point here. The controller:
#Controller
#RequestMapping("view")
public class PortletController {
#RenderMapping
public String view(RenderRequest request, RenderResponse response, ModelMap model) {
ResourceURL baseResourceUrl = response.createResourceURL();
model.addAttribute("ajaxURL", baseResourceUrl.toString() + "&");
model.addAttribute("standalone", false);
model.addAttribute("portletId", getPortletId(request));
model.addAttribute("portletAppContextPath", request.getContextPath() + "/");
return "index";
}
The component scan element in the applicationcontext is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- DispatcherPortlet Context: defines this portlet's request-processing infrastructure -->
<!-- Autodetect annotated controllers -->
<context:component-scan base-package="com.package.of.controller"/>
</beans>
Any idea of why it could be not working?
I am trying to get an object from my database using Spring REST API. The problem is that I am not receiving the content correctly.
My log output:
/hello
Hibernate: select this_.id as id0_0_, this_.countryCode as countryC2_0_0_ from Country this_ where this_.countryCode=?
Found: at
And the controller I use:
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mahlzeit.datamodel.HibernateTest;
import com.mahlzeit.datamodel.address.Country;
#RestController
public class HelloWorldController {
#RequestMapping(value = "/hello")//, method = RequestMethod.GET)
public Country hello(ModelMap model) {
System.out.println("/hello");
HibernateTest hbt = new HibernateTest();
Session session = hbt.sessionFactory.openSession();
Criteria cr = session.createCriteria(Country.class);
cr.add(Restrictions.eq("countryCode", "at"));
List<Country> queryAustria = cr.list();
if (queryAustria.isEmpty() == true) {
System.err.println("at not found");
return null;
}
Country austria = null;
for (Iterator<Country> iterator = queryAustria.iterator(); iterator
.hasNext();) {
Country country = (Country) iterator.next();
if (country.getCountryCode().equals("at")) {
austria = country;
break;
}
}
System.out.println("Found: "+ austria.getCountryCode());
return austria;
}
}
So, I am getting back my desired object from Hibernate but what I am actually getting back is
HTTP Status 404
This is Country.java:
#Entity
public class Country implements Serializable {
private static final long serialVersionUID = -2060021861139912774L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(length=2,unique=true)
private String countryCode;
// Setter & Getter ..
}
Config file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.mahlzeit.server.mobile" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
If you are using the InternalResourceViewResolver then Spring will try to resolve the View based on view name that you are passing. So it will look for the file /WEB-INF/austria.jsp assuming the controller is returning the value as "austria". So that is the reason you are getting 404 error.
So to fix the issue, add <mvc:annotation-driven /> in Spring configuration file.
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.mahlzeit.server.mobile" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Also you need to have the JSON related Jars in your classpath -- WEB-INF/lib folder:
jackson-core-asl-1.9.13.jar & jackson-mapper-asl-1.9.13.jar
I have this code...
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
</beans>
The code exits, but the JVM never stops.
Anyone any ideas why its doesn't stop?
I've also tried a new Main method of the following, but it keeps running.
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
((ConfigurableApplicationContext)context).registerShutdownHook();
((ConfigurableApplicationContext)context).stop();
System.out.println("exiting NOW...");
}
If I pause the JVM, it shows 4 threads.
1 with TimerThread.run()
3 with ScheduledThreadPoolExecutor.take()
The ConfigurableApplicationContext interface (that ClassPathXmlApplicationContext implements) has a close method you need to call in order for the JVM to shut down properly.
More information can be found here.
I am using Spring and integrating with hibernate 4 as persistence Provider, here what i ma trying is to do crud operation
on student Entity,
All my select operations are working fine, but add and update operation are not working,
My persistence.xml,
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="forSpring" transaction-type="JTA">
<class>com.entity.Student</class>
</persistence-unit>
</persistence>
My Spring-bean.xml,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.*" />
<jee:jndi-lookup id="datasourceId" jndi-name="jdbc/myPrac" resource-ref="true" />
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
<!-- Spring integration with JPA -->
<bean id="vendorAdaptor-inj" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="DERBY" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="entityMgrFactory-inj" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasourceId" />
<property name="persistenceUnitName" value="forSpring" />
<property name="jpaVendorAdapter" ref="vendorAdaptor-inj" />
</bean>
</beans>
This is my StudentDAO,
package com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.entity.Student;
#Repository("studentSpringDao-inj")
#Transactional(value="txManager",readOnly=true)
public class StudentSpringDAO {
#PersistenceContext(unitName="forSpring")
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public List<Student> getStudentList() throws Exception{
System.out.println(" \n\n\n LOADING... \n\n\n ");
String query = "select s from Student s order by s.studentId desc";
TypedQuery<Student> studentQuery = em.createQuery(query,Student.class);
return studentQuery.getResultList();
}
public Integer latestStudent() throws Exception{
String query = "select max(s.studentId) from Student s";
TypedQuery<Integer> studentQuery = em.createQuery(query,Integer.class);
return studentQuery.getResultList().get(0);
}
#Transactional(value="txManager",readOnly=false,propagation=Propagation.REQUIRES_NEW)
public Student saveStudent(Student student) throws Exception{
return em.merge(student);
}
}
Just for the information, i am using jndi look-up name "jdbc/myPrac" to look-up the datasource,
Can you help me out with this, do i am missing any configuration in spring-bean.xml
#Transactional(value="txManager",readOnly=true)
What do you think readOnly=true means and have you tried it with readOnly=false?
replace the class org.springframework.transaction.jta.JtaTransactionManager
with org.springframework.orm.jpa.JpaTransactionManager and add tx:annotation-driven