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
Related
I'm trying to fill a combobox with a specific field (name) from a json file.
parser file to extract information from json:
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
public class ReferencesParser {
private final File jsonFile;
public ReferencesParser(File jsonFile) {
this.jsonFile = jsonFile;
}
public Map<ReferencesEnum, Reference> parseReferenceFile() {
Map<ReferencesEnum, Reference> referencesMap = new HashMap<>();
try {
String content = new String(Files.readAllBytes(this.jsonFile.toPath()));
JSONObject json = new JSONObject(content);
for (Object object : (JSONArray) json.get("genes")) {
JSONObject geneObject = (JSONObject) object;
Long id = geneObject.getLong("id");
String name = geneObject.getString("name");
String sequence = geneObject.getString("sequence");
Reference reference = new Reference(id, name, sequence);
referencesMap.put(ReferencesEnum.valueOf(name), reference);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return referencesMap;
}
}
genes.json file containing data to implement:
{
"genes": [
{ "id":"1","name":"gene1", "sequence": "gcattgtgggcgctatattgt" },
{ "id":"2","name":"gene2", "sequence": "gcattgtgggcgctatattcc" },
{ "id":"3","name":"gene3", "sequence": "gcatcgtgggcgctatatcat" }
]
}
and I'm trying to populate a combobox with 'name' value from json using a controller file:
...
#FXML
private ComboBox<String> choosegene;
#FXML
public void initialize(){
try {
populateGene_reference();
// System.out.println(geneFile);
System.out.println(referencesMap);
} catch (IOException e) {
e.printStackTrace();
} catch (CompoundNotFoundException e) {
e.printStackTrace();
}
};
private void populateGene_reference() throws IOException, CompoundNotFoundException {
URL url = getClass().getResource("/genes.json");
if (url != null) {
File geneFile = new File(url.getPath());
// String _Path = url.getPath();
// System.out.println("URL = " + url);
ReferencesParser parser = new ReferencesParser(geneFile);
// System.out.println("genefile = " + geneFile);
Map<ReferencesEnum, Reference> referencesMap = parser.parseReferenceFile();
// Map<ReferencesEnum, Reference> test parser.parseReferenceFile();
System.out.println("refmap = " + referencesMap);
choosegene.getItems().add(String.valueOf(referencesMap));
I have tried different ways to get my gene names but 'system.out.println' give me this:
refmap = {gene2=gene2 gcatcgtgggcgctatatcat}
refmap2 = {}
What did I miss?
Thank you for your help
ok referencesMap was ok but not choosegene, this works for me:
private void populateGene_reference() throws IOException, CompoundNotFoundException {
URL url = getClass().getResource("/main/genes.json");
if (url != null) {
File geneFile = new File(url.getPath());
ReferencesParser parser = new ReferencesParser(geneFile);
Map<ReferencesEnum, Reference> referencesMap = parser.parseReferenceFile();
for (ReferencesEnum key : referencesMap.keySet()) {
choosegene.getItems().add(referencesMap.get(key).getName());
}
Hope it will help those having the same issue!
import org.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author rajshree.some
*/
public class sample {
public static void main(String[] args) {
// JSONArray arrayinputip = new JSONArray();
// arrayinputip.put("10.253.140.116");
// arrayinputip.put("10.253.140.111");
// arrayinputip.put("10.253.140.118");
// arrayinputip.put("10.253.140.110");
// JSONArray arrayinputusername = new JSONArray();
// arrayinputusername.put("10.253.140.116");
// arrayinputusername.put("10.253.140.111");
// arrayinputusername.put("10.253.140.118");
// arrayinputusername.put("10.253.140.110");
// JSONArray arrayinput = new JSONArray();
// arrayinput.put("10.253.140.116");
// arrayinput.put("10.253.140.111");
// arrayinput.put("10.253.140.118");
// arrayinput.put("10.253.140.110");
JSONObject inputJsonObj1 = new JSONObject();
JSONObject inputJsonObj2 = new JSONObject();
JSONObject inputJsonObj3 = new JSONObject();
JSONArray array= new JSONArray();
try {
inputJsonObj1.put("ipaddress","10.253.140.116");
inputJsonObj1.put("username","bwadmin");
inputJsonObj1.put("password","c0mcast!");
inputJsonObj2.put("ipaddress","10.253.140.117");
inputJsonObj2.put("username","bwadmin");
inputJsonObj2.put("password","bwadmin!");
array.put(inputJsonObj1);
array.put(inputJsonObj2);
// inputJsonObj3.put("server",array);
System.out.println(array);
Client client = Client.create();
WebResource webResource = client.
resource("http://10.85.249.29:8080/checkRest/CheckxARC/getVersion");
ClientResponse response = webResource.type("application/json").
post(ClientResponse.class, array.toString());
String output = response.getEntity(String.class);
System.out.println(" op--->" + output);
} catch (Exception e) {
System.out.println(e.getMessage() + " ");
}
}
}
//This is my clinet code for calling a resftful webservice.
//This is my api
#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
String output3[] = new String[100];
try {
JSONArray inputarray = new JSONArray();
inputarray.put(getVersionJson);
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
for(int i=0;i<inputarray.length();i++){
output3[i]=inputarray.getString(inputarray[i]);
}
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output1;
}
//In my client calling a restful webservice I am sending ipaddress,password,username of two service and I am binding them in an array and calling them.
Now in the calling method I need to access each ipaddress,username and password .But i am not being able to access the ipaddress,username and password.Can u please show me some ways to solve it.
I'm trying to parse a redirected page from an HTML page and it works just fine when I'm trying to run it in Java console but some how it fails when I'm trying to run the same code in Android.
Here's the stack:
W: java.lang.IllegalArgumentException: Header name must not be empty
W: at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
W: at org.jsoup.helper.HttpConnection$Base.header(HttpConnection.java:292)
W: at org.jsoup.helper.HttpConnection$Response.processResponseHeaders(HttpConnection.java:828)
W: at org.jsoup.helper.HttpConnection$Response.setupFromConnection(HttpConnection.java:772)
W: at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:569)
W: at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:540)
W: at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:227)
W: at gavi_anna_netanel.com.madomes.ug_login.GradesParser$GradesFetcher.getGradesList(GradesParser.java:48)
W: at gavi_anna_netanel.com.madomes.ug_login.GradesParser$GradesFetcher.doInBackground(GradesParser.java:32)
W: at gavi_anna_netanel.com.madomes.ug_login.GradesParser$GradesFetcher.doInBackground(GradesParser.java:28)
W: at android.os.AsyncTask$2.call(AsyncTask.java:287)
W: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
W: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
W: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
W: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
W: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
W: at java.lang.Thread.run(Thread.java:856)
Here's my code:
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.ByteArrayInputStream;
import java.util.Map;
/**
* Created by Anna on 6/18/2016.
*/
public class GradesParser {
String outputFileName;
public GradesParser(String outputFileName) {
this.outputFileName = outputFileName;
}
private class GradesFetcher extends AsyncTask<String, Void, Document> {
#Override
protected Document doInBackground(String... params) {
return getGradesList(params[0], params[1]);
}
private Document getGradesList(String username, String password) {
try {
//create session (?) and prepare initial cookie
Response resp1 = Jsoup.connect("http://techmvs.technion.ac.il/cics/wmn/wmngrad?ORD=1").followRedirects(true).execute();
String url1 = resp1.url().toString();
Map welcomeCookies = resp1.cookies();
//login for the session
String url2 = url1 + "&s=1";
Response resp2 = Jsoup
.connect(url1 + "&s=1")
.followRedirects(true)
.data("userid", username)
.data("password", password)
.data("function", "signon")
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Referer", "http://ug3.technion.ac.il/Tadpis.html")
.cookies(welcomeCookies)
.method(Method.POST)
.execute();
Map<String, String> coockies = resp2.cookies();
if ((!coockies.containsKey("TechAnamUser")) || (coockies.get("TechAnamUser") != username)) {
return null;
}
Document doc3 = Jsoup.parse(new ByteArrayInputStream(resp2.bodyAsBytes()), "ISO-8859-8", url2);
return doc3;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public JSONObject gradesParse(String username, String password) {
Document gradesList = null;
try {
gradesList = new GradesFetcher().execute(username, password).get();
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (gradesList == null) {
return null;
}
Elements tables = gradesList.getElementsByTag("table");
Elements rows = tables.get(2).select("tr");
Elements cells = rows.get(1).select("td");
JSONObject gradesListObject = new JSONObject();
try {
gradesListObject.put("point num", Float.parseFloat(cells.get(0).text()));
gradesListObject.put("success rate", Integer.parseInt(cells.get(1).text()));
gradesListObject.put("average", Float.parseFloat(cells.get(2).text()));
} catch (Exception e) {
e.printStackTrace();
return null;
}
JSONArray semesters = new JSONArray();
if (tables.size() > 5) {
for (int i = 4; i < tables.size() - 1; i++) {
JSONObject semester = new JSONObject();
rows = tables.get(i).select("tr");
JSONArray courses = new JSONArray();
for (int j = 2; j < rows.size() - 1; j++) {
JSONObject course = new JSONObject();
cells = rows.get(j).select("td");
try {
course.put("grade", Integer.parseInt(cells.get(0).text()));
course.put("points", Float.parseFloat(cells.get(1).text()));
String numberWithName = cells.get(2).text();
numberWithName = numberWithName.replace("\u00a0", " ");
String[] splitted = numberWithName.split(" ");
String name = new StringBuilder(splitted[splitted.length - 2]).reverse().toString();
for (int k = splitted.length - 3; k >= 0; k--) {
name = name + " " + new StringBuilder(splitted[k]).reverse().toString();
}
course.put("number", splitted[splitted.length - 1]);
course.put("name", name);
courses.put(course);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
try {
semester.put("courses", (Object) courses);
Element lastRow = rows.get(rows.size() - 1);
cells = lastRow.select("td");
semester.put("points", Float.parseFloat(cells.get(1).text()));
String averageWithSuccessRate = cells.get(0).text();
averageWithSuccessRate = averageWithSuccessRate.replace("\u00a0", " ");
String[] separeted = averageWithSuccessRate.split(" ");
semester.put("average", Float.parseFloat(separeted[0]));
semester.put("success rate", Integer.parseInt(separeted[2].substring(0, separeted[2].length() - 1)));
semesters.put(semester);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
try {
gradesListObject.put("semesters", (Object) semesters);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return gradesListObject;
}
}
I may have little understanding of the header I need, but I have tried several and couldn't find it. I'd appreciate if someone could help me.
Solution chosen by OP:
Our team decided to manipulate the jsoup files to ignore such header. This worked for us.
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>
I have developed an app in phonegap (html5, JQuery, JS) and I want to develop a plugin to print to a BT printer.
I download printer manufacturer's SDK and I imported the appropriate .jar file to my project with all the methods I will need in my project.
I create the below plugin, following an internet tutorial, in order to call from JS the JAVA methods from printer manufacturers SDK.
JS
var HelloPlugin = {
callNativeFunction: function (success, fail, resultType) {
return cordova.exec(success, fail, "com.tricedesigns.HelloPlugin", "nativeAction", [resultType]);
}
};
JAVA
package com.tricedesigns;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import com.starmicronics.stario.StarIOPort;
import com.starmicronics.stario.StarIOPortException;
import com.starmicronics.stario.StarPrinterStatus;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.util.Log;
public class HelloPlugin extends Plugin {
public static final String NATIVE_ACTION_STRING="nativeAction";
public static final String SUCCESS_PARAMETER="success";
#Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
if (NATIVE_ACTION_STRING.equals(action)) {
this.ctx.runOnUiThread(new Runnable()
{
public void run()
{
String resultType = null;
StarIOPort port = null;
String message = null;
String portName = "bt:";
String portSettings = "mini";
byte[] texttoprint = new byte[]{0x1b, 0x40, 0x1b,0x74,0x0D,(byte) 0x91,(byte) 0x92,(byte) 0x93,(byte) 0x94,(byte) 0x95,(byte) 0x96,(byte) 0x97,(byte) 0x98,(byte) 0x99,0x0A,0x0A,0x0A,0x0A,0x0A};
try
{
port = StarIOPort.getPort(portName, portSettings, 10000);
try
{
Thread.sleep(500);
}
catch(InterruptedException e) {}
}
catch (StarIOPortException e)
{
Builder dialog = new AlertDialog.Builder((Context)ctx);
dialog.setNegativeButton("Ok", null);
AlertDialog alert = dialog.create();
alert.setTitle("Failure");
alert.setMessage("Failed to connect to printer");
alert.show();
}
finally
{
if(port != null)
{
try
{
StarIOPort.releasePort(port);
} catch (StarIOPortException e) {}
}
}
}
});
}
return null;
}
}
Printer command manual say:
GetPort is what you will be using to “open” the port to the printer. Using one of the valid
inputs for portName and portSettings as mentioned previously before this, you can pass your
connection string into the StarIO class so that it will correctly set its private variables.
//The following would be an actual usage of getPort:
StarIOPort port = null;
try
{
port = StarIOPort.getPort(portName, portSettings, 10000);
}
catch (StarIOPortException e)
{
//There was an error opening the port
}
StarIOPort is a part of StarIO and this will allow you to create a “port” handle. The
above example shows the port being created and set to null then being assigned the actual
port hook on the following line that contains getPort.
Always use a try, catch when using getPort. If the port cannot be opened
because of connection problems, your program will crash unless you use a
try, catch like the above example.
Is the above syntax of plugin correct or is there something i missed?
When I run my app always i receive "Failed to connect to printer" even if the printer is on and connected to my device.
try this:
public PluginResult execute(String action, JSONArray data, String callbackId) {
PluginResult result = null;
if (PRINT_ACTION.equals(action))
{
JSONObject printerStatusJSON = new JSONObject();
try {
Boolean prtStatus = false;
String msg ="Failed to connect to printer";
String portName = "";
ArrayList<PortInfo> dvss = PrinterFunctions.getDevices();//BTPortList = StarIOPort.searchPrinter("BT:");
if (Looper.myLooper() == null) {
Looper.prepare();
}
for(PortInfo dvs : dvss) {
Map<String, String> st = PrinterFunctions.CheckStatus(dvs.getPortName(), "mini");//port = StarIOPort.getPort(portName, portSettings, 1000);
if(st.get("status") == "true") {
prtStatus = true;
portName = st.get("portName");
break;
}
msg = st.get("message");
}
if(!portName.isEmpty()) {
PrinterFunctions.PrintSomething(portName, data);//MiniPrinterFunctions.PrintSampleReceipt(String portName, JSONArray data);
}
printerStatusJSON.put("prtStatus", prtStatus);
printerStatusJSON.put("message", msg);
result = new PluginResult(Status.OK, printerStatusJSON);
}
catch (Exception jsonEx) {
Log.e("YourApplicationName", "Got JSON Exception " + jsonEx.getMessage());
jsonEx.printStackTrace();
result = new PluginResult(Status.JSON_EXCEPTION);
}
}
else {
result = new PluginResult(Status.INVALID_ACTION);
Log.e(TAG, "Invalid action : " + action);
}
return result;
}