Log requests and responses using Spring resttemplate - resttemplate

Getting below error:
aused by: java.lang.IllegalArgumentException: No InputStream specified
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.util.StreamUtils.copy(StreamUtils.java:118)
at org.springframework.util.StreamUtils.copyToByteArray(StreamUtils.java:56)
at org.springframework.http.client.BufferingClientHttpResponseWrapper.getBody(BufferingClientHttpResponseWrapper.java:69)
Code for logging requests and responses:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
private static final String CLASS_NAME = LoggingRequestInterceptor.class.getName();
private static final String LOG_NAME = "WBDO2Web";
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
String methodName="traceRequest";
LogUtil.w2Info(CLASS_NAME, methodName,"===========================request begin================================================",LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"URI : {}"+ request.getURI(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Method : {}"+ request.getMethod(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Headers : {}"+ request.getHeaders(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Request body: {}"+ new String(body, "UTF-8"),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"==========================request end================================================",LOG_NAME);
}
private void traceResponse(ClientHttpResponse response) throws IOException {
String methodName="traceResponse";
System.out.println("Response#########"+response.getBody());
final ClientHttpResponse responseWrapper = new BufferClientHttpResponseWrapper(response);
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseWrapper.getBody(), "UTF-8"));
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
LogUtil.w2Info(CLASS_NAME, methodName,"============================response begin==========================================",LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Status code : {}"+ response.getStatusCode(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Status text : {}"+ response.getStatusText(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Headers : {}"+ response.getHeaders(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"Response body: {}"+ inputStringBuilder.toString(),LOG_NAME);
LogUtil.w2Info(CLASS_NAME, methodName,"=======================response end=================================================",LOG_NAME);
}
}

Related

my netty program sometimes occur exception like “connection reset by peer”

i am coding a http server with netty-all-4.1.0.Final.jar,while the server listening,sometimes while happen "connection reset by peer",the detail like below:
Connection reset by peer
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1098)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:350)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:112)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:544)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:485)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:399)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:371)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:742)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:145)
at java.lang.Thread.run(Thread.java:748)
this is my main server code:
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
//将同一个http请求的内容组装到一起,调用一次handler
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new HttpServerHandler());
}
});
int port = ConfUtils.port;
ChannelFuture f = b.bind(port).sync();
logger.info("start lisner-------port is {}",port);
f.channel().closeFuture().sync();
} catch(Exception e){
logger.error(e.getMessage(),e);
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
this is my handler class:
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if(msg instanceof FullHttpRequest){
try{
logger.info("accept http msg!");
FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
ProcessMsg.dealMsg(fullHttpRequest);
logger.info("full header is {}",fullHttpRequest);
String responseHtml = "response from server!";
byte[] responseBytes = responseHtml.getBytes("UTF-8");
int contentLength = responseBytes.length;
FullHttpResponse response = new
DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().set("Content-Length", Integer.toString(contentLength));
Thread.sleep(1000 * 5);
ctx.writeAndFlush(response);
ctx.flush();
logger.info("response from server!");
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
else{
logger.info("this is not http request");
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LoggerFactory.getLogger("excplog").error(cause.getMessage(),cause);
ctx.close();
}
}
it's not always happend,sometimes happen and most times not,and we can't find any question about request

Xtext get AST from servlet

I want create API by xtextservlet:
URI: /xtext-service/parser
Input in body of request: "Hello Xtext!"
API response: Abstract Syntax Tree
I use Ecslipse DSL Tool then overwrite to MyDslServlet.xtend file:
#WebServlet(name = 'XtextServices', urlPatterns = '/xtext-service/*')
class MyDslServlet extends XtextServlet {
DisposableRegistry disposableRegistry
Pattern _pattern2 = Pattern.compile("/parser")
#Inject
private ParseHelper<Model> parseHelper
.....
override doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
val url = req.getRequestURL().toString()
val _matcher = _pattern2.matcher(url)
if (_matcher.find()) {
resp.setContentType("text/x-json")
val myDslParser = new MyDslParser()
val iParseResult = myDslParser.doParse(text)
val gson = new Gson()
gson.toJson(iParseResult.toString(), resp.writer)
} else {
val service = getService(req)
if (!service.hasConflict && (service.hasSideEffects || service.hasTextInput)) {
// Send error 405 (method not allowed)
super.doGet(req, resp)
} else {
doService(service, resp)
}
}
}
}
But, always error:
[qtp1650967483-11] WARN org.eclipse.jetty.servlet.ServletHandler - /xtext-service/parser
java.lang.NullPointerException
at org.eclipse.xtext.parser.antlr.AbstractAntlrParser.parse(AbstractAntlrParser.java:84)
at org.eclipse.xtext.parser.antlr.AbstractAntlrParser.doParse(AbstractAntlrParser.java:62)
at org.eclipse.xtext.parser.antlr.AbstractAntlrParser.doParse(AbstractAntlrParser.java:70)
at org.xtext.example.mydsl.web.MyDslServlet.doGet(MyDslServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at

Getting Session has been Expired for wicket 6.6 in IE and FireFox, working fine in Chrome

1) Upgraded our code from wicket 1.4.9 to wicket 6.6 and from jdk 1.6 to Jdk 1.8
2)First time i am able to log in application, if i click logout and click login
link from homepage getting session expired,
Is there any modification is required in wicket 6.6 to work fine in IE and FireFox, old code(wicket 1.4.9) was working fine in all 3 browsers.
3)We are using Jboss-eap-7.0 server
This the servlet class responsible for JSESSIONID
package com.bnaf.servlet;
import static com.bnaf.CLAS.clasConfiguration;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.grlea.log.SimpleLogger;
import org.owasp.esapi.ESAPI;
import com.bnaf.utils.Constants;
import com.bnaf.utils.RedirectUrlBuilder;
public class ReqAuthnServlet extends HttpServlet {
private static final SimpleLogger log = new SimpleLogger(ReqAuthnServlet.class);
private HttpServletResponse response = null;
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("*********************************************************");
log.info(" Authentication request process initiated ");
log.info("**********************************************************");
this.response = response;
// Valid request parameters
ESAPI.httpUtilities().setCurrentHTTP(request, response);
String sessionIdReq = ServletHelper.getSafeValue(request, "sessionid");
log.debug("Authentication request received. sessionIdReq: [" + sessionIdReq + "]");
if (sessionIdReq == null || sessionIdReq.equals("")) {
log.error("Failed to find requested session ID!");
String message = Constants.ERROR_CODE_ILLEGAL_ARGS + ";" + Constants.ERROR_MSG_ILLEGAL_ARGS;
handleResponse(HttpServletResponse.SC_BAD_REQUEST, message);
return;
}
sessionIdReq = sessionIdReq.trim();
if (request.getSession(false) != null) {
request.getSession(false).invalidate(); // invalidate old session
}
Cookie cookie = new Cookie("JSESSIONID", sessionIdReq);
cookie.setMaxAge(-1);
response.addCookie(cookie);
String authnURL = constructRedirectUrl(request, clasConfiguration().getAuthnURL()) + ";jsessionid=" + sessionIdReq;
log.debug("authnURL = " + authnURL);
response.sendRedirect(response.encodeRedirectURL(authnURL));
log.info(" ****** Generated authentication URL ****** " + authnURL);
log.info(" ****** Authentication request process completed ****** ");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private String constructRedirectUrl(HttpServletRequest request, String path) {
// construct redirect url base
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setScheme(request.getScheme());
urlBuilder.setServerName(request.getServerName());
urlBuilder.setPort(request.getServerPort());
urlBuilder.setContextPath(request.getContextPath());
urlBuilder.setServletPath(path);
return urlBuilder.getUrl();
}
private void handleResponse(int status, String msg) throws IOException {
if (status != HttpServletResponse.SC_OK) {
response.sendError(status, msg);
} else {
this.response.setStatus(status);
PrintWriter out = this.response.getWriter();
out.println(msg);
out.flush();
out.close();
}
}
}
Below code is in wicket6.6 -- you can find log out method, where session is invalidated.
import static com.bnaf.CLAS.clasConfiguration;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang.WordUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.core.request.handler.PageProvider;
import org.apache.wicket.core.request.handler.RenderPageRequestHandler;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.link.PopupSettings;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebResponse;//new
import org.apache.wicket.request.http.handler.RedirectRequestHandler;//news
import org.apache.wicket.request.mapper.parameter.PageParameters;//new
import org.apache.wicket.request.resource.CssPackageResource;//new
import org.bouncycastle.ocsp.RespData;
import org.grlea.log.SimpleLogger;
import com.bnaf.exception.AuthenticationServiceException;
import com.bnaf.model.ClasDB;
import com.bnaf.utils.Constants;
import com.bnaf.web.ClasApplication;
import com.bnaf.web.UserSession;
import com.bnaf.web.common.panel.ClasBaseAfterLoginPanel;
import com.bnaf.web.onlineregistration.ui.BnafContactAddress;
import com.bnaf.web.onlineregistration.ui.BnafPrivacyPolicy;
import com.bnaf.web.onlineregistration.ui.BnafServCenter;
public class ClasBaseAfterLogin extends WebPage {
ClasDB user;
String userId;
protected String accountType = "";
private static final SimpleLogger LOG = new SimpleLogger(ClasBaseAfterLogin.class);
public ClasBaseAfterLogin(PageParameters parameters) {
String ticket = parameters.get("ticket").toString();
String clasSessionId = parameters.get("clasSessionId").toString();
Authentication au = new Authentication();
List lst;
try {
lst = au.retrieveAuthnStatus(ticket, clasSessionId);
} catch (AuthenticationServiceException e) {
String locale = getSession().getLocale().toString();
String redirectUrl = clasConfiguration().getUserMgmtHomeUrl() + "?loc=" + locale;
getRequestCycle().scheduleRequestHandlerAfterCurrent(new RedirectRequestHandler(redirectUrl));//new
return;
}
String authStat = (String) lst.get(1);
boolean authStatus = Boolean.valueOf(authStat);
userId = (String) lst.get(0);
}
public ClasBaseAfterLogin() {
PopupSettings popupSettings = new PopupSettings().setHeight(825).setWidth(1000);
add(new BookmarkablePageLink("privacyPolicy", BnafPrivacyPolicy.class).setPopupSettings(new PopupSettings(PopupSettings.RESIZABLE
| PopupSettings.SCROLLBARS).setHeight(1500).setWidth(1000)));
add(new BookmarkablePageLink("contactUs", BnafContactAddress.class).setPopupSettings(new PopupSettings(PopupSettings.RESIZABLE
add(new BookmarkablePageLink("servCenter", BnafServCenter.class).setPopupSettings(new PopupSettings(PopupSettings.RESIZABLE
| PopupSettings.SCROLLBARS).setHeight(1500).setWidth(1000)));
Label label = new Label("pageTitle", getLocalizer().getString("label.title", this));
add(label);
userId = (String) UserSession.get().getMyObject();
if (userId == null) {
setResponsePage(Welcome.class);
} else {
try {
user = ClasApplication.get().getPasswordManagerService().getUserProfileDetails(userId);
} catch (AuthenticationServiceException e) {
LOG.errorException(e);
setResponsePage(new BnafCommonErrorPage(this.getPage(), getLocalizer().getString("label.applicaiton.error.page", this),
getLocalizer().getString("request.process.page.error", this)));
}
}
String nameOfUser = null;
if (user != null && user.getLangPref().equals(Constants.USER_LANG_PREF_ENG)) {
nameOfUser = WordUtils.capitalize(user.getName().concat(" ")
.concat((user.getSixthName() != null || (!user.getSixthName().equals("")) ? user.getSixthName() : "")));
} else if (user != null && user.getLangPref().equals(Constants.USER_LANG_PREF_AR)) {
nameOfUser = user.getNameArb().concat(" ")
.concat((user.getSixthNameArb() != null || (!user.getSixthNameArb().equals("")) ? user.getSixthNameArb() : ""));
}
add(new Label("userName", nameOfUser));
add(new ClasBaseAfterLoginPanel("clasbasepanel", userId));
// addCssToPage();
String accountType ="";
String registrationType =(String) UserSession.get().getRegistrationType();
if(!(registrationType.equals(""))){
if(registrationType.equals(Constants.LABEL_BASIC_EKEY_USER)){
accountType = getLocalizer().getString("standard.ekey.account", this);
}else if(registrationType.equals(Constants.LABEL_ADVANCE_EKEY_USER)){
accountType = getLocalizer().getString("advanced.ekey.account", this);
}
}
LOG.info("account_type:" + accountType);
add(new Label("accountType", accountType));
if (getSession().getId() == null) {
//getRequestCycle().setRedirect(true);
throw new RestartResponseException(new BnafCommonErrorPage(this.getPage(), getLocalizer().getString(
"label.session.expired.heading", this), getLocalizer().getString("label.session.expired.error", this)));
}
add(new Link("logout") {
public void onClick() {
String locale = getSession().getLocale().toString();
String redirectUrl = clasConfiguration().getUserMgmtHomeUrl() + "?loc=" + locale;
getSession().invalidateNow();
// getRequestCycle().setRedirect(true);
//getRequestCycle().setRequestTarget(new RedirectRequestTarget(redirectUrl));//old
getRequestCycle().scheduleRequestHandlerAfterCurrent(new RedirectRequestHandler(redirectUrl));//new
}
});
}
/**************NEW WAY TO ADD css FILE FROM WICKET 6.X ************************/
#Override
public void renderHead(IHeaderResponse response) {
response.render(CssHeaderItem.forUrl("css/$/styles.css".replace("$", getSession().getLocale().toString().toLowerCase())));
response.render(CssHeaderItem.forUrl("css/$/reset.css".replace("$", getSession().getLocale().toString().toLowerCase())));
}
/**************END NEW WAY TO ADD css FILE FROM WICKET 6.X ************************/
#Override
protected void configureResponse(WebResponse responses) {
super.configureResponse(responses);
//WebResponse response = (WebResponse) getRequestCycle().getResponse();// getResponse() use Get the active response at the request cycle.
responses.setHeader("Cache-Control", "no-cache, max-age=0,must-revalidate, no-store");
responses.setHeader("Expires", "-1");
responses.setHeader("Pragma", "no-cache");
// responses.setCharacterEncoding("text/html; charset=utf-8");
getSession().setLocale(new Locale(getSession().getLocale().toString()));
}
}

How can map the response to the request url with netty when handle http Keep-Alive connections

I want to read a list of url to the same site which support http 1.1 keep-live.
I try to use netty to do this and it works.
but when i get the response,i can not identify it is for which url.
how can i get the request url from method messageReceived below:
public static void main(String[] args) throws InterruptedException, URISyntaxException {
String host = "localhost";
int port = 8080;
String[] paths = new String[]{"1.html", "2.html", "3.html"};
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
#Override
protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
System.out.println("response from url ?:" + content.content().toString());
}
}
});
}
});
Channel ch = b.connect(host, port).sync().channel();
for (String path : paths) {
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
ch.writeAndFlush(request);
}
Try this:
p.addLast(new SimpleChannelInboundHandler<Object>() {
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
System.out.println("I'm HttpRequest");
FullHttpRequest req = (FullHttpRequest) msg;
if (HttpHeaders.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
System.out.println("response from url ?:" + req.getUri());
ByteBuf content = req.content();
}
}
});
Don't know what version of netty are you using. If 5.0+, rename channelRead to messageReceived.

