How to creat an Server-Client Application using the DatagramPacket and DatagramSocket classes? - spring-data-graph

As the question say, how may I create a server- client application using DatagramPacket and DatagramSocket ?

See the following solution:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class DFSTree {
public static ArrayList<Integer> listeIDsOrder = new ArrayList<>();
public static void main (String[] args){
Map<Integer, Integer> map = new HashMap<>();
map.put (1, null); //root
map.put (10, 1);
map.put (11, 10);
map.put (12, 10);
map.put (13, 10);
map.put (20, 1);
map.put (21, 20);
map.put (22, 20);
map.put (30, 1);
map.put (31, 30);
getOrder (1, map);
System.out.println (listeIDsOrder);
}
public static void getOrder (int root, Map<Integer, Integer> graph){
LinkedList<Integer> stack = new LinkedList<>(); //use stack for correct order of processing
stack.add(root); //add root
getOrder(graph, stack);
}
public static void getOrder (Map<Integer, Integer> graph, LinkedList<Integer> stack ){
while(!stack.isEmpty()){
int node = stack.pollFirst(); //for bfs order. for dfs order use stack.pollLast();
listeIDsOrder.add(node);
List<Integer> keys = new ArrayList<>(graph.keySet());
Collections.sort(keys);
for(int key : keys){
if(graph.get(key) != null && graph.get(key) == node) {
stack.add(key);
}
}
}
}
}
Output: [1, 10, 20, 30, 11, 12, 13, 21, 22, 31]

Related

Pass data between two tabs in jtabedpane

When i create a new tab with a button and in that tab i have a button to pass the data from the textfield in that tab to the textfield in the first created tab but when i switch i got the data data in the textfield in the first tab, but it doesn't display that data in the textfiled
How cai pass data from selected tab natural to first tab she show it on textfield
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
/**
* #author Nguyen Phuc Thinh
*/
public class Test extends JFrame {
private JPanel contentPane;
private JButton btnNewTab;
private JTabbedPane tabbedPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnNewTab = new JButton("New Tab");
btnNewTab.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newTab();
}
});
btnNewTab.setBounds(175, 10, 85, 21);
contentPane.add(btnNewTab);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 60, 416, 193);
contentPane.add(tabbedPane);
}
private void newTab() {
JPanel[] panel = new JPanel[tabbedPane.getTabCount()+1];
JTextField[] txtValue = new JTextField[tabbedPane.getTabCount()+1];
JButton[] btnSend = new JButton[tabbedPane.getTabCount()+1];
for(int i =0; i < tabbedPane.getTabCount()+1; i++) {
panel[i] = new JPanel();
txtValue[i] = new JTextField(10);
btnSend[i] = new JButton();
btnSend[i].setPreferredSize(new Dimension(100, 25));
btnSend[i].setText("Send tab 1");
if(tabbedPane.getTabCount() ==0) {
btnSend[i].setVisible(false);
}
panel[i].add(txtValue[i]);
panel[i].add(btnSend[i]);
btnSend[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
btnSend[0].setText(txtValue[tabbedPane.getSelectedIndex()].getText());
System.out.println(txtValue[tabbedPane.getSelectedIndex()].getText());
}
});
}
tabbedPane.addTab("Tab"+(tabbedPane.getTabCount()+1), null, panel[tabbedPane.getTabCount()], null);
}
}

Java IndexOutOfBoundsException in Arraylist

