how to run java on website and to get values to html - java

i know the question may sound easy to most of you but I am stuck with it.
First of all i like to define what i am trying to achieve.
on eclipse i am running a piece of code that sends some data over specific port, and via html and javascript i am getting those that it's sent and print them on screen.
I have an account from one of free hosting websites.
I want to run my code on that website e.g mywebsite.blahblah.com/...
and from html file on my computer i want to access that website, get those values produced by java code and print them on screen.
I have no idea where to start.
the codes are
java and html
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class GPSServer extends WebSocketServer {
static int port = 9876;
public GPSServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public GPSServer(InetSocketAddress address) {
super(address);
}
public void sendData(String s) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(s);
}
}
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
System.out.println(arg0.getRemoteSocketAddress().getAddress()
.getHostAddress()
+ " connected to the server!");
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
System.out.println(arg0 + " disconnected!");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
arg1.printStackTrace();
if (arg0 != null) {
}
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
System.out.println(arg0 + ": " + arg1);
}
public static Runnable sendData() {
Runnable r = new Runnable() {
#Override
public void run() {
WebSocketImpl.DEBUG = true;
GPSServer server;
try {
server = new GPSServer(GPSServer.port);
server.start();
System.out.println("GPS server started at port: "
+ server.getPort());
double longitude = 39.55;
double latitude = 22.16;
String lng = Double.toString(longitude);
String ltd = Double.toString(latitude);
String all = lng + "-" + ltd;
while (true) {
server.sendData(all);
/*
* server.sendData(Double.toString(longitude));
* System.out.println("longitude sent...");
* server.sendData(Double.toString(latitude));
* System.out.println("latitude sent...");
*/
Thread.sleep(5000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return r;
}
public static void main(String[] args) throws UnknownHostException {
Thread thread = new Thread(GPSServer.sendData());
thread.start();
}
}
--
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
var lat;
var lng;
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9876/echo");
ws.onopen = function()
{
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var partsArray = evt.data.split('-');
lng=partsArray[0];
lat=partsArray[1];
alert(lat);
alert(lng);
};
ws.onclose = function() {
alert("Connection is closed...");
console.log("Connection is closed...");
};
}
else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
<div>
<p id="para"> BASIC HTML!</p>
</div>
</body>
</html>
Thanks!

I'm assuming you're very new to all this web development. I haven't studied your code fully but the basic idea is you need a server side scripting language like JSP(of course JSP because you're using Java Code). I hope you know Javascript's basic idea is to use resources on the client's end, or to load data dynamically. So if you're only concerned with displaying some values from server to the client, you can simple make a servlet which will print your data.
Following MVC pattern,
Controller== Make a servlet which will handle the request made by user(i.e. the link which will show data,basically). Set your Model in this controller once you receive a request(you can decide what to do on GET/POST separately too).
Model== Make an abstract representation(class of Java) holding all your data that is to be displayed.
View== Here you'll receive the model. In other words, this will be your HTML. You can use JSP helpers to customize the view, the basic idea is to control HOW DATA WILL BE SHOWN TO THE USER(hence the name View). HTML will be automatically generated at run-time and passed to the user.
Again, I say I'm assuming you're very new to web development. Please let me know if I haven't understood your question well. Enjoy coding.

Related

Wicket, modify HTML <body> element

I want to modify the HTML body tag when I open a Wicket-Bootstrap Modal. What I'm trying to achieve is <body class="modal-open"> instead of <body>
Using Wicket 8 M8 , I have this code:
owsImportDialog = new MyModalBootstrapDialog("owsImportDialog"
, new CompoundPropertyModel<>(new BopOwsTO())) {
#Override
void importOws(AjaxRequestTarget target, IModel<BopOwsTO> owsModel) {
appendCloseDialogJavaScript(target);
BopOwsTO owsTo = owsModel.getObject();
try {
importOwsCapabilities(owsTo);
owsViewDialog.header(Model.of("OWS anzeigen"))
.setModel(Model.of(owsTo.getServiceId()));
owsViewDialog.appendShowDialogJavaScript(target);
}
catch (OwsCapsImportException e) {
String localizedMessage = e.getLocalizedMessage();
importAlert.setModelObject(localizedMessage);
importAlert.appendShowDialogJavaScript(target);
error(localizedMessage);
}
finally {
target.appendJavaScript("document.getElementsByTagName('body')[0]" +
".setAttribute('class', 'modal-open');");
// target.appendJavaScript("document.body.setAttribute('class', 'modal-open');");
// target.prependJavaScript("document.body.setAttribute('class', 'modal-open');");
// target.appendJavaScript("alert('Hallo');");
// owsViewDialog is a child of owsView WebMarkupContainer
target.add(owsView, feedback);
}
}
#Override
void saveOws(AjaxRequestTarget target, IModel<BopOwsTO> owsModel)
{ }
#Override
void cancel(AjaxRequestTarget target)
{ }
};
If the line target.appendJavaScript("alert('Hallo');"); is active I actually see the alert window.
I also tried this code in the page class:
#Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
PackageResourceReference resourceReference = new PackageResourceReference(
getClass(), "../css/BuiOwsPage.css");
CssReferenceHeaderItem cssRef = CssReferenceHeaderItem.forReference(resourceReference);
response.render(cssRef);
response.render(OnLoadHeaderItem
.forScript("document.body.setAttribute('class', 'modal-open');"));
}
But none of my attempts was succesful.
Update
The answer of #martin-g didn't solve the issue.
I'm quite sure that the problem is caused by the sequence of these statements:
{
appendCloseDialogJavaScript(target);
...
try {
owsViewDialog.appendShowDialogJavaScript(target);
....
}
catch { ... }
finally {
target.add(owsView, feedback);
}
}
When this modal is closed because of appendCloseDialogJavaScript() ,
the class modal-open is erased from the class attribute of the <body> .
Then owsViewDialog opens, but modal-open isn't inserted in class, no matter if I append the snippet jQuery(document.body).addClass('modal-open') or not. The missing modal-open means that the page can't be scrolled.
Since Wicket and Bootstrap are used then jQuery is also available. I would recommend you to use jQuery(document.body).addClass('modal-open').
There must be a reason why jQuery has both addClass() and attr()!

ORIGINAL EXCEPTION: ReferenceError: io is not defined

I am trying to create a chat app using Ionic2 (Angular2). I have a Java Server and Ionic 2 Client.
I get the following error:
ORIGINAL EXCEPTION: ReferenceError: io is not defined
Any suggestions please?
Client
import { Component, NgZone } from '#angular/core';
import { Http } from "#angular/http";
declare var io;
//require ('io');
#Component({
templateUrl: 'build/pages/chat/chat.html',
})
export class ChatPage {
private socketHost: string = "http://localhost:3700";
private messages: string[] = [];
private zone: NgZone = null;
private chatBox: string = null;
private socket: any = null;
constructor(http: Http) {
this.messages = [];
this.zone = new NgZone({ enableLongStackTrace: false });
//let url = this.socketHost + "/fetch";
let url = this.socketHost;
http.get(url).subscribe((success) => {
var data = success.json();
for (var i = 0; i < data.length; i++) {
this.messages.push(data[i].message);
}
}, (error) => {
console.log(JSON.stringify(error));
});
this.chatBox = "";
this.socket = io(this.socketHost);
this.socket.on("chat_message", (msg) => {
this.zone.run(() => {
this.messages.push(msg);
});
});
}
send(message) {
if (message && message != "") {
this.socket.emit("chat_message", message);
}
this.chatBox = "";
}
}
HTML
<ion-navbar *navbar>
<ion-title>
Chat
</ion-title>
</ion-navbar>
<ion-content class="home">
<ion-list>
<ion-item *ngFor="let message of messages">{{message}}</ion-item>
</ion-list>
</ion-content>
<ion-footer-bar>
<ion-input>
<input type="text" [(ngModel)]="chatBox" placeholder="Message..." />
<button (click)="send(chatBox)">Send</button>
</ion-input>
</ion-footer-bar>
index.html
<script src="/socket.io/socket.io.js"></script>
Server
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
public class Server {
public static void main(String[] args) {
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(3700);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(new ConnectListener() {
#Override
public void onConnect(SocketIOClient client) {
System.out.println("onConnected");
client.sendEvent("message", new Message("", "Welcome to the chat!"));
}
});
server.addDisconnectListener(new DisconnectListener() {
#Override
public void onDisconnect(SocketIOClient client) {
System.out.println("onDisconnected");
}
});
server.addEventListener("send", Message.class, new DataListener<Message>() {
#Override
public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
System.out.println("onSend: " + data.toString());
server.getBroadcastOperations().sendEvent("message", data);
}
});
System.out.println("Starting server...");
server.start();
System.out.println("Server started");
}
}
UPDATE
I add the following to index.html, and I don't get any errors any more:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
But it just hangs. And in Firebug, I can see that the following request is just hanging:
GET http://localhost:3700/
The following is printed in the server console:
onConnected
When the server is not running the following request times out as expected, but when the server is running, the request does return, but with a null response:
GET http://localhost:3700/socket.io/?EIO=3&transport=...LRQn9sx&sid=53081e79-81f3-4fc0-8fb7-17c8673938ca
200 OK
27ms
So it suggests that my server code or the communication between client and server is wrong I think.
Any ideas?
In your Angular app you're listening for and emitting chat_message.
In your Java server you're listening for send and emitting message.
This doesn't add up, does it?