Not getting value in midlet from servlet

I'm trying to send data from a midlet to a servlet and recieve back a response from the servlet but I don't get any value in response. I've tried to print it on command window and it seems to be null yet I expect only two values "ok" or "error". Please help me check the code and let me know what I should do to get the response right on the midlet. My code is below:
import javax.microedition.midlet.*;//midlet class package import
import javax.microedition.lcdui.*;//package for ui and commands
import javax.microedition.io.*;//
import java.io.*;
/**
* #author k'owino
*/
//Defining the midlet class
public class MvsMidlet extends MIDlet implements CommandListener {
private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;
private Form vCode;//vote code
private StringItem welStr;
private TextField phoneField;
private StringItem phoneError;
private Command quitCmd;
private Command contCmd;
//constructor of the midlet
public MvsMidlet() {
display = Display.getDisplay(this);//creating the display object
welForm = new Form("THE MVS");//instantiating welForm object
welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
+ "Please enter the your phone number below");//instantiating welStr string item
phoneError = new StringItem("", "");//intantiating phone error string item
phoneField = new TextField("Phone number e.g 0789834141", "", 10, 3);//phone number field object
quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
welForm.append(welStr);//adding welcome string item to form
welForm.append(phoneField);//adding phone field to form
welForm.append(phoneError);//adding phone error string item to form
welForm.addCommand(contCmd);//adding continue command
welForm.addCommand(quitCmd);//adding quit command
welForm.setCommandListener(this);
display.setCurrent(welForm);
}
//start application method definition
public void startApp() {
}
//pause application method definition
public void pauseApp() {
}
//destroy application method definition
public void destroyApp(boolean unconditional) {
}
//Command action method definition
public void commandAction(Command c, Displayable d) {
if (d == welForm) {
if (c == quitCmd) {
exitMidlet();//call to exit midlet
} else {//if the command is contCmd
//place a waiting activity indicator
System.out.println("ken de man");
Thread t = new Thread() {
public void run() {
try {
//method to connect to server
sendPhone();
} catch (Exception e) {
}//end of catch
}//end of ru()
};//end of thread
t.start();//starting the thread
}//end of else
}//end of first if
}//end of command action
//defining method to exit midlet
public void exitMidlet() {
display.setCurrent(null);
destroyApp(true);
notifyDestroyed();
}//end of exitMidlet()
//defining sendPhone method
public void sendPhone() throws IOException {
System.out.println("ken de man");//check
HttpConnection http = null;//HttpConnection variable
OutputStream oStrm = null;//OutputStream variable
InputStream iStrm = null;//InputStream variable
String url = "http://localhost:8084/MvsWeb/CheckPhone";//server url
try {
http = (HttpConnection) Connector.open(url);//opening connection
System.out.println("connection made");//checking code
oStrm = http.openOutputStream();//opening output stream
http.setRequestMethod(HttpConnection.POST);//setting request type
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
byte data[] = ("phone=" + phoneField.getString()).getBytes();
oStrm.write(data);
iStrm = http.openInputStream();//openning input stream
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
int length = (int) http.getLength();
String str;
if (length != -1) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
} else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) {
bStrm.write(ch);
}
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("de man");
System.out.println(str);
if (str.equals("ok")) {
//change to vcode form
} else {
//add error message to phone_error stingItem
}
}
} catch (Exception e) {
}
}
}//end of class definition
//servlet
import java.io.*;//package for io classes
import javax.servlet.ServletException;//package for servlet exception classes
import javax.servlet.http.*;
import java.sql.*;//package for sql classes
/**
*
* #author k'owino
*/
public class CheckPhone extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//declaring variables
PrintWriter pw;//PrintWriter object
String pnum;//phone parameter sent from client
Connection con = null;//connection variable
String dbDriver = "com.jdbc.mysql.Driver";//the database driver
String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
String dbUser = "root";//database user
String dbPwd = "";//database password
PreparedStatement pstmt = null;//Prepared statement variable
String query = "select * from student where stud_phone = ?;";
ResultSet rs = null;//resultset variable
String dbPhone=null;//phone from database
//getting the "phone" parameter sent from client
pnum = req.getParameter("phone");//getting the "phone" parameter sent from client
System.out.println(pnum);
//setting the content type of the response
res.setContentType("text/html");
//creating a PrintWriter object
pw = res.getWriter();
pw.println("ken");
try{//trying to load the database driver and establish a connection to the database
Class.forName(dbDriver).newInstance();//loading the database driver
con = DriverManager.getConnection(dbUrl,dbUser,dbPwd);//establishing a connection to the database
System.out.println("connection established");
}
catch(Exception e){
}
//trying to query the database
try{
pstmt = con.prepareStatement(query);//preparing a statement
pstmt.setString(1, pnum);//setting the input parameter
rs = pstmt.executeQuery();//executing the query assigning to the resultset object
//extracring data from the resultset
while(rs.next()){
dbPhone = rs.getString("stud_phone");//getting the phone number from database
}//end of while
if(pnum.equals(dbPhone)){
pw.print("ok");
pw.close();
}
else{
pw.print("error");
pw.close();
}
}
catch(Exception e){
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Resources