Below is the code that I wrote:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
for(int a=0,i=0;list.get(i)!=42;i++){
a=sc.nextInt();
list.add(i,a);
}
for(int i=0;i<list.size();i++){
out.println(list.get(i));
}
}
}
And this is the error im getting:
Execution failed.
java.lang.IndexOutOfBoundsException : Index: 0, Size: 0
Stack Trace:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Uni.main(Uni.java:8)
Can you please help with what to do?
Maybe you wanted to use a while cycle? It's much easier to initialize the list.
Furthermore, your code is checking if list.get(i) is not equal to 42, but you cannot do that because your list at the index 0 is still null.
A solution could be:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0;
while(i!=42) {
list.add(i++,sc.nextInt());
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
EDIT: to stop after the Input is 42:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0
while (true) {
int in = sc.nextInt();
if (in==42) break;
list.add(i++,sc.nextInt())
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}

Ignite dataStreamer is not working

I am exploring Ignite dataStreamer with the following code.
But the output is:
For MessageKey0001, the output all displays data is null.
For MessageKey0003, the output also all displays data is null
For MessageKey0002, the output shows nothing, looks that receiver code is not run
When I change
dataStreamer.addData(i, "data-" + i);
to
IgniteFuture future = dataStreamer.addData(i, "data-" + i);
future.get();
The future.get() doesn't return, looks addData doesn't finish anyway?
I am not sure where the problem is, can someone take a look? Thanks!
package ignite.streamer;
import org.apache.ignite.*;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.stream.StreamReceiver;
import javax.cache.Cache;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
class IgniteDataStreamer_Person implements Serializable {
#QuerySqlField(index = true)
private String name;
#QuerySqlField(index = true)
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class IgniteDataStreamerTest {
public static void main(String[] args) {
String configPath = "D:/Software/apache-ignite-fabric-1.7.0-bin/apache-ignite-fabric-1.7.0-bin/config/default-config.xml";
Ignite ignite = Ignition.start(configPath);
CacheConfiguration<Integer, String> cfg = new CacheConfiguration<Integer, String>();
String cacheName = "stream_cache";
cfg.setName(cacheName);
cfg.setIndexedTypes(Integer.class, IgniteDataStreamer_Person.class);
Cache cache = ignite.getOrCreateCache(cfg);
IgniteDataStreamer<Integer, String> dataStreamer = ignite.dataStreamer(cacheName);
for (int i = 0; i < 3; i++) {
dataStreamer.addData(i, "data-" + i);
}
//null is got from cache
for (int i = 0; i < 3; i++) {
System.out.println(String.format("0001: data is %s ", cache.get(i)));
}
dataStreamer.receiver(new StreamReceiver<Integer, String>() {
public void receive(IgniteCache<Integer, String> cache, Collection<Map.Entry<Integer, String>> entries) throws IgniteException {
//nothing is printed to console
for (Map.Entry<Integer, String> entry : entries) {
System.out.println(String.format("0002: key is: %s, value is: %s", entry.getKey(), entry.getValue()));
}
}
});
//null is got from cache
for (int i = 0; i < 3; i++) {
System.out.println(String.format("0003: data is %s ", cache.get(i)));
}
ignite.close();
}
}
DataStreamer uses batches in order to provide good performance. You should flush data in your case (use flush() method) before block on future.get() method.
Please, see IgniteDataStreamer javadocs for details.

Java : Null Pointer Exception

I have to do a chat client/server project, but i am getting a Null Pointer Exception on pr1.println(msg) on the ChatServer1 class.
Any help would be appreciated.
public class ChatClient1 extends JFrame{
private JPanel contentPane;
private JPanel panel_1 = new JPanel();
private static JTextArea textArea = new JTextArea();
private static JTextField Txt1 = new JTextField();
private JButton DisconnectBtn = new JButton("DISCONNECT");
private static JButton SendTxt = new JButton("SEND");
private JLabel lbl1 = new JLabel("Message to send");
ServerSocket serversocket;
static BufferedReader br1;
static PrintWriter pr1;
Socket socket;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ChatServer1 frame = new ChatServer1();
frame.setVisible(true);
frame.setTitle("CLIENT");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ChatClient1() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 542, 383);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel_1.setBackground(Color.GRAY);
panel_1.setBounds(0, 0, 536, 355);
contentPane.add(panel_1);
panel_1.setLayout(null);
DisconnectBtn.setBounds(29, 220, 183, 33);
panel_1.add(DisconnectBtn);
textArea.setBounds(235, 11, 291, 242);
panel_1.add(textArea);
Txt1.setBounds(29, 303, 387, 41);
panel_1.add(Txt1);
Txt1.setColumns(10);
SendTxt.setBounds(437, 303, 89, 41);
panel_1.add(SendTxt);
lbl1.setBounds(29, 278, 123, 14);
panel_1.add(lbl1);
try {
Socket socket = new Socket("LocalHost" , 5000);
pr1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
br1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
textArea.append("Server: " + br1.readLine() + '\n' );
}
} catch (IOException e) {
}
SendTxt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = Txt1.getText();
pr1.println(msg);
pr1.flush();
textArea.append(msg + '\n');
Txt1.setText("");
}
});
}
}
ChatServer1 class:
public class ChatServer1 extends JFrame{
private JPanel contentPane;
private JPanel panel_1 = new JPanel();
private static JTextArea textArea = new JTextArea();
private static JTextField Txt1 = new JTextField();
private JButton DisconnectBtn = new JButton("DISCONNECT");
private static JButton SendTxt = new JButton("SEND");
private JLabel lbl1 = new JLabel("Message to send");
static BufferedReader br1;
static PrintWriter pr1;
Socket socket;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ChatServer1 frame = new ChatServer1();
frame.setVisible(true);
frame.setTitle("SERVER");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ChatServer1() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 542, 383);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel_1.setBackground(Color.GRAY);
panel_1.setBounds(0, 0, 536, 355);
contentPane.add(panel_1);
panel_1.setLayout(null);
DisconnectBtn.setBounds(29, 220, 183, 33);
panel_1.add(DisconnectBtn);
textArea.setBounds(235, 11, 291, 242);
panel_1.add(textArea);
Txt1.setBounds(29, 303, 387, 41);
panel_1.add(Txt1);
Txt1.setColumns(10);
SendTxt.setBounds(437, 303, 89, 41);
panel_1.add(SendTxt);
lbl1.setBounds(29, 278, 123, 14);
panel_1.add(lbl1);
try {
ServerSocket serversocket = new ServerSocket(5000);
socket = serversocket.accept();
pr1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
br1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
textArea.append("Client: " + br1.readLine() + '\n' );
}
} catch (IOException e) {
}
SendTxt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = Txt1.getText();
pr1.println(msg);
pr1.flush();
textArea.append(msg + '\n');
Txt1.setText("");
}
});
}
}
your problem is with the ChatServer1 code, here you have the following:
ServerSocket serversocket = new ServerSocket(5000);
socket = serversocket.accept();
When you call accept, its waiting and listening for an incoming connection so never actually reaches your instantiation of pr1. Hence pr1 stays as null. Easy to fix simply move the pr1 instantiation above the accept call like this:
pr1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
ServerSocket serversocket = new ServerSocket(5000);
socket = serversocket.accept();
Hope this helps!

