I am new to restful web services ..when a post request is made to "/adduser" ,like with request data as {"iduser":5,"name":"bob"} , the rest client gives 500 error and eclipse console gives MySqlSyntaxErrorException: Unknown column 'bob' in 'field list'
DbConnection.java
package com.dbproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getConnection(){
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3307/thedb","root","root");
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
DbServices.java
package com.dbproject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DbServices {
Connection con=DbConnection.getConnection();
public String addUser(int iduser,String name) throws SQLException{
PreparedStatement ps=con.prepareStatement("insert into users values("+iduser+","+name+")");
int res=ps.executeUpdate();
con.close();
if(res>0){
System.out.println("Insert Query Successfull");
return "Done";
}
else{
System.out.println("Insert Query Failed");
return "Error";
}
}
}
Resources.java
package com.dbproject;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
#Path("/user")
public class Resources {
DbServices dbServices=new DbServices();
#POST
#Path("/adduser")
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String addUser(String s) throws SQLException{
Gson gson=new Gson();
UserModel userModel=gson.fromJson(s,UserModel.class);
String str=dbServices.addUser(userModel.getIduser(),userModel.getName());
return str;
}
}
UserModel.java
package com.dbproject;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class UserModel {
private int iduser;
private String name;
public int getIduser() {
return iduser;
}
public String getName() {
return name;
}
public void setIduser(int iduser) {
this.iduser = iduser;
}
public void setName(String name) {
this.name = name;
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>dbproject</display-name>
<servlet>
<servlet-name>Jersey Web Services</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.dbproject</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Services</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
MySqlSyntaxErrorException
Means you have a syntax error on your SQL.
"insert into users values("+iduser+","+name+")"
String values require quotes. The name value needs to be wrapped in quotes
+",'"+name+"')"
Numbers don't need them.
Aside from this, you are not even use PreparedStatement correctly. You should be using ? syntax, and using the PreparedStatment API to replace them. e.g.
PreparedStatement ps=con.prepareStatement("insert into users values(?,?)");
ps.setInt(1, isuser);
ps.setString(2, name);
int result = ps.executeUpdate();
See Also:
Using Prepared Statements
Related
I am using Spring Boot with EhCache and Jersey, I am having issue to make BootstrapCacheLoader work, debug shows the load function executes and make call to the function (for which I want result to be cached). but once app is started the first request still calls the function and takes it's time to load data and then afterwords it is quick i.e. first call takes around 2 minutes and then following requests take less than a second.
here is my implementation:
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<cache name="idsMap"
maxEntriesLocalHeap="1000"
maxEntriesLocalDisk="10000"
eternal="true"
diskSpoolBufferSizeMB="20"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
EhCache Config
package com.spinners.rest.config;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheFactoryBean;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
/**
* #author sajid
*
*/
#Configuration
#EnableCaching
public class EhCacheConfig {
#Autowired
CacheManager cacheManager;
#Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
return ehCacheManagerFactoryBean;
}
#Bean
public CacheManager cacheManager() {
EhCacheCacheManager cacheManager = new EhCacheCacheManager();
cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
return cacheManager;
}
#Bean
public MyBootstrapCacheLoaderFactory myBootstrapCacheLoaderFactory() {
return new MyBootstrapCacheLoaderFactory();
}
#Bean
public EhCacheFactoryBean ehCacheFactory() {
EhCacheFactoryBean ehCacheFactory = new EhCacheFactoryBean();
ehCacheFactory.setCacheManager(ehCacheManagerFactoryBean().getObject());
ehCacheFactory.setBootstrapCacheLoader(myBootstrapCacheLoaderFactory());
return ehCacheFactory;
}
}
Here is my implementation of BootstrapCacheLoader
package com.spinners.rest.config;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.spinners.rest.repositories.IdsMapRepository;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
import net.sf.ehcache.bootstrap.BootstrapCacheLoaderFactory;
public class MyBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactory implements BootstrapCacheLoader {
#Autowired
private IdsMapRepository idsMapRepo;
public MyBootstrapCacheLoaderFactory() {
super();
}
#Override
public BootstrapCacheLoader createBootstrapCacheLoader(Properties properties) {
return new MyBootstrapCacheLoaderFactory();
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public boolean isAsynchronous() {
return false;
}
public void load(Ehcache ehCache) throws CacheException {
try {
// function for which I want to load data in cache
Map<String, String> idsMap = idsMapRepo.getIdsMap();
} catch (Exception e) {
e.printStackTrace();
}
}
}
any suggestions? thanks in advance friends.
Best Regards
Sajid
I am new to JSF and working on session-timeout and based on it redirecting to a logout page. But it is not working properly and showing unusual behavior like, some times it's getting redirected and some times it's not...
Code for web.xml:
<context-param>
<param-name>web.TIME_OUT_PAGE</param-name>
<param-value>/sessionTimeOut.html</param-value>
</context-param>
<listener>
<display-name>SessionTimeoutNotifier</display-name>
<listener-class>test.web.SessionTimeoutNotifier</listener-class>
</listener>
<listener>
<display-name>ViewExpirationListener</display-name>
<listener-class>test.web.ViewExpirationListener</listener-class>
</listener>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
and code for SessionTimeoutNotifier.java:
package test.web;
import java.io.Serializable;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import org.apache.commons.lang.exception.ExceptionUtils;
import test.User;
public class SessionTimeoutNotifier implements HttpSessionBindingListener,Serializable
{
private static final long serialVersionUID = 8420390506024648336L;
public SessionTimeoutNotifier(){
}
public void valueBound(HttpSessionBindingEvent event)
{
User user = (User) event.getSession().getAttribute(User.USER);
System.out.println("Session Max Inactive Interval Value:"+ event.getSession().getMaxInactiveInterval());
if (user != null) {
System.out.println("Session ID:"+ event.getSession().getId() + " created for user ID: " + user.getId());
} else {
System.out.println("Session ID:"+ event.getSession().getId() + " created for user ID: UNKNOWN");
}
}
public void valueUnbound(HttpSessionBindingEvent event)
{
User user = (User) event.getSession().getAttribute(User.USER);
System.out.println("Session expired : [" + (user == null ? "Unknown" : user.getId()) + "]");
}
}
and ViewExpirationListener.java Class:
package test.web;
import java.io.IOException;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
public class ViewExpirationListener implements PhaseListener {
private static final String TIME_OUT_PAGE_PARAM = "web.TIME_OUT_PAGE";
#Override
public PhaseId getPhaseId() {
return PhaseId.APPLY_REQUEST_VALUES;
}
#Override
public void afterPhase(PhaseEvent event) {
// Do nothing.
}
#Override
public void beforePhase(PhaseEvent event) {
FacesContext facesContext = event.getFacesContext();
List<FacesMessage> iter = facesContext
.getMessageList(ViewExpiredException.class.getName());
List<FacesMessage> msgs = facesContext.getMessageList();
int count = 1;
if (iter.size() > 0) {
handleTimeOut(facesContext);
}
}
private void handleTimeOut(FacesContext facesContext) {
ExternalContext extContext = facesContext.getExternalContext();
String timeOutPage = extContext.getRequestContextPath()
+ extContext.getInitParameter(TIME_OUT_PAGE_PARAM);
try {
extContext.redirect(timeOutPage);
} catch (IOException e) {
throw new FacesException(e);
}
facesContext.responseComplete();
}
}
and still it is not redirecting every-time after inactivity of 30 min. Some times timeout works even at 31st minute and some times session is still active even after 5 hours....
I am not able to understand where I am wrong and what can be done to resolve it..
Thanks in advance for help...
i am new in ejb3 application
my project is:
ServletController.java
package controller;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.HelloUser;
public class ServletController extends HttpServlet {
#Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
try {
InitialContext Context = new InitialContext();
Context context = new InitialContext();
HelloUser helloUser = (HelloUser) context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local");
System.out.println(".................................");
helloUser.sayHello("reza");
arg1.sendRedirect("reza");
} catch (Exception e) {
e.printStackTrace();
}
}
}
HelloUser.java:
package com;
import javax.ejb.Local;
#Local
public interface HelloUser {
public void sayHello(String name);
}
HelloUserBean.java
package com;
import javax.ejb.Stateless;
#Stateless
public class HelloUserBean implements HelloUser {
public HelloUserBean() {
}
public void sayHello(String name) {
System.out.println("Hello " + name + " welcome to EJB 3!");
}
}
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Baharan-Framework</display-name>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>controller.ServletController</servlet-class>
</servlet>
</web-app>
the following error is raised when ServletController is called by webbrowser(URL is:http://localhost:7001/weblogic/rest/jkfg):
javax.naming.NameNotFoundException: While trying to lookup 'ejb3.HelloUser/local' didn't find subcontext 'ejb3'. Resolved ''; remaining name 'ejb3/HelloUser/local'
at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
First of all, Weblogic print all jndi names assigned to every Enterprise bean, and you can get it directly. The second, remove context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local"); then in simple cases this function can helps you:
public static <T>T lookupBean(Class<T> beanClass) {
final String jndiName = "java:module/" + beanClass.getSimpleName();
logger.info("lookup : {}", jndiName);
try {
T bean = InitialContext.doLookup(jndiName);
logger.info("detected : {}", bean);
return bean;
}
catch(NamingException e) {
logger.error(e.getMessage(), e);
return null;
}
Can you provide me deployments log?? and rather then trying using initialcontext lookup with #EJB annotation.
I'm trying to write error handler in Spring-Boot for my controllers that would catch most possible errors (Spring, sql etc.). So far I'm able to get JSON response with Nulls however i'm unable to put any data inside. When I try to get error message in I just receive a blank page.
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
#RestController
public class BasicErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
#RequestMapping(value=ERROR_PATH)
#ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {
ErrorBody eBody = new ErrorBody();
eBody.setMessage(e.getCause().getMessage());
return eBody;
}
}
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
public class ErrorBody {
private String dateTime;
private String exception;
private String url;
private String message;
}
Yo can do something like this:
#ControllerAdvice
public class ControllerExceptionTranslator {
#ExceptionHandler(EntityNotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
#ResponseBody
SimpleErrorMessage handleException(EntityNotFoundException exception){
log.debug("Entity Not Found Exception {}",exception.getMessage());
log.trace(exception.getMessage(),exception);
return new SimpleErrorMessage("Entity not found","This resource was not found");
}
#ExceptionHandler({UsernameNotFoundException.class})
#ResponseStatus(HttpStatus.UNAUTHORIZED)
#ResponseBody
SimpleErrorMessage handleException(UsernameNotFoundException exception){
log.debug("Username not found {}",exception.getLocalizedMessage());
log.trace(exception.getMessage(),exception);
return new SimpleErrorMessage("Unaouthorized"," ");
}
}
I was able to get to data about errors and send them as json properly by using "HttpServletRequest request" and reading information from request.
#RequestMapping(value = ERROR_PATH)
public ErrorBody defaultErrorHandler(HttpServletRequest request) {....}
Here this is an example of #ExceptionHandler(Exception.class)
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
You can use #ControllerAdvice
package demo.controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
#ControllerAdvice
public class ExceptionControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("controller advice: init binder");
}
#ExceptionHandler(Exception.class)
public String exception(Exception e) {
System.out.println("controller advice: exception Handler");
System.out.println(e.getMessage());
return "error";
}
#ModelAttribute
public void modelAttribute(){
System.out.println("controller advice:model Attribute");
}
}
I have an issue while compiling my DocumentManager application in eclipse. it is not getting Hibernate.createBlob(file.getInputStream()) method and giving "The method createBlob(InputStream) is undefined for the type Hibernate". I am using Spring 3 and Hibernate 4 with Maven. Please suggest me some solution. Code below... Thanks
package com.ecom.data.access.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.ecom.data.access.dao.DocumentDAO;
import com.ecom.data.access.model.Document;
import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
#Controller
public class DocumentController {
#Autowired
private DocumentDAO documentDao;
#RequestMapping("/index")
public String index(Map<String, Object> map) {
try {
map.put("document", new Document());
map.put("documentList", documentDao.list());
}catch(Exception e) {
e.printStackTrace();
}
return "documents";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
#ModelAttribute("document") Document document,
#RequestParam("file") MultipartFile file) {
System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
try {
Blob blob = Hibernate.createBlob(file.getInputStream());
document.setFilename(file.getOriginalFilename());
document.setContent(blob);
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}
try {
documentDao.save(document);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/index.html";
}
#RequestMapping("/download/{documentId}")
public String download(#PathVariable("documentId")
Integer documentId, HttpServletResponse response) {
Document doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "inline;filename=\"" +doc.getFilename()+ "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(doc.getContent().getBinaryStream(), out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
#RequestMapping("/remove/{documentId}")
public String remove(#PathVariable("documentId")
Integer documentId) {
documentDao.remove(documentId);
return "redirect:/index.html";
}
}
The method Hibernate.createBlob() is depreciated, you can use Hibernate.getLobCreator(sessionfactory.getCurrentSession()).createBlob() instead
I think you can't resolve that method, as it doesn't exist.
In Hibernate 3, there was a method almost like what you're calling, but it had an additional integer argument specifying the size.
That method still exists in Hibernate 4, but in a different place. You probably want to call the Hibernate.getLobCreator method and then use the createBlob method on that.