Websocket disconnects Openshift - java

Compiled files of chat websocket example that comes with Tomcat 7 works fine on localhost and Openshift.
However, when I compile those files myself it doesn't work on Openshift, although on localhost still works great (tomcat 7).
I tried to compile through netbeans, eclipse, and terminal (OSX). Tried all versions of dependencies, tried building as java webapp, maven webapp, tried to upload as war file but no success.
The module I'm trying to test is the chat websocket. It is composed by two classes, one xhtml file and two dependencies.
working: http://chatoriginal-helioha.rhcloud.com:8000/examples/websocket/chat.xhtml
not working: http://chat-helioha.rhcloud.com:8000/websocket/chat.xhtml
I'm not changing a single line of code, so the files I compile myself should be the same as the ones that comes already compiled right?
I also tried to decompile files using www.javadecompilers.com to see if there was anything extra there but I couldn't find any difference.
There are only three files on this project and they are shown bellow.
ChatAnnotation.java
package websockets.chat;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import util.HTMLFilter;
#ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
private static final Log log = LogFactory.getLog(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
new CopyOnWriteArraySet<>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
#OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
#OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, HTMLFilter.filter(message.toString()));
broadcast(filteredMessage);
}
#OnError
public void onError(Throwable t) throws Throwable {
log.error("Chat Error: " + t.toString(), t);
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
log.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
HTMLFilter.java
package util;
/**
* HTML filter utility.
*
* #author Craig R. McClanahan
* #author Tim Tye
*/
public final class HTMLFilter {
/**
* Filter the specified message string for characters that are sensitive
* in HTML. This avoids potential attacks caused by including JavaScript
* codes in the request URL that is often reported in error messages.
*
* #param message The message string to be filtered
*/
public static String filter(String message) {
if (message == null)
return (null);
char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuilder result = new StringBuilder(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
}
}
chat.xhtml
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Apache Tomcat WebSocket Examples: Chat</title>
<style type="text/css"><![CDATA[
input#chat {
width: 410px
}
#console-container {
width: 400px;
}
#console {
border: 1px solid #CCCCCC;
border-right-color: #999999;
border-bottom-color: #999999;
height: 170px;
overflow-y: scroll;
padding: 5px;
width: 100%;
}
#console p {
padding: 0;
margin: 0;
}
]]></style>
<script type="application/javascript"><![CDATA[
"use strict";
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
Console.log('Error: WebSocket is not supported by this browser.');
return;
}
Chat.socket.onopen = function () {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function () {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
Chat.socket.onmessage = function (message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host + '/examples/websocket/chat');
} else {
Chat.connect('wss://' + window.location.host + '/examples/websocket/chat');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
document.addEventListener("DOMContentLoaded", function() {
// Remove elements with "noscript" class - <noscript> is not allowed in XHTML
var noscripts = document.getElementsByClassName("noscript");
for (var i = 0; i < noscripts.length; i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}
}, false);
]]></script>
</head>
<body>
<div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
Javascript and reload this page!</h2></div>
<div>
<p>
<input type="text" placeholder="type and press enter to chat" id="chat" />
</p>
<div id="console-container">
<div id="console"/>
</div>
</div>
</body>
</html>

Related

Kerberos and Active Directory - where does the Active Directory Server name get set?

Total Kerberos and Active Directory newb here trying to get a very small sample working.
Found a Java Active Directory JAAS example onLine and here is the code.
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class ActiveDirectoryValidator
{
private static final String USERNAME = "FOO";
private static final String PASSWORD = "BAR";
private ActiveDirectoryValidator()
{
}
public boolean validateUser(String userName, String password)
{
try
{
LoginContext lc = null;
ADCallbackHandler ch = new ADCallbackHandler();
ch.setUserId(userName);
ch.setPassword(password);
lc = new LoginContext("JaasConfig", ch);
lc.login();
return true;
}
catch (LoginException le)
{
System.err.println("Authentication failed:");
System.err.println(" " + le.getMessage());
return false;
}
catch (NullPointerException e)
{
System.err.println("Authentication failed:");
System.err.println(" " + e.getMessage());
return false;
}
}
public static void main(String[] args) throws Exception
{
ActiveDirectoryValidator validateUser = new ActiveDirectoryValidator();
if (validateUser.validateUser(USERNAME, PASSWORD))
{
System.out.print("Authentication Successful");
}
else
{
System.out.print("Authentication Failed");
}
}
}
and
import javax.security.auth.callback.*;
import java.io.IOException;
public class ADCallbackHandler implements CallbackHandler
{
private String ADUserId;
private char[] ADPassword;
public void handle(Callback[] callbacks) throws java.io.IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof NameCallback)
{
NameCallback cb = (NameCallback)callbacks[i];
cb.setName(ADUserId);
}
else if (callbacks[i] instanceof PasswordCallback)
{
PasswordCallback cb = (PasswordCallback)callbacks[i];
cb.setPassword(ADPassword);
}
else
{
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}
public void setUserId(String userid)
{
ADUserId = userid;
}
public void setPassword(String password)
{
ADPassword = new char[password.length()];
password.getChars(0, ADPassword.length, ADPassword, 0);
}
}
Where does the Active Directory Server name go?
I would not expect it to be in the jaas.conf file as I have seen other programs set it via the UI interface and the jaas.conf file never changes.
What am I missing?
Is this example showing something totally different?
Moved my test to a Linux machine and ultimately found 2 missing components.
1 - when executing, I needed to include the
-Djava.security.auth.login.config=mylocation/jaas.conf
2 - I needed to edit the following file to include my Active Directory information
/etc/krb5.conf
After making the necessary references and entries, it worked.