How to get location based tweets using Spring social with Twitter Streaming API?

I need to live feed the tweets based on geolocation. By Twitter API documentation I understand we can search based on geolocaion.
But is it possible to stream based on geolocaion? and i use spring social twitter for API integration.
List<StreamListener> listeners = new ArrayList<StreamListener>();
StreamListener streamListener = new StreamListener() {
#Override
public void onWarning(StreamWarningEvent warningEvent) {}
#Override
public void onTweet(Tweet tweet) {}
#Override
public void onLimit(int numberOfLimitedTweets) {}
#Override
public void onDelete(StreamDeleteEvent deleteEvent) {}
};
listeners.add(streamListener);
//to-do geolocation based stream filter
twitter.streamingOperations().filter("tesla", listeners);
Thread.sleep(10000);
And I see Twitter streaming API also have a location parameter for request. But how do i implement it with Spring Social Twitter.
Thanks
I have been trying this and finally got the streaming tweets working.
I proceeded with this tutorial - https://spring.io/guides/gs/accessing-twitter.
visiting http://localhost:8080/stream/10_000 will stream tweets from San Francisco region(hardcoded as of now) for 10 secs in the console and display those tweets in webpage after 10 sec.
In the Controller Class add a #RequestMapping method something like this:
HelloController.java
#RequestMapping("/stream/{time}")
public String streamTweet(#PathVariable int time, Model model) throws InterruptedException{
if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
return "redirect:/connect/twitter";
}
Model returnedmodel = streamService.streamApi(model, time);
model = returnedmodel;
return "stream";
}
StreamService.java
#Service
public class StreamService {
private final Logger log = LoggerFactory.getLogger(StreamService.class);
#Autowired
private Twitter twitter;
public Model streamApi(Model model, int time) throws InterruptedException{
List<Tweet> tweets = new ArrayList<>();
List<StreamListener> listeners = new ArrayList<StreamListener>();
StreamListener streamListener = new StreamListener() {
#Override
public void onWarning(StreamWarningEvent warningEvent) {
// TODO Auto-generated method stub
}
#Override
public void onTweet(Tweet tweet) {
System.out.println(tweet.getUser().getName() + " : " + tweet.getText());
log.info("User '{}', Tweeted : {}", tweet.getUser().getName() , tweet.getText());
tweets.add(tweet);
model.addAttribute("tweets", tweets);
}
#Override
public void onLimit(int numberOfLimitedTweets) {
// TODO Auto-generated method stub
}
#Override
public void onDelete(StreamDeleteEvent deleteEvent) {
// TODO Auto-generated method stub
}
};
listeners.add(streamListener);
//This sets the GeoCode (-122.75,36.8,-121.75,37.8) of San Francisco(South-West and North-East) region as given in below twitter docs
//https://dev.twitter.com/streaming/overview/request-parameters#locations
Float west=-122.75f;
Float south=36.8f;
Float east=-121.75f;
Float north = 37.8f;
FilterStreamParameters filterStreamParameters = new FilterStreamParameters();
filterStreamParameters.addLocation(west, south, east, north);
Stream userStream = twitter.streamingOperations().filter(filterStreamParameters, listeners);
Thread.sleep(time);
userStream.close();
return model;
}
}
stream.html
<html>
<head>
<title>Hello Twitter Stream</title>
</head>
<body>
<h4>The Twitter Stream:</h4>`enter code here`
<ul>
<li th:each="tweet:${tweets}"
th:text="${tweet.text} + ' tweeted by - ' + ${tweet.user.name}
+ ' from ' + ${tweet.user.location}
+ ' # ' + ${tweet.createdAt}">
Tweet
</li>
</ul>
</body>
</html>
PS: I know you don't wanna do something like this (i.e. show tweets after waiting for X secs, I just did this to make this working)
Btw, if you have any ideas how can I use this stream to display tweets realtime, (with or without using websockets) please share. Thanks.