How to use prefix queries on fields in Lucene?

I am trying to use a PrefixQuery in Lucene for the purpose of autocomplete. I've made a simple test of what I thought should work, but it doesn't. I am indexing some simple strings and using the KeywordAnalyzer to make sure they are not tokenized, but my searches still do not match anything. How should I index and search a field to get a prefix match?
Here's the unit test I made to test with. Everything passes except the autocomplete and singleTerm methods.
package com.sample.index;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class TestIndexStuff {
public static final String FIELD_AUTOCOMPLETE = "autocomplete";
public static final String FIELD_NORMAL = "normal";
private IndexSearcher searcher;
private PerFieldAnalyzerWrapper analyzer;
#Before
public void init() throws IOException {
RAMDirectory idx = new RAMDirectory();
HashMap<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>();
fieldAnalyzers.put(FIELD_AUTOCOMPLETE, new KeywordAnalyzer());
analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_35), fieldAnalyzers);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
IndexWriter writer = new IndexWriter(idx, config);
addDocs(writer);
writer.close();
searcher = new IndexSearcher(IndexReader.open(idx));
}
private void addDocs(IndexWriter writer) throws IOException {
for (String text : new String[]{"Fred Rogers", "Toni Reed Preckwinkle", "Randy Savage", "Kathryn Janeway", "Madonna", "Fred Savage"}) {
Document doc = new Document();
doc.add(new Field(FIELD_NORMAL, text, Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field(FIELD_AUTOCOMPLETE, text, Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
}
}
#Test
public void prefixParser() throws ParseException {
Query prefixQuery = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Fre*");
assertTrue(prefixQuery instanceof PrefixQuery);
Query normalQuery = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Fred");
assertFalse(normalQuery instanceof PrefixQuery);
}
#Test
public void normal() throws ParseException, IOException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_NORMAL, analyzer).parse("Fred");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(2, topDocs.totalHits);
}
#Test
public void autocomplete() throws IOException, ParseException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Fre*");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(2, topDocs.totalHits);
}
#Test
public void singleTerm() throws ParseException, IOException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Mado*");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(1, topDocs.totalHits);
}
}
edit: adding revised code for those who read this later to show full test after changing thanks to #jpountz. Rather than leave things as mixed case though, I chose to index them as lower case. I also added a unit test to make sure that a term in the middle would not be matched, since this should only match things that start with the search term.
package com.sample.index;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class TestIndexStuff {
public static final String FIELD_AUTOCOMPLETE = "autocomplete";
public static final String FIELD_NORMAL = "normal";
private IndexSearcher searcher;
private PerFieldAnalyzerWrapper analyzer;
#Before
public void init() throws IOException {
RAMDirectory idx = new RAMDirectory();
HashMap<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>();
fieldAnalyzers.put(FIELD_AUTOCOMPLETE, new KeywordAnalyzer());
analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_35), fieldAnalyzers);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
IndexWriter writer = new IndexWriter(idx, config);
addDocs(writer);
writer.close();
searcher = new IndexSearcher(IndexReader.open(idx));
}
private void addDocs(IndexWriter writer) throws IOException {
for (String text : new String[]{"Fred Rogers", "Toni Reed Preckwinkle", "Randy Savage", "Kathryn Janeway", "Madonna", "Fred Savage"}) {
Document doc = new Document();
doc.add(new Field(FIELD_NORMAL, text, Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field(FIELD_AUTOCOMPLETE, text.toLowerCase(), Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
}
}
#Test
public void prefixParser() throws ParseException {
Query prefixQuery = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Fre*");
assertTrue(prefixQuery instanceof PrefixQuery);
Query normalQuery = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Fred");
assertFalse(normalQuery instanceof PrefixQuery);
}
#Test
public void normal() throws ParseException, IOException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_NORMAL, analyzer).parse("Fred");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(2, topDocs.totalHits);
}
#Test
public void autocomplete() throws IOException, ParseException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Fre*");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(2, topDocs.totalHits);
}
#Test
public void beginningOnly() throws ParseException, IOException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("R*");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(1, topDocs.totalHits);
}
#Test
public void singleTerm() throws ParseException, IOException {
Query query = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Mado*");
TopDocs topDocs = searcher.search(query, 10);
assertEquals(1, topDocs.totalHits);
}
}
By default, QueryParser lowercases the terms of special queries (in particular prefix queries). To disable this, see QueryParser.setLowercaseExpandedTerms.
Replace
Query query = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer).parse("Mado*");
with
QueryParser qp = new QueryParser(Version.LUCENE_35, FIELD_AUTOCOMPLETE, analyzer);
qp.setLowercaseExpandedTerms(false);
Query query = qp.parse("Mado*");
to fix your tests.