JAVA REST jersy + Eclipse + MYSQL insert data into db

I am new to webservices,
inside chrome debugger getting error:
http://localhost:8080/CRUDrestApp/REST/WebService/addUser 500 (Internal Server Error)
And in postman app getting error:
http://localhost:8080/CRUDrestApp/REST/WebService/addUser?regUserName=a
status: 415 Unsupported Media Type
To fix this errors what necessary changes I have to do?
FeedService.java>>
package webService;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import model.AddUserManager;
import model.GetUserManager;
import com.google.gson.Gson;
import dto.FeedObjects;
import dto.AddUserObject;
#Path("/WebService")
public class FeedService {
//for insert query
#POST
#Path("/addUser")
#Consumes("application/json")
#Produces("application/json")
public void reguserdata(AddUserObject reguserData)
{
String feeds = null;
try
{
//StringBuffer sb = new StringBuffer();
System.out.println("Inside reguserdata");
Gson gson = new Gson();
System.out.println("Inside add User web service::"+gson.toJson(reguserData));
feeds = gson.toJson(reguserData);
AddUserManager projectManager= new AddUserManager();
projectManager.SetFeeds(feeds);
} catch (Exception e)
{
System.out.println("error");
}
}
}
AddUser.Java>>>
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.AddUserObject;
public class AddUser {
public ArrayList<AddUserObject> GetFeeds(Connection connection, String receivedData) throws Exception
{
ArrayList<AddUserObject> regData = new ArrayList<AddUserObject>();
String receivedData1 = receivedData;
try
{
//String uname = request.getParameter("uname");
//PreparedStatement ps = connection.prepareStatement("SELECT * from users");
//ps.setString(1,uname);
//PreparedStatement ps = connection.prepareStatement("insert into users(username,password,hint1,hint2,emailid,uid) values(?,?,?,?,?,?)");
PreparedStatement ps = connection.prepareStatement("insert into users (username) values (?)");
AddUserObject feedObject = new AddUserObject();
System.out.println("Add>>receivedData1.valueOf(0):"+receivedData1.valueOf(0));
feedObject.setRegUserName(receivedData1.valueOf(0));
System.out.println("Add>>getRegUserName:"+feedObject.getRegUserName());
ps.setString(1, feedObject.getRegUserName());
// ps.setString(2, feedObject.getRegPassword());
// ps.setString(3, feedObject.getRegHint1());
// ps.setString(4, feedObject.getRegHint2());
// ps.setString(5, feedObject.getRegEmail());
// ps.setString(6, feedObject.getRegUid());
regData.add(feedObject);
ps.executeUpdate();
ps.close();
return regData;
}
catch(Exception e)
{
throw e;
}
}
}
AddUserObject.java>>>
package dto;
public class AddUserObject {
private String regId;
private String regusername;
private String regpassword;
private String reghint1;
private String reghint2;
private String regemail;
private String reguid;
/**
* #return the url
*/
public String getRegId() {
return regId;
}
/**
* #param reguid to set
*/
public void setRegId(String regId) {
this.regId = regId;
}
/**
* #return the title
*/
public String getRegUserName() {
return regusername;
}
/**
* #param title the title to set
*/
public void setRegUserName(String regusername) {
this.regusername = regusername;
}
/**
* #return the description
*/
public String getRegPassword() {
return regpassword;
}
/**
* #param description the description to set
*/
public void setRegPassword(String regpassword) {
this.regpassword = regpassword;
}
/**
* #return the url
*/
public String getRegHint1() {
return reghint1;
}
/**
* #param url the url to set
*/
public void setRegHint1(String reghint1) {
this.reghint1 = reghint1;
}
/**
* #return the url
*/
public String getRegHint2() {
return reghint2;
}
/**
* #param url the url to set
*/
public void setRegHint2(String reghint2) {
this.reghint2 = reghint2;
}
/**
* #return the url
*/
public String getRegEmail() {
return regemail;
}
/**
* #param reguid to set
*/
public void setRegEmail(String regemail) {
this.regemail = regemail;
}
/**
* #return the url
*/
public String getRegUid() {
return reguid;
}
/**
* #param reguid to set
*/
public void setRegUid(String reguid) {
this.reguid = reguid;
}
}
AddUserManeger.java>>>
package model;
import java.sql.Connection;
import java.util.ArrayList;
import dao.Database;
import dao.AddUser;
import dto.AddUserObject;
public class AddUserManager {
public static ArrayList<AddUserObject> SetFeeds(String feeds2)throws Exception {
ArrayList<AddUserObject> feeds = null;
String receivedData = feeds2;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
AddUser project= new AddUser();
feeds=project.GetFeeds(connection , receivedData);
} catch (Exception e) {
throw e;
}
return feeds;
}
}
app.js>>
var app = angular.module("mainApp", ['ngRoute','ngAnimate']);
var baseUrl ="http://localhost:8080/CRUDrestApp/REST/WebService";
console.log("Inside App js");
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html',
controller: 'homeCtrl'
}).
when('/register', {
templateUrl: 'register.html',
controller: 'registerCtrl'
}).
when('/login', {
templateUrl: 'login.html',
controller: 'loginCtrl'
}).
otherwise({
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
}]);
app.controller('NavController', function ($scope, $location) {
$scope.isCollapsed = true;
$scope.$on('$routeChangeSuccess', function () {
$scope.isCollapsed = true;
});
$scope.getClass = function (path) {
if(path === '/') {
if($location.path() === '/') {
return "active";
} else {
return "";
}
}
if ($location.path().substr(0, path.length) === path) {
return "active";
} else {
return "";
}
}
});
app.controller('homeCtrl', function($http, $scope, $timeout) {
});
app.controller('loginCtrl', function($http, $scope, $timeout) {
});
console.log("after route provider");
app.controller('registerCtrl', function($http, $scope, $timeout) {
console.log('inside registerAppCtrl controller');
$scope.addUser = function() {
var userdetails = JSON.stringify($scope.userAdd);
console.log("$scope.userAdd::"+userdetails);
if($scope.userAdd.regUserName == "" || $scope.userAdd.regUserPass == "" || $scope.userAdd.regUserCPass == "" || $scope.userAdd.regHint1 == "" || $scope.userAdd.regHint2 == ""){
console.log('Insert mandatory field values');
}
else{
$.ajax({
url: baseUrl + '/addUser',
dataType: 'json',
type: 'post',
contentType: 'application/json ',
data: userdetails,
success: function( data, textStatus, jQxhr ){
//$('#response pre').html( data );
console.log("successfully retrived response from server:::"+data);
/* console.log(data); */
$scope.userAdd = '';
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
};
});
Register.html
<section id="" ng-controller="registerCtrl">
<form>
<div>
User Name
</div>
<div>
<input type="text" ng-model="userAdd.regUserName" required>
</div>
<div>
Password
</div>
<div>
<input type="password" ng-model="userAdd.regUserPass" >
</div>
<div>
Confirm Password
</div>
<div>
<input type="password" ng-model="userAdd.regUserCPass" >
</div>
<div>
Enter Hint1
</div>
<div>
<input type="text" ng-model="userAdd.regHint1" >
</div>
<div>
Enter Hint2
</div>
<div>
<input type="text" ng-model="userAdd.regHint2" >
</div>
<div>
Enter UID
</div>
<div>
<input type="text" ng-model="userAdd.regUid" >
</div>
<div>
<input type="submit" name="Register" value="Register" ng-click="addUser()">
</div>
<div>
Login
</div>
</form>
</section>
make an empty constructor in your AddUserObject.java
public AddUserObject(){}

SQL syntax error in pagination query

I'm trying to make pagination in my jsp page. But I didn't get data from Database. I got an error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1".
I didn't understand what's wrong. would you please check my code and help me to solve the problem?
BooksInfo.java
package com.sreejonee.books;
import java.sql.Date;
import java.sql.Timestamp;
public class BooksInfo {
private int book_id;
private String bookName;
private String filename;
private String writerName;
private String book_details;
private Timestamp date_time;
private int rating;
private int parentscat_id;
private String parentscat_name;
private String thumCoverImag;
private String filePath;
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getWriterName() {
return writerName;
}
public void setWriterName(String writerName) {
this.writerName = writerName;
}
public String getBook_details() {
return book_details;
}
public void setBook_details(String book_details) {
this.book_details = book_details;
}
public Timestamp getDate_time() {
return date_time;
}
public void setDate_time(Timestamp date_time) {
this.date_time = date_time;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getParentscat_id() {
return parentscat_id;
}
public void setParentscat_id(int parentscat_id) {
this.parentscat_id = parentscat_id;
}
public String getParentscat_name() {
return parentscat_name;
}
public void setParentscat_name(String parentscat_name) {
this.parentscat_name = parentscat_name;
}
public String getThumCoverImag() {
return thumCoverImag;
}
public void setThumCoverImag(String thumCoverImag) {
this.thumCoverImag = thumCoverImag;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
BooksInfoDAO.java
package com.sreejonee.books;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.sreejonee.db.ConnectionFactory;
import com.sreejonee.db.DBConnector;
public class BooksInfoDAO {
Connection connection;
Statement stmt;
private int noOfRecords;
private static Connection getConnection()
throws SQLException,
ClassNotFoundException
{
Connection con = ConnectionFactory.
getInstance().getConnection();
System.out.println("connected!");
return con;
}
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
List<BooksInfo> bookslist = new ArrayList<BooksInfo>();
BooksInfo books = null;
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
books = new BooksInfo();
books.setBook_id(rs.getInt("book_id"));
books.setBook_details(rs.getString("book_details"));
books.setBookName(rs.getString("bookName"));
books.setWriterName(rs.getString("writerName"));
books.setDate_time(rs.getTimestamp("date_time"));
books.setParentscat_id(rs.getInt("parentscat_id"));
books.setParentscat_name(rs.getString("parentscat_name"));
books.setFilename(rs.getString("filename"));
books.setFilePath(rs.getString("filePath"));
books.setRating(rs.getInt("rating"));
books.setThumCoverImag(rs.getString("thumCoverImag"));
bookslist.add(books);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if (rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
return bookslist;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
Servlet:
BooksInfoServlet.java
package com.sreejonee.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sreejonee.books.BooksInfo;
import com.sreejonee.books.BooksInfoDAO;
#WebServlet("/BooksInfoServlet")
public class BooksInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BooksInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = 1;
int recordsPerPage = 5;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
int noOfRecords = booksInfoDAO.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("booksList", bookslist);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("user.jsp");
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP page:
<c:forEach var="books" items="${bookslist}">
<div id="${books.filename}" class="single_midlecontent_component">
<div class="socialicon_on_post">
<h4>
<i class="fa fa-facebook-square"></i>
</h4>
</div>
<div class="title_of_post ">
<a href="#" class="media-left">
<img class="media-object" src="${books.getFilePath()+File.separator+books.getThumCoverImag()}" alt="...">
</a>
<h5 class="media-body ">
<span>${books.getBookName()}</span>
</h5>
<h5 class="media-body ">
<span>by ${books.getWriterName()}</span>
</h5>
<p class="date_time media-body">${books.getDate_time()}</p>
</div>
<div class="body_of_post">
<p>${books.getBook_details()}</p>
<img src="" class="img-responsive" alt="Responsive image">
</div>
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<div class="download_book">
<form action="DownloadFileServlet" method="post">
<input type="hidden" name="filename" value="${books.getFilename()}">
<div>
<input type="hidden" name="parentscat_name" value="${books.getParentscat_name()}">
</div>
<div class="download_button">
<input class="btn btn-default " type="submit" value="Download">
</div>
</form>
</div>
<div class="bottom_of_post"></div>
</div>
I can see two errors here.
First one:
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
There is a space missing after limit -- the way you wrote it, it will generate ... limit10, 5.
Second one:
I think the caller of viewAllBooksInfo() gives a wrong offset argument. Based on the error, I assume that offset is -10 which is illegal because the arguments to the limit clause in MySQL need to be non-negative.
In your updated question, you show this code:
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
Obviously, because recordsPerPage is 5, and offset is -10, page seems to be -1. You have not shown the Code for the page which calls the BooksInfoServlet, but I guess you have entered -1 as the requested page number there.
You should have looked yourself before asking this question. It is expected from you that you should first try to remove these error yourself.
If you would look into the error stack, it says:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1"
If you can look carefully, the limit options are "-10, 5". Limit arguments in MySQL should be non-negative.
And in BooksInfoDAO.java code:
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
...
you are missing a space between the limit clause and the offset parameter.

How to manage back end process with Tomcat?

I have a web page that the user pushes a button and initiates an action in a proprietery app (which resides in Tomcat).
That action is a long running process and the only way I have to see what's going on is to log onto the server and look at a log file.
I wrote a quick Java function that reads the log file and gives feedback on what's happening. (Essentially it just tails the file and parses out the things I need)
I'd like to be able to add a jsp that I can view the output without logging into the server.
===
From a design standpoint, I understand that the JSP should return quickly with a result and not just keep on processing.
So my idea is to create a simple web page that queries the jsp for an update and writes the latest info to the screen. Wait 30 seconds, poll the server again, and append the latest update.
What I'm struggling to grasp is how to get the JSP to communicate with the back end process, and how that back end process should be spawned / killed.
This is a very occasional thing (once every two weeks, start to completion takes an hour or two), so I don't want a daemon running all the time. I want to be able to turn it on temporarily and turn it off.
If I spawn a process from within a simple servlet, how do I end that process when I'm done?
And how do I communicate with it?
You can create a java.lan.Runnable witch reads the file content an saves it into a buffer. The Runnable reads the file content withing a while loop for witch the break condition can be set from outside, Thread that is executing your Runnable will terminate whe the run method of your Runnable terminates.
In your JSP you can create a java.lang.Thread and pass an instance of your Runnable to it. Save th instace of the runable in the ServletContext so you can access it across the requests. If you want to terminate the polling than just set the break condition of your Runnable from the JSP, the rum method will terminate and thus the thread too.
You can use javascript setInterval() function and XMLHttpRequest refresh the page.
here is a sample basic implemntation (I hope this will meet your requirements):
Polling Runnable
package com.web;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class FilePollingThread implements Runnable {
private String filepath = null;
private boolean polling = false;
private StringBuffer dataWritenAfterLastPoll = null;
private String error = null;
public FilePollingThread(String filepath) {
this.filepath = filepath;
}
#Override
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath)));
dataWritenAfterLastPoll = new StringBuffer();
polling = true;
String line = null;
while(polling) {
try {
line = br.readLine();
while(line == null) {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
error = e.toString();
}
line = br.readLine();
}
dataWritenAfterLastPoll.append(markUp(line));
} catch (IOException e) {
e.printStackTrace();
error = e.toString();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
error = e.toString();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
error = e.toString();
}
}
}
}
private String markUp(String line) {
String markup = "";
if(line != null) {
markup = "<div style=\"height: 6px\"><span style=\"line-height: 1.1;\">" + line + "</span></div>\n";
}
return markup;
}
public synchronized void stopPolling() {
polling = false;
}
public synchronized String poll() {
String tmp = markUp(error == null ? "Not ready" : error);
if(dataWritenAfterLastPoll != null) {
tmp = dataWritenAfterLastPoll.toString();
dataWritenAfterLastPoll = new StringBuffer();
}
return tmp;
}
}
And a JSP witch initiats the polling an keep retrieving data
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.web.FilePollingThread" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Poll file</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link rel="stylesheet" type="text/css" href="style/default.css"></link>
<script type="text/javascript">
var c = 1;
var ih;
var polling = false;
var filepath = null;
function startPolling(interval) {
ih = setInterval(function () {
try {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
var w = getElementById('ajax_content');
w.innerHTML = w.innerHTML + xmlHttp.responseText;
getElementById('page_refresh').innerHTML = c++;
polling = true;
window.scrollTo(0, document.body.scrollHeight);
} else {
polling = false;
throw 'HTTP ' + xmlHttp.status;
}
}
};
xmlHttp.open('GET', 'pollfile.jsp?filepath=' + filepath + '&c=' + c, true);
xmlHttp.send();
} catch(e) {
alert('Error at startPolling: ' + e);
clearInterval(ih);
}
}, interval);
}
function startStopPolling() {
var orgPolling = polling;
try {
if(polling) {
polling = false;
clearInterval(ih);
doPolling();
} else {
polling = true;
doPolling();
startPolling(1000);
}
flipStartStopButtonsLabel();
} catch(e) {
polling = orgPolling;
flipStartStopButtonsLabel();
alert('Error at startStopPolling: ' + e);
}
}
function flipStartStopButtonsLabel() {
var label;
if(polling) {
c = 1;
label = 'Stop polling';
getElementById('page_refresh').innerHTML = '0';
} else {
label = 'Sart polling';
getElementById('page_refresh').innerHTML = 'stoped';
}
var buttons = document.getElementsByName('start_stop_polling');
if(buttons) {
for(var i = 0; i < buttons.length; i++) {
buttons[i].value = label;
}
}
}
function doPolling() {
var url = 'pollfile.jsp?polling=';
if(polling) {
filepath = getElementById('filepath');
if(filepath && filepath.value && filepath.value.length > 0) {
url += 'true&filepath=' + encodeURIComponent(filepath.value);
} else {
throw 'No filepath specified.';
}
} else {
url += 'false';
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status != 200) {
throw 'HTTP ' + xmlHttp.status;
}
}
};
xmlHttp.open('POST', url, false);
xmlHttp.send();
}
function clearWindow() {
var w = getElementById('ajax_content');
if(w) {
w.innerHTML = '';
}
}
function getElementById(id) {
try {
if(id) {
elm = document.getElementById(id);
return elm;
}
} catch(e) {
alert('Error at getElementById: ' + e);
}
return null;
}
</script>
</head>
<body>
<%
String polling = request.getParameter("polling");
if("true".equals(polling)) {
String filepath = request.getParameter("filepath");
if(filepath != null && filepath.length() > 0) {
FilePollingThread pollingThread = new FilePollingThread(filepath);
new Thread(pollingThread, "polling thread for file '" + filepath + "'").start();
request.getServletContext().setAttribute("pollingThread", pollingThread);
}
} else if("false".equals(polling)) {
FilePollingThread pollingThread = (FilePollingThread) request.getServletContext().getAttribute("pollingThread");
if(pollingThread != null) {
pollingThread.stopPolling();
}
} else {
FilePollingThread pollingThread = (FilePollingThread) request.getServletContext().getAttribute("pollingThread");
if(pollingThread != null) {
response.getWriter().println(pollingThread.poll());
response.getWriter().close();
return;
}
}
%>
<div class="label">
<span>Page polling:</span>
</div>
<div style="float: left;">
<span id="page_refresh">0</span>
</div>
<div class="clear_both"> </div>
<form id="input_form" action="pollfile.jsp" method="get">
<div>
<div style="float: left;">
<label>Filepath:
<input style="height: 24px;" id="filepath" type="text" size="120" value=""/>
</label>
</div>
<div style="clear: both;"/>
<div style="float: left;">
<input style="height: 24px;" name="start_stop_polling" id="start_stop_polling_button" type="button" onclick="startStopPolling(); return false;" value="Start polling"/>
</div>
<div style="float: left;">
<input style="height: 24px;" name="clear_window" id="clear_window_button" type="button" onclick="clearWindow(); return false;" value="Clear"/>
</div>
<div style="clear: both;"> </div>
</div>
</form>
<div id="ajax_content">
</div>
<div>
<div style="float: left;">
<input style="height: 24px;" name="start_stop_polling" id="start_stop_polling_button" type="button" onclick="startStopPolling(); return false;" value="Start polling"/>
</div>
<div style="float: left;">
<input style="height: 24px;" name="clear_window" id="clear_window_button" type="button" onclick="clearWindow(); return false;" value="Clear"/>
</div>
<div style="clear: both;"> </div>
</div>
</body>
</html>
EDIT
there is a bug in FilePollingThread: if no data is available in the file the thread might get stuck in inner while loop. it should be
while(line == null && polling)
also the JSP will not work on IE (testet on IE9). It seems that the data writen to the response in the line
response.getWriter().println(pollingThread.poll());
contains the HTML of the hole page. If added to the target div IE seems not able to render it.
I made another version using a simple static HTML file an a servlet as it offers more controle on what is writen to response.
If you are interested in the code let me know.
You should consider using something like JMS to control your background process.
For control, your front-end code can send messages start/stop/inspect the process.
For monitoring, your process can publish to a JMS topic for your front end code to read.