TimeoutException on telegram java client

i used the java telegram api to communicate with telegram core api in windows intellij idea
https://github.com/ex3ndr/telegram-api
But the app is facing Timeout error in line TLConfig config = api.doRpcCall(new TLRequestHelpGetConfig());Full source code:
AppInfo appinfo=new AppInfo(45687, "Myapp", "154", "587","en");
TLRequestAuthCheckPhone checkRequest = new TLRequestAuthCheckPhone("96521452365");
MyApiStorage state=new MyApiStorage();
TelegramApi api = new TelegramApi(state, appinfo, new ApiCallback()
{
public void onApiDies(TelegramApi api) {
// When auth key or user authorization dies
}
#Override
public void onUpdatesInvalidated(TelegramApi api) {
System.out.print("############################### onUpdatesInvalidated");
// When api engine expects that update sequence might be broken
}
#Override
public void onAuthCancelled(TelegramApi ta) {
System.out.print("############################### onAuthCancelled");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void onUpdate(TLAbsUpdates updates) {
System.out.print("############################### onUpdate");
System.out.println("user Id ::::"+((TLUpdateShortMessage) updates).getFromId());
}
});
api.switchToDc(1);
TLConfig config = api.doRpcCall(new TLRequestHelpGetConfig());
System.out.print("############################### config" + config.getTestMode());
state.updateSettings(config);
api.doRpcCall(checkRequest, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() {
System.out.print("############################### onConfirmed");
}
public void onResult(TLCheckedPhone result) {
boolean invited = result.getPhoneInvited();
boolean registered = result.getPhoneRegistered();
System.out.print("############################### onResult" + registered);
// TODO process response further
}
public void onError(int errorCode, String message) {
System.out.print("############################### onError" + message);
}
});
can someone help me
Your timeout might happen for several reasons:
1. You are using
api.doRpcCall(new TLRequestHelpGetConfig());
In the TelegramApi class this translates into
return this.doRpcCall(method, timeout, 0);
0 there stands for DC. If your DC is different you will timeout
2. There were suggestions in other places to use doRpcCallSide instead and it worked for some and not for others. The reason is it translates into
return this.doRpcCall(method, 15000, this.primaryDc, true);
where true stands authRequired.
3. If you want to do this without authorization then use api.doRpcCallNonAuth

