I'm writing an application in which data from a text file is saved to the array and late transferred to the widget GWT Highcharts as an array of Number type. I wrote a servlet that writes data from a file into an array, and I'm stuck here. I don't know how to pass the contents of the array to the client part of the application. Is there a quick and easy way to do this?
This code written by me:
DataPointsImpl.java:
package com.pwste.gwt.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pwste.gwt.client.DataPoints;
public class DataPointsImpl extends RemoteServiceServlet implements DataPoints {
private static final long serialVersionUID = 1L;
#Override
public Number[] getDataPoints() throws IOException {
File dataFile = new File("points.txt");
FileReader dataFileReader = new FileReader(dataFile);
BufferedReader dataBufferedReader = new BufferedReader(dataFileReader);
Number[] arrayNumber = new Number[10000];
String dataString = dataBufferedReader.readLine();
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = Integer.parseInt(dataString);
dataString = dataBufferedReader.readLine();
}
dataBufferedReader.close();
return arrayNumber;
}
}
DataPoints.java:
package com.pwste.gwt.client;
import java.io.IOException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("dataPoints")
public interface DataPoints extends RemoteService {
Number[] getDataPoints() throws IOException;
}
DataPointsAsync.java:
package com.pwste.gwt.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface DataPointsAsync {
void getDataPoints(AsyncCallback<Number[]> callback);
}
You have to use the Async-Interface on the client side:
private DataPointsAsync dataPointsService = GWT.create(DataPoints.class);
you can use the service in this way:
dataPointsService.getDataPoints(AsyncCallback<Number[]>(){
#Override
public void onSuccess(Number[] result) {
// result contains the returning values
}
#Override
public void onFailure(Throwable caught) {
Window.alert("panic");
}
});
Related
I'm trying to create objects of the classes I have in the main method, I'm implementing the lazy simpleton pattern, but I keep getting the error cannot find symbol in class. I've checked to see if I've written the import package statements correctly as well.
This is my main class
package control;
import java.io.File;
import java.io.FileNotFoundException;
import model.ApplicationModel;
import java.util.* ;
import model.Shop;
import view.ApplicationViewer;
import model.ApplicationModel;
public class ApplicationControl {
public static void main (String[] args) throws FileNotFoundException{
ApplicationModel apm = new ApplicationModel.getInstance();
}
}
This is my Singleton class ApplicationModel
package model;
// needed for ArrayLists
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ApplicationModel {
private static ApplicationModel instance = null;
private ApplicationModel()
{
}
public static ApplicationModel getInstance (){
if (instance == null){
instance = new ApplicationModel();
}
return instance;
}
private List<Shop> shops = new ArrayList<Shop>();
public List<Shop> getShops(){
return this.shops;
}
public void setShops(List<Shop> shops){
this.shops = shops;
}
public Shop createShop(String csvString){
String[] attributes = csvString.split(",");
Shop shop = new Shop(attributes[0],attributes[1],attributes[2],
attributes[3],attributes[4]);
return shop;
}
public List<Shop> readShops(String shopFileName){
ApplicationModel am = new ApplicationModel();
List<Shop> shopList = new ArrayList<>();
try{
Scanner naughty = new Scanner(new File(shopFileName));
if (naughty.hasNext()) naughty.nextLine();
while(naughty.hasNext()){
shopList.add(am.createShop(naughty.nextLine()));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ApplicationModel.class.getName()).log(Level.SEVERE, null, ex);
}
return shopList;
}
public String printShops(){
String listOfShops ="";
for(Shop shop : shops ){
listOfShops = listOfShops +'\n'+ shop.toString().trim() + '\n';
}
return listOfShops.trim();
}
}
Whenever I type in ApplicationModel in the main class, the import statement error stating that the import has not been used goes away too, I'm not sure what's wrong (I'm using netbeans). Can anyone help?
Remove "new" from your code:
ApplicationModel apm = ApplicationModel.getInstance();
Being static, getInstance() is a class method (not an instance method). This syntax is how you call class methods.
am new to Java. I am trying to decouple the Responder class from the WeatherSystem Class. But I get an error at Public NewResponder in the Responder class (invalid method declaration; return type required), I am really stuck at this point. I have tried changing all the class points at NewResponder and responder but can't rectify it. Could anyone point out why I am getting this issue, please?
(I also have InputReader class but that's not included below).
WeatherSystem Class
import java.util.HashSet;
public class WeatherSystem
{
private InputReader reader;
private NewResponder responder;
public WeatherSystem(NewResponder responder)
{
reader = new InputReader();
this.responder = new Responder();
}
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
HashSet<String> input = reader.getInput();
if(input.contains("exit")) {
finished = true;
}
else {
String response = this.responder.generateResponse(input);
System.out.println(response);
}
}
printGoodbye();
.............................................
Class Responder
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import WeatherSystem.NewResponder
public class Responder implements NewResponder
{
private HashMap<String, String> responseMap;
private ArrayList<String> defaultResponses;
private Random randomGenerator;
public NewResponder()
{
responseMap = new HashMap<>();
defaultResponses = new ArrayList<>();
fillResponseMap();
fillDefaultResponses();
randomGenerator = new Random();
}
public String generateResponse(HashSet<String> words)
{
for (String word : words) {
String response = this.responseMap.get(word);
if(response != null) {
return response;
}
}
return pickDefaultResponse();
....................................................
You really need to check whether you need interface NewResponder inside WeatherSystem. Which you are implementing in Responder class with wrong constructor name.
why can execute my code without any issues and it gives me the correct results.
package com.opennlp.demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "I need a PHP note if";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP") || p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
//System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
System.out.println(child.toString()+"lol");
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses){
//p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : "+nounPhrases);
}
}
below is my second code.. it gives me a blank Array in console.I removed main method from above class and I tried to print the nounPhrases inside another class. it shows a blank array. I think in second code my parserAction method is not executing. How can I do execute that method without a main method in another class ?
my second code
package com.opennlp.demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
//private static String line = "i need a Java book which has JSP also";
private static String line = "I need a PHP note if";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP") || p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
//System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
System.out.println(child.toString()+"lol");
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses){
//p.show();
getNounPhrases(p);
}
}
}
I called the nounPhrases in another class like below. But it shows a blank result. How to fix this ? I need to do this without a main method in this class.
ParserTest pt = new ParserTest();
pt.parserAction();
System.out.println(ParserTest.nounPhrases);
I have a simplified example of a problem I am working on. I am trying to load a document that contains an array of an array of numbers.
{
"_id" : ObjectId("570cf0167640ed9f8bcff8e7"),
"matrix" : [
[
42
]
]
}
In order to create all indexes I call org.mongodb.morphia.Datastore#ensureIndexes(). As I understand, from what is documented, I need to call org.mongodb.morphia.Morphia#map(Class ...) to tell Morphia on which classes to look for #Indexes annotation. Without Morphia#map(...) the app runs fine (and as expected no indexes will be created). If I add Morphia#map(...) I get an Exception.
Exception in thread "main" java.lang.RuntimeException: java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [elementData]
at org.mongodb.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:74)
at org.mongodb.morphia.mapping.Mapper.readMappedField(Mapper.java:772)
at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:230)
at org.mongodb.morphia.mapping.Mapper.fromDBObject(Mapper.java:191)
at org.mongodb.morphia.query.MorphiaIterator.convertItem(MorphiaIterator.java:134)
at org.mongodb.morphia.query.MorphiaIterator.processItem(MorphiaIterator.java:146)
at org.mongodb.morphia.query.MorphiaIterator.next(MorphiaIterator.java:117)
at org.mongodb.morphia.query.QueryImpl.asList(QueryImpl.java:150)
at it.test.Main.fails(Main.java:41)
at it.test.Main.main(Main.java:24)
Caused by: java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [elementData]
at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:168)
at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:160)
at org.bson.types.BasicBSONList.get(BasicBSONList.java:105)
at org.mongodb.morphia.mapping.MappedField.getDbObjectValue(MappedField.java:190)
at org.mongodb.morphia.converters.Converters.fromDBObject(Converters.java:121)
at org.mongodb.morphia.mapping.ValueMapper.fromDBObject(ValueMapper.java:20)
at org.mongodb.morphia.mapping.Mapper.readMappedField(Mapper.java:766)
at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:230)
at org.mongodb.morphia.mapping.EmbeddedMapper.readMapOrCollectionOrEntity(EmbeddedMapper.java:206)
at org.mongodb.morphia.mapping.EmbeddedMapper.readCollection(EmbeddedMapper.java:142)
at org.mongodb.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:45)
... 9 more
Can someone explain why explicitly calling map() breaks Morphia?
The following exmaple reproduces the problem (just add org.mongodb.morphia:morphia:1.1.1 as dependency).
package it.test;
import java.util.List;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.dao.BasicDAO;
import org.mongodb.morphia.query.QueryResults;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import it.test.model.Doc;
public class Main {
private static final String URI = "mongodb://localhost:27017";
private static final String NAME = "test";
private static final MongoClientURI CLIENT_URI = new MongoClientURI(URI + "/" + NAME);
public static void main(String[] args) {
Main main = new Main();
main.works();
main.fails();
}
private void fails() {
try (MongoClient client = new MongoClient(CLIENT_URI)) {
Morphia morphia = new Morphia();
morphia.getMapper().getOptions().setStoreEmpties(true);
morphia.mapPackage("it.test.model");
find(morphia, client, CLIENT_URI.getDatabase());
}
}
private void works() {
try (MongoClient client = new MongoClient(CLIENT_URI)) {
Morphia morphia = new Morphia();
morphia.getMapper().getOptions().setStoreEmpties(true);
// morphia.mapPackage("it.test.model"); // bad call?
find(morphia, client, CLIENT_URI.getDatabase());
}
}
private void find(Morphia morphia, MongoClient client, String dbName) {
Datastore datastore = morphia.createDatastore(client, dbName);
BasicDAO<Doc, ObjectId> dao = new BasicDAO<>(Doc.class, datastore);
QueryResults<Doc> result = dao.find();
List<Doc> rootEntities = result.asList();
System.out.println("Found " + rootEntities.size() + " RootEntity documents.");
}
}
package it.test.model;
import java.util.List;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
#Entity
public class Doc {
#Id
private ObjectId id;
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
private List<List<Integer>> matrix;
public List<List<Integer>> getMatrix() {
return matrix;
}
public void setMatrix(List<List<Integer>> matrix) {
this.matrix = matrix;
}
}
If you look at this test you can see List<List<Integer>> works just fine. Looking at your example, I don't see anything obvious that would lead to the errors you're getting but I can verify at least that List<List<Integer>> works. What version of the Java driver are you using? It should be in the 3.x line at the least.
I am attempting to create a HashMap<Integer, Class>, and am not being successful. Essentially, all I want to do is have the ability to dynamically load the classes into the Map.
My managed Bean looks like this:
package Demo;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
/**
*
* #author kbarnett
*/
#Named(value = "facePalmBean")
#Dependent
public class FacePalmBean {
private HashMap<Integer, Class> chimpanzee;
private NewClass0 NewClass0;
private NewClass1 NewClass1;
private NewClass2 NewClass2;
/**
* Creates a new instance of FacePalmBean
*/
public FacePalmBean() {
chimpanzee = new HashMap<>();
NewClass0 = new NewClass0(0);
NewClass1 = new NewClass1(1);
NewClass2 = new NewClass2(2);
}
public HashMap<Integer, Class> getChimpanzee() {
for (int i = 0; i < 3; i++) {
try {
String tmpstring = "NewClass"+i;
System.out.println(tmpstring);
Class tmpclass = Class.forName(tmpstring);
System.out.println(tmpclass);
chimpanzee.put(i, tmpclass);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FacePalmBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println(chimpanzee.toString());
return chimpanzee;
}
public void setChimpanzee(HashMap<Integer,Class> chimpanzee) {
this.chimpanzee=chimpanzee;
}
}
and the NewClasses look like this:
package Demo;
public class NewClass0 {
Integer MyNumber;
NewClass0(int num){
MyNumber=num;
}
public Integer getMyNumber() {
return MyNumber;
}
}
All of the NewClasses are identical except for the number (i.e. 0, 1, and 2).
In order to load a class with the Class.forName() method, you must specify a fully qualified package name. In this case it must be Demo.NewClass0, for example.