Read google book in android

i have developed an application in which i fetch books using googleapibook search. I have an isbn no. Now i want to let my user read that book page by page. But i didn't find any method or solution to read book in java or android.
Here is my code.
package com.project.bookhunt;
import java.net.URL;
import java.util.ArrayList;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.widget.Toast;
public class BookSearchParser
{
Context m_context;
static ArrayList<Book_Item> books= new ArrayList<Book_Item>();
String searchResult;
BookSearchParser(Context c,URL url)
{
try
{
m_context=c;
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url.toString());
int statusCode = client.executeMethod(getMethod);
System.out.println("status Code"+statusCode);
System.out.println(getMethod.getResponseBodyAsString());
searchResult=getMethod.getResponseBodyAsString();
parseJSON(searchResult);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static ArrayList<Book_Item> getBooks()
{
return books;
}
private void parseJSON(String object)
{
try
{
books=new ArrayList<Book_Item>();
JSONObject jSonObject = new JSONObject(object);
if(jSonObject.getInt("totalItems")>0)
{
JSONArray jSonObjectArray = jSonObject.getJSONArray("items");
for(int count = 0; count < jSonObjectArray.length();count++)
{
Book_Item item=new Book_Item();
JSONObject jsonItem = (JSONObject) jSonObjectArray.get(count);
if(jsonItem.has(("id")))
{
item.setId(jsonItem.getString("id"));
}
// else
// {
// item.setId("No Id");
// }
if(jsonItem.has("selfLink"))
{
item.setSelfLink(jsonItem.getString("selfLink"));
}
// else
// {
// item.setSelfLink("No Link Avilable");
// }
if(jsonItem.has("volumeInfo"))
{
JSONObject volumeInfo = (JSONObject)jsonItem.get("volumeInfo");
if(volumeInfo.has("title"))
{
item.setTitle(volumeInfo.getString("title"));
}
// else
// {
// item.setTitle("No Title");
// }
if(volumeInfo.has("subtitle"))
{
item.setSubTitle(volumeInfo.getString("subtitle"));
}
// else
// {
// item.setSubTitle("No SubTitle Avilable");
// }
//
if(volumeInfo.has("authors"))
{
JSONArray Authors = volumeInfo.getJSONArray("authors");
for(int authorCount=0;authorCount<Authors.length();authorCount++)
{
item.setAuthor(Authors.getString(authorCount));
}
}
if(volumeInfo.has("description"))
{
item.setDiscription(volumeInfo.getString("description"));
}
// else
// {
// item.setDiscription("No Description Avilable");
// }
if(volumeInfo.has("averageRating"))
{
item.setRating(volumeInfo.getString("averageRating"));
}
if(volumeInfo.has("industryIdentifiers"))
{
JSONArray isbnArray = volumeInfo.getJSONArray("industryIdentifiers");
for(int isbnCount=0;isbnCount<isbnArray.length();isbnCount++)
{
JSONObject isbn=(JSONObject)isbnArray.get(isbnCount);
if(isbn.getString(("type")).equals("ISBN_10"))
{
item.setIsbn10(isbn.getString("identifier"));
}
if(isbn.getString(("type")).equals("ISBN_13"))
{
item.setIsbn13(isbn.getString("identifier"));
}
}
}
if(volumeInfo.has("categories"))
{
JSONArray categoriesArray = volumeInfo.getJSONArray("categories");
for(int j=0;j<categoriesArray.length();j++)
{
item.setCategory(categoriesArray.getString(j));
}
}
// else
// {
// item.setCategory("No category");
// }
//
if(volumeInfo.has("imageLinks"))
{
JSONObject ImageLinks = volumeInfo.getJSONObject("imageLinks");
if(ImageLinks.has("smallThumbnail"))
{
item.setSmallThumb(ImageLinks.getString("smallThumbnail"));
}
if(ImageLinks.has("thumbnail"))
{
item.setThumb(ImageLinks.getString("thumbnail"));
}
// else
// {
// //item.setSmallThumb("No Thumbnail");
// }
//
if(ImageLinks.has("previewLink"))
{
item.setPreviewLink((ImageLinks.getString("previewLink")));
}
// else
// {
// item.setPreviewLink("No Thumbnail");
// }
}
// else
// {
// //item.setSmallThumb("No Thumbnail");
// item.setPreviewLink("No Preview");
// }
}
books.add(item);//add one volume to array_list
}
}
else
{
Toast.makeText(m_context, "0 Record Found..",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Here with a possible solution.
As you are using the Book Search API and you are able to get the ISBN of the book
Then, to allow your user to read the book , maybe:
Using a WebView with the Google Docs Embedded Viewer API + your ISBN you will be able to load the book preview inside that WebView
for example, a WebView with this code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Books Embedded Viewer API Example</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("books", "0");
function initialize() {
var viewer = new google.books.DefaultViewer(document.getElementById('viewerCanvas'));
viewer.load('**ISBN:0738531367**');
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="viewerCanvas" style="width: 600px; height: 500px"></div>
</body>
</html>
This is my solution for you, the trick is located at : google.books.DefaultViewer(document.getElementById('viewerCanvas'));
viewer.load('ISBN:0738531367');
I hope this helps you
for a better understanding on this please visit http://code.google.com/apis/books/docs/viewer/developers_guide.html at The "Hello, World" of the Embedded Viewer API
When you use that API you can get something like this: http://code.google.com/apis/books/docs/viewer/examples/book-simple.html

Categories

Resources