GWT AutoSuggest In JSP

I would like to add a GWT autosuggest textbox in JSP.
Could someone provide some insight into this?
Thanks
Typically GWT is considered a web application framework which is different to a widget framework. Personally I would consider GWT too heavy to just add an autosuggest to a simple web page and instead use something like jQuery autocomplete.
Having said that, there's nothing magical about running GWT code. Follow GWT standard module layout and just set up your JSP-page as a GWT host page where you alter the paths to be absolute to your compiled module.
Here an example of how I was able to get a suggest box to work. I make an RPC call to the database while the user is typing.
I agree that you could do something similar in jQuery but why would you when GWT has the widget available?
Hope this helps!
vendorSuggestBox = new SuggestBox(new SuggestionOracle()); //client package
public class SuggestionOracle extends SuggestOracle { //shared package
public boolean isDisplayStringHTML() {
return true;
}
#SuppressWarnings("unchecked")
public void requestSuggestions(Request request, Callback callback) {
ItemMovementRemoteServiceAsync service=GWT.create(ItemMovementRemoteService.class);
service.getVendors(request, new SuggestionCallback(request,callback));
}
#SuppressWarnings("unchecked")
class SuggestionCallback implements AsyncCallback {
private SuggestOracle.Request req;
private SuggestOracle.Callback callback;
public SuggestionCallback(SuggestOracle.Request _req, SuggestOracle.Callback _callback) {
req=_req;
callback=_callback;
}
public void onFailure(Throwable caught) {
callback.onSuggestionsReady(req, new SuggestOracle.Response());
}
public void onSuccess(Object result) {
callback.onSuggestionsReady(req, (SuggestOracle.Response) result);
}
}
public SuggestOracle.Response getVendors(Request req) { //server package
Connection db=null;
PreparedStatement ps=null;
ResultSet rs=null;
SuggestOracle.Response resp = new SuggestOracle.Response();
List<Suggestion> suggestions=new ArrayList<Suggestion>();
int count=0;
try {
db=Database.open("ACM0");
ps=db.prepareStatement(
" SELECT VE_CD,upper(VE_NAME) VE_NAME" +
" FROM AP.VE_WEB " +
" WHERE (VE_NAME NOT LIKE 'AC Moore%') " +
" AND (lower(VE_NAME) LIKE ? OR VE_CD LIKE ?)" +
" ORDER BY VE_NAME");
ps.setString(1, "%"+req.getQuery().toLowerCase()+"%");
ps.setString(2, "%"+req.getQuery().toLowerCase()+"%");
rs=ps.executeQuery();
while(rs.next() && count < 25) {
suggestions.add(new ASuggestion(rs.getString("VE_NAME").trim()+"-"+rs.getString("VE_CD").trim()));
count++;
}
resp.setSuggestions(suggestions);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
Database.close(db);
}
return resp;
}
public class ASuggestion implements IsSerializable, Suggestion { //shared package model object
private String s;
public ASuggestion(){}
public ASuggestion(String s) {
this.s=s;
}
public String getDisplayString() {
return s;
}
public String getReplacementString() {
return s;
}

Categories