Handling multiple client in java - sockets

I made simple client server chat program that support multiple client but i have a problem:`
public class Main extends Application {
public Button send;
public TextArea textarea;
public TextArea onlineuser;
public TextField usertext;
public static int maxUser = 100;
public boolean run=true;
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("server.fxml"));
primaryStage.setTitle("Server control ");
primaryStage.setScene(new Scene(root, 749, 494));
primaryStage.show();
}
public static void main(String[] args) throws IOException{
Server sv=new Server(1111);
launch(args);
}
class Server extends Thread {
private ServerSocket sv;
private ThreadServer[] clientconnect = new ThreadServer[maxUser];
public Server(int port) throws IOException {
this.sv = new ServerSocket(port);
start();
}
public void run() {
while (run) {
try {
Socket connect = this.sv.accept();
connectionThread(connect);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void connectionThread(Socket connection) {
for (int a = 0; a < maxUser; a++) {
if (this.clientconnect[a] == null) {
this.clientconnect[a] = new ThreadServer(connection, a);
break;
}
}
}
}
class ThreadServer extends Thread {
final private int userID;
final private Socket threadconnect;
public void run() {
while (run)) {
try {
PrintWriter out = new PrintWriter(threadconnect.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(threadconnect.getInputStream()));
textarea.appendText(in.readLine());
out.println(usertext.getText());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public ThreadServer(Socket connect, int ID) {
this.userID = ID;
this.threadconnect = connect;
}
}
I have client part works fine but i cant call my server class in main because it's not a static but i should use main also launch javafx gui part how can i solve this problem?

Related

Handling CuratorFramework close method properly

I'm receiving a stack trace in log files when testing my ZooKeeperFetcher class. I'm quite sure that the problem lies in the fact
that CuratorFramework client is being closed before the pathChildrenCache instance. Is it possible for pathChildrenCache to detect and
call close() once curatorFramework was closed? I cannot simply add new close() -> {pathChildrenCache.close(); } method to ZooKeeperFetcher.
Simplified code:
public class ZooKeeperFetcher() {
private final CuratorFramework client;
private PathChildrenCache pathChildrenCache;
ZooKeeperFetcher(CuratorFramework client) {
this.client = client;
pathChildrenCache = new PathChildrenCache(client, '/', true);
PathChildrenCacheListener pathListener =
(client, event) -> /* handle event */;
}
/* this option is just not possible for me */
// public void close() {
// pathChildrenCache.close();
// }
}
And the test class:
public class TestZooKeeperFetcher {
private TestingServer zookeeperServer;
private final CuratorFramework client;
private ZooKeeperFetcher fetcher;
#Before
public void beforeEachTest() {
zookeeperServer = new TestingServer(true);
client =
CuratorFrameworkFactory.newClient(
zookeeperServer.getConnectString(), new RetryNTimes(10, 50));
client.start();
fetcher = ZooKeeperFetcher(client);
}
#After
public void afterEachTest() throws Exception {
client.close();
}
#Test
public void justDontThrowExceptionsTest() throws Exception {
}
}

JPA Entity not stored OneToMany relationship

i trie to run the following code.
But the child is not created to the parent Entity 'Erfasser'.
If i comment out the line erfasser.getErfasst().add(neu) everything works fine.
#PostConstruct
public void init() {
Erfasser erfasser = new Erfasser();
erfasser.setEmail("benjamin.koubik#auditweb.de");
erfasser.setPasswort("counting88");
gesamtAnzahl.einfuegenErfasser(erfasser);
Erfasst neu = new Erfasst();
neu.setDatum(new Date());
neu.setJuristische(1);
neu.setNatuerliche(0);
gesamtAnzahl.einfuegen(neu);
erfasser.getErfasst().add(neu);
gesamtAnzahl.update(erfasser);
}
Only the Erfasser itself is stored correctly in the DB.
#Entity
public class Erfasser implements Serializable {
private static final long serialVersionUID = 1L;
public Erfasser() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int erfasser_id;
#Column(length = 50)
#Email(message = "Inkorrekt EMail")
private String email;
#Column(length = 30)
private String passwort;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(referencedColumnName = "erfasser_id", name = "erfasst_id_referenz")
private List<Erfasst> erfasst;
public int getErfasser_id() {
return erfasser_id;
}
public void setErfasser_id(int erfasser_id) {
this.erfasser_id = erfasser_id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswort() {
return passwort;
}
public void setPasswort(String passwort) {
this.passwort = passwort;
}
public List<Erfasst> getErfasst() {
return erfasst;
}
public void setErfasst(List<Erfasst> erfasst) {
this.erfasst = erfasst;
}
}
And here my SessionBeans:
AnzahlErfasstGesamtLocal.java
#Local
public interface AnzahlErfasstGesamtLocal {
public abstract List<Integer> gesamt();
public abstract List<Erfasst> gesamtNatuerlich();
public abstract List<Erfasst> gesamtJuristisch();
public abstract void einfuegenErfasser(Erfasser e);
public abstract void einfuegen(Erfasst e);
public abstract void update(Erfasser e);
public abstract void loeschen(Erfasst e);
}
AnzahlErfasstGesamt.java
#Stateless
#LocalBean
public class AnzahlErfasstGesamt implements AnzahlErfasstGesamtLocal {
#PersistenceContext
private EntityManager em;
public AnzahlErfasstGesamt() {
}
#Override
public List<Integer> gesamt() {
return null;
}
#Override
public List<Erfasst> gesamtNatuerlich() {
try {
TypedQuery<Erfasst> q = em.createQuery(
"SELECT COUNT(e) FROM Erfasst e WHERE e.natuerliche = 1 AND e.juristische = 0; ", Erfasst.class);
List<Erfasst> liste = q.getResultList();
if (!liste.isEmpty()) {
return liste;
} else {
return null;
}
} catch (NoResultException e) {
return null;
}
}
#Override
public List<Erfasst> gesamtJuristisch() {
try {
TypedQuery<Erfasst> q = em.createQuery(
"SELECT COUNT(e) FROM Erfasst e WHERE e.juristische = 1 AND e.natuerliche = 0; ", Erfasst.class);
List<Erfasst> liste = q.getResultList();
if (!liste.isEmpty()) {
return liste;
} else {
return null;
}
} catch (NoResultException e) {
return null;
}
}
#Override
public void einfuegen(Erfasst e) {
em.persist(e);
}
#Override
public void update(Erfasser e) {
em.merge(e);
}
#Override
public void loeschen(Erfasst e) {
em.remove(em.merge(e));
}
#Override
public void einfuegenErfasser(Erfasser e) {
em.persist(e);
}
}
There is nothing wrong with JPA - something is wrong in external code (and certainly with your description of the problem). For example I don't see where the actual erfasst list is created - if nothing happens in einfuegenErfasser (whatever that means), then you will get a NullPointerException while trying to add an element to a null list. Is that what happens?
The problem is the combination of JPA entity setup and the code using it. The JPA entity Erfasser has CascadeType.ALL, therefore the gesamtAnzahl.update(erfasser); updates the child entities erfasst with it. At the same time you do not setup the erfasser reference on the neu instance. You need to do something alog the line neu.setErfasser(erfasser) before gesamtAnzahl.update(erfasser);.
On separated line of concern, using the native German naming drives my head crazy, even though I am more German then English speaker.

mongoTemplate is null. Cannot understand why

I'm trying to parse xml file and save some info in mongodb. I get the file to parse and give it to my #Controller. Here is the code of the POST method of #Controller:
#RequestMapping(value = TracksGeopointsRoutes.TRACKS, method = RequestMethod.POST)
public String tracks(#RequestParam MultipartFile file){
TracksGeopointsDoc tracksGeopointsDoc = new TracksGeopointsDoc();
try {
tracksGeopointsDoc.setFile(tracksGeopointsService.convert(file));
} catch (IOException e) {
e.printStackTrace();
}
mongoTemplate.save(tracksGeopointsDoc);
new MySaxParser(tracksGeopointsDoc.getFile().getAbsolutePath()); // here I give my file to my parser
return "com.ub.geopoints_test.index";
}
And my parser:
#Component
public class MySaxParser extends DefaultHandler{
#Autowired
MongoTemplate mongoTemplate;
private List<DotGeopointsDoc> dotGeopointsDocList;
String xmlFileName;
private String tmpValue;
private DotGeopointsDoc currentDotGeopointsDoc;
private DotGeopointsDoc dotGeopointsDoc;
String bookXmlFileName;
public MySaxParser() {
}
public MySaxParser(String bookXmlFileName) {
this.xmlFileName = bookXmlFileName;
dotGeopointsDocList = new ArrayList<DotGeopointsDoc>();
dotGeopointsDoc = new DotGeopointsDoc();
parseDocument();
}
private void parseDocument() {
// parse
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(xmlFileName, this);
} catch (ParserConfigurationException e) {
System.out.println("ParserConfig error");
} catch (SAXException e) {
System.out.println("SAXException : xml not well formed");
} catch (IOException e) {
System.out.println("IO error");
}
}
#Override
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
if (elementName.equalsIgnoreCase("trkpt")) {
dotGeopointsDoc.setId(new ObjectId());
dotGeopointsDoc.setLat(attributes.getValue("lat"));
dotGeopointsDoc.setLon(attributes.getValue("lon"));
}
}
#Override
public void endElement(String s, String s1, String element) throws SAXException {
if (element.equals("trkpt")) {
dotGeopointsDocList.add(dotGeopointsDoc);
mongoTemplate.save(dotGeopointsDoc); // here I'm getting NullPointerException. My mongoTemplate is null
dotGeopointsDoc = new DotGeopointsDoc();
}
}
#Override
public void characters(char[] ac, int i, int j) throws SAXException {
tmpValue = new String(ac, i, j);
}
}
Really don't understand why my mongoTemplate is null. Cause in my #Controller it is not. Could anyone help me?
Its because Spring doesn't know about your MySaxParser. You should not instentiate by it your self, what you did here in your controller:
new MySaxParser(tracksGeopointsDoc.getFile().getAbsolutePath());
This is how your controller should look like:
#Autowired
private MySaxParser mySaxParser;//this is how you can inject a spring managed object
#RequestMapping(value = TracksGeopointsRoutes.TRACKS, method = RequestMethod.POST)
public String tracks(#RequestParam MultipartFile file) {
TracksGeopointsDoc tracksGeopointsDoc = new TracksGeopointsDoc();
try {
tracksGeopointsDoc.setFile(tracksGeopointsService.convert(file));
} catch (IOException e) {
e.printStackTrace();
}
mongoTemplate.save(tracksGeopointsDoc);
mySaxParser.setUpMySaxParser(tracksGeopointsDoc.getFile().getAbsolutePath());
return "com.ub.geopoints_test.index";
}
and this is how your xml parser should be changed:
#Service//this is more of a service then a component
public class MySaxParser extends DefaultHandler {
#Autowired
private MongoTemplate mongoTemplate;
private List<DotGeopointsDoc> dotGeopointsDocList;
private String xmlFileName;
private String tmpValue;
private DotGeopointsDoc currentDotGeopointsDoc;
private DotGeopointsDoc dotGeopointsDoc;
private String bookXmlFileName;
//you do not need constuctors here just a "setup method ex."
public void setUpMySaxParser(String bookXmlFileName) {
this.xmlFileName = bookXmlFileName;
dotGeopointsDocList = new ArrayList<DotGeopointsDoc>();
dotGeopointsDoc = new DotGeopointsDoc();
parseDocument();
}
private void parseDocument() {
// parse
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(xmlFileName, this);
} catch (ParserConfigurationException e) {
System.out.println("ParserConfig error");
} catch (SAXException e) {
System.out.println("SAXException : xml not well formed");
} catch (IOException e) {
System.out.println("IO error");
}
}
#Override
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
if (elementName.equalsIgnoreCase("trkpt")) {
dotGeopointsDoc.setId(new ObjectId());
dotGeopointsDoc.setLat(attributes.getValue("lat"));
dotGeopointsDoc.setLon(attributes.getValue("lon"));
}
}
#Override
public void endElement(String s, String s1, String element) throws SAXException {
if (element.equals("trkpt")) {
dotGeopointsDocList.add(dotGeopointsDoc);
mongoTemplate.save(dotGeopointsDoc); // here I'm getting NullPointerException. My mongoTemplate is null
dotGeopointsDoc = new DotGeopointsDoc();
}
}
#Override
public void characters(char[] ac, int i, int j) throws SAXException {
tmpValue = new String(ac, i, j);
}
}

Logic issue on dynamic static Asyncallback - GWT

Im trying to test the Performance tip of : https://groups.google.com/forum/#!msg/google-web-toolkit/f9FLCEloW-c/3ZelaqGUGTcJ
I have more than 5 different Callbacks with different result object .
how can i creat a dynamic static class in only one static Class :
public class AsyncCallbacks
{
private static AsyncCallback<?> callback = null;
private AsyncCallbacks(){
}
private AsyncCallback<?> createCallback() {
if(callback == null) {
callback = new AsyncCallback(){
#Override
public void onFailure(Throwable caught)
{
// TODO Auto-generated method stub
}
#Override
public void onSuccess(Object result)
{
// TODO Auto-generated method stub
}
};
}
return callback;
}
}
public class Asyncs implements AsyncCallback<Object> {
private Dto1 dto1 = null;
private Dto2 dto2 = null;
private Object result = null;
#Override
public void onFailure(Throwable caught) {
// failed message
}
#Override
public void onSuccess(Object result) {
this.result = result;
}
public Object getSuccessObject() {
if (result instanceof Dto1) {
dto1 = (Dto1) result;
} else if (result instanceof Dto2) {
dto2 = (Dto2) result;
}
return result;
}
}

How to use same servlet for RPC and upload File in GWT.

i created a web application where i have to use fileUpload.
i have to send the file and their properties to server . For sending a file i used FormPanel and for properties i used RPC .
public void onModuleLoad() {
final FileServiceEndPoint serviceEndPoint = new FileServiceEndPoint();
new AddDocument();
Button b = new Button("addDocument");
b.addClickHandler(new ClickHandler() {
private Map<String, String> docProperty;
public void onClick(ClickEvent event) {
docProperty =getProperties();
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onSuccess(String result) {
System.out.println("he ha" +result);
}
public void onFailure(Throwable caught) {
}
};
serviceEndPoint.uploadAttachement(docProperty, callback);
}
});
RootPanel.get().add(b);
}
this new AddDocument(); contains code for uploading a file (formPanel code)
private FormPanel getFormPanel() {
if (uploadForm == null) {
uploadForm = new FormPanel();
uploadForm.setAction(GWT.getHostPageBaseURL() +"TestUploadFileServlet");
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
uploadForm.setWidget(getFileUpload());
System.out.println(GWT.getHostPageBaseURL() +"TestUploadFileServlet");
uploadForm.addFormHandler(new FormHandler() {
public void onSubmitComplete(FormSubmitCompleteEvent event) {
AddDocument.this.hide(true);
}
public void onSubmit(FormSubmitEvent event) {
}
});
}
return uploadForm;
}
private Button getAddButton() {
if (addButton == null) {
addButton = new Button("ADD");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
uploadForm.submit();
}
});
addButton.setText("Add");
}
Interface is created for Sending property.
EndPoints:
public class FileServiceEndPoint implements FileServiceAsync{
FileServiceAsync service = (FileServiceAsync)GWT.create(FileService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) service;
public FileServiceEndPoint() {
endpoint.setServiceEntryPoint(GWT.getHostPageBaseURL() + “TestUploadFileServlet”);
}
public void uploadAttachement(Map docProperty,
AsyncCallback callback) {
service.uploadAttachement(docProperty, callback);
}
}
On Server:
public class FileUploadImpl extends RemoteServiceServlet implements FileService {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FileUploadImpl.class
.getName());
String a;
protected void service(final HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
a=”5″;
System.out.println(“ServletWorking Fine “);
}
public String uploadAttachement(Map docProperty) {
// TODO Auto-generated method stub
return “Checked”;
}
}
When I debug formPanel.submit : the debugger goes in Server and print ServletWorking Fine(this is perfect)
and when i debug the addProperties button it goes to server and print ServletWorking Fine. but It should not go in service method.
the debugger should go in UploadAttachement.
Plz tell how to pass hashMap using same servlet.