Redis Database Implementation with Java - java
Good Day,
I have a project to do where I have to create a database with Redis bit arrays data type and write a Java code to access the database with a GUI drop down menu. I was able to implement the code with sorted set commands but the specification I was given was with bit arrays data type and commands. From my understanding bit arrays operate on strings. Please how would I go about this? Kindly find attached my project below and images of the gui.
/*
* 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.
*/
//MAIN PROJECT
package cen414dat;
import java.util.HashMap;
import java.util.Map;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;
/**
*
* #author ariel
*/
public class CEN414Dat {
static HashMap<Double, String> redisData = new HashMap<Double, String>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Jedis jedis = new Jedis("localhost");
Info igr= new Info();
if (jedis.zcard("igr") == null || jedis.zcard("igr") == 0) {
jedis.zadd("igr", (Map) Info.map);}
for(Tuple t: jedis.zrangeByScoreWithScores("igr", 0, 100)){
System.out.println(t.getScore());
redisData.put(t.getScore(),t.getElement());
}
ArrayList<String> states = new ArrayList<String>();
for (Map.Entry m : redisData.entrySet()) {
states.add((String)m.getValue());
}
String[] statesArray = new String[states.size()];
states.toArray(statesArray);
JComboBox<String> stateList = new JComboBox<>(statesArray);
stateList.addItemListener(new Handler());
// stateList.addItemListener(null);
// add to the parent container (e.g. a JFrame):
JFrame jframe = new JFrame();
JLabel item1 = new JLabel("IGR STATISTICS FOR H1 2020");
item1.setToolTipText("Done by AJ");
jframe.add(item1);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setLayout(new FlowLayout());
jframe.setSize(275,180);
jframe.setVisible(true);
jframe.add(stateList);
// get the selected item:
// String selectedBook = (String) stateList.getSelectedItem();
// check whether the server is running or not
System.out.println("Server is running: " + jedis.ping());
//getting the percentage for each state
//
// storing the data into redis database
System.out.println(jedis.zrange("igr", 0, 100));
for (Map.Entry m : Info.map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
//jedis.zadd("outofschool", M)
}
}
private static class Handler implements ItemListener{
//
// #Override
// public void actionPerformed(ActionEvent e) {
// JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
// }
#Override
public void itemStateChanged(ItemEvent e) {
for (Map.Entry m : redisData.entrySet()) {
if(e.getItem().toString() == m.getValue()&& e.getStateChange() == 1){
JOptionPane.showMessageDialog(null, m.getKey() , "Value in billions", 1);
System.out.println(m.getKey());
break;
}
}
}
}
}
/*
* 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.
*/
package cen414dat;
import static com.sun.org.apache.xalan.internal.lib.ExsltDynamic.map;
import java.util.HashMap;
/**
*
* #author ariel
*/
//Info project
public class Info {
public static HashMap<Double, String> map = new HashMap<Double, String>();
public Info(){
// IGR statistics in each state
map.put(4.27,"Q1 Abia");
map.put(1.92,"Q2 Abia");
map.put(1.63,"Q1 Adamawa");
map.put(2.12,"Q2 Adamawa");
map.put(12.00,"Q1 Akwa-Ibom");
map.put(4.26,"Q2 Akwa-Ibom");
map.put(4.53,"Q1 Anambra");
map.put(5.01,"Q2 Anambra");
map.put(4.39,"Q1 Bauchi");
map.put(1.37,"Q2 Bauchi");
map.put(2.88,"Q1 Bayelsa");
map.put(2.51,"Q2 Bayelsa");
map.put(3.62,"Q1 Benue");
map.put(1.73,"Q2 Benue");
map.put(3.59,"Q1 Borno");
map.put(1.79,"Q2 Borno");
map.put(3.99,"Q1 CrossRiver");
map.put(4.06,"Q2 CrossRiver");
map.put(19.3,"Q1 Delta");
map.put(11.5,"Q2 Delta");
map.put(4.65,"Q1 Ebonyi");
map.put(1.69,"Q2 Ebonyi");
map.put(9.51,"Q1 Edo");
map.put(4.50,"Q2 Edo");
map.put(1.65,"Q1 Ekiti");
map.put(1.55,"Q2 Ekiti");
map.put(5.95,"Q1 Enugu");
map.put(6.31,"Q2 Enugu");
map.put(20.7,"Q1 FCT");
map.put(14.5,"Q2 FCT");
map.put(11.1,"Q1 Gombe");
map.put(2.68,"Q2 Gombe");
map.put(3.08,"Q1 Imo");
map.put(4.65,"Q2 Imo");
map.put(1.91,"Q1 Jigawa");
map.put(1.10,"Q2 Jigawa");
map.put(10.2,"Q1 Kaduna");
map.put(4.36,"Q2 Kaduna");
map.put(7.85,"Q1 Kano");
map.put(9.66,"Q2 Kano");
map.put(2.10,"Q1 Katsina");
map.put(3.44,"Q2 Katsina");
map.put(2.21,"Q1 Kebbi");
map.put(2.18,"Q2 Kebbi");
map.put(5.42,"Q1 Kogi");
map.put(2.01,"Q2 Kogi");
map.put(7.22,"Q1 Kwara");
map.put(2.14,"Q2 Kwara");
map.put(114.00,"Q1 Lagos");
map.put(90.5,"Q2 Lagos");
map.put(3.03,"Q1 Nasawara");
map.put(2.87,"Q2 Nasawara");
map.put(1.90,"Q1 Niger");
map.put(2.12,"Q2 Niger");
map.put(14.6,"Q1 Ogun");
map.put(9.07,"Q2 Ogun");
map.put(8.16,"Q1 Ondo");
map.put(5.42,"Q2 Ondo ");
map.put(7.02,"Q1 Osun");
map.put(1.94,"Q2 Osun");
map.put(7.35,"Q1 Oyo");
map.put(10.4,"Q2 Oyo");
map.put(7.20,"Q1 Plateau");
map.put(2.20,"Q2 Plateau");
map.put(36.6,"Q1 Rivers");
map.put(27.9,"Q2 Rivers");
map.put(1.58,"Q1 Sokoto");
map.put(3.02,"Q2 Sokoto");
map.put(2.35,"Q1 Taraba");
map.put(1.71,"Q2 Taraba");
map.put(1.96,"Q1 Yobe");
map.put(1.96,"Q2 Yobe");
map.put(3.57,"Q1 Zamfara");
map.put(3.52,"Q2 Zamfara");
}
}
Image of the GUI
Related
How do you re-display a JTree node?
I am using Java Swing v2 by Robinson & Vorobiev as a framework to understand JTree's. I have redone the source code from [https://www.manning.com/books/swing-second-edition][1] Chapter17/4 to include better encapsulating and information hiding. The rename EditorListener (CellEditorListener) had a bug in that java.io.File.rename() did not work but java.nio.Files.move() does. I then included checks for an existing directory and for a failure to move. The issue is that in these two failures the only thing needed is to update the GUI so that the original value of the node is displayed. The node data does not change and does not need to be updated. The display area update I know how to do. But I do not know how to update only the displayed node. The only thing that seems to work is to replace the tree node with a new version of itself. Code is below. Any help will be greatly appreciated. /** * Copyright 1999-2002 Matthew Robinson and Pavel Vorobiev. * All Rights Reserved. * * =================================================== * This program contains code from the book "Swing" * 2nd Edition by Matthew Robinson and Pavel Vorobiev * http://www.spindoczine.com/sbe * =================================================== * * The above paragraph must be included in full, unmodified * and completely intact in the beginning of any source code * file that references, copies or uses (in any way, shape * or form) code contained in this file. */ /* Source Code: https://www.manning.com/books/swing-second-edition Chapter17/4 */ package ch17.v4; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import javax.swing.JTextField; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.JOptionPane; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; /** * * #author Java Swing vrs. 2 */ public class EditorListener implements CellEditorListener { protected Tree m_tree; protected DefaultTreeCellEditor m_editor; protected DefaultTreeModel m_model; protected JTextField m_display; public EditorListener( DefaultTreeCellEditor m_editor , Tree m_tree , DefaultTreeModel m_model , JTextField m_display) { this.m_editor = m_editor; this.m_tree = m_tree; this.m_model = m_model; this.m_display = m_display; } // EditorListener() #Override public void editingStopped(ChangeEvent e) { if (m_tree.m_editingNode != null) { String newName = m_editor.getCellEditorValue().toString(); File dir = m_tree.m_editingNode.getFile(); File newDir = new File(dir.getParentFile(), newName); m_tree.m_editingNode = null; // moved /******************************** New Code ********************************/ if(newDir.exists()) { int value = JOptionPane.showConfirmDialog( null // parent , "Do you wnat to overwrite>" // message , newName // title , JOptionPane.YES_NO_OPTION // optionType , JOptionPane.WARNING_MESSAGE); // messageType if (value == JOptionPane.NO_OPTION) { update(dir); return; } } try { Path move = Files.move( dir.toPath() // from , newDir.toPath() // to , StandardCopyOption.REPLACE_EXISTING); } catch (IOException exception) { JOptionPane.showConfirmDialog( null // parent , "Unable to rename" // message , newName // title , JOptionPane.OK_OPTION // optionType , JOptionPane.ERROR_MESSAGE); // messageType System.out.println( "[ERROR] Unable to rename " + dir.toString() + " " + exception.getMessage()); update(dir); return; } /**************************************************************************/ // dir.renameTo(newDir); // Update tree update(newDir); } } private void update( File dir) { // correctly displays node TreePath path = m_tree.getSelectionPath(); DefaultMutableTreeNode node = Tree.getTreeNode(path); IconData idata = new IconData( DirTree.ICON_FOLDER , DirTree.ICON_EXPANDEDFOLDER , new FileNode(dir)); node.setUserObject(idata); m_model.nodeStructureChanged(node); m_display.setText(dir.getAbsolutePath()); } // void update( File dir) #Override public void editingCanceled(ChangeEvent e) { m_tree.m_editingNode = null; } private void restoreName() { } // void restoreName() } // class EditorListener implements CellEditorListener
sarxos webcam-capture-live-streaming example error: package us.sosia.video.stream.agent.ui does not exist
I want to make a webcam capture software and a stream software using sarxos's webcam library. Wanting to understand the examples first i don't know what to change or add in order to go past this error at import us.sosia. package us.sosia.video.stream.agent.ui does not exist package us.sosia.video.stream.handler Maybe i have to make a Marvin project and change the pow.xml file but i don't know how to do this and still add my sarxos library to the Marvin project using NetBeans. first class is StreamServer: package us.sosia.video.stream.agent; import java.awt.Dimension; import java.net.InetSocketAddress; import com.github.sarxos.webcam.Webcam; public class StreamServer { /** * #author kerr * #param args */ public static void main(String[] args) { Webcam.setAutoOpenMode(true); Webcam webcam = Webcam.getDefault(); Dimension dimension = new Dimension(320, 240); webcam.setViewSize(dimension); StreamServerAgent serverAgent = new StreamServerAgent(webcam, dimension); serverAgent.start(new InetSocketAddress("localhost", 20000)); } } Second class is StreamClient: package us.sosia.video.stream.agent; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.net.InetSocketAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import us.sosia.video.stream.agent.ui.SingleVideoDisplayWindow; import us.sosia.video.stream.handler.StreamFrameListener; public class StreamClient { /** * #author kerr * */ private final static Dimension dimension = new Dimension(320,240); private final static SingleVideoDisplayWindow displayWindow = new SingleVideoDisplayWindow("Stream example",dimension); protected final static Logger logger = LoggerFactory.getLogger(StreamClient.class); public static void main(String[] args) { //setup the videoWindow displayWindow.setVisible(true); //setup the connection logger.info("setup dimension :{}",dimension); StreamClientAgent clientAgent = new StreamClientAgent(new StreamFrameListenerIMPL(),dimension); clientAgent.connect(new InetSocketAddress("localhost", 20000)); } protected static class StreamFrameListenerIMPL implements StreamFrameListener{ private volatile long count = 0; #Override public void onFrameReceived(BufferedImage image) { logger.info("frame received :{}",count++); displayWindow.updateImage(image); } } } I need a way to go past this error. Thanks in advance.
your first 2 lines in both files are: package us.sosia.video.stream.agent; This means that these files should be in the following path "/us/sosia/video/stream/agent/" Remove this line from both files.
The file "/Users/username/Documents/workspace/LifeExp/bin/data/LifeExpectancyWorldBank.csv" is missing or inaccessible
I'm looking into UC San Diego's OOP course on coursera. I have to take a CVS file, then process it and parse the date into a hashmap for the second assignment they had given. But when I try to load the CSV file it seems that Java can't get an access to it. package app; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.providers.Google.GoogleMapProvider; import de.fhpotsdam.unfolding.utils.MapUtils; import processing.core.PApplet; public class LifeExpectancy extends PApplet { //properties UnfoldingMap map; GoogleMapProvider provider; File csvFile; //setup method //it only runs once, so write your code accordingly public void setup() { csvFile = new File("/data/LifeExpectancyWorldBank.csv"); try { loadLifeExpectancyfromCSV(csvFile.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } size(800, 600, OPENGL); provider = new GoogleMapProvider(); map = new UnfoldingMap(this, 50, 50, 700, 500, provider); MapUtils.createDefaultEventDispatcher(this, map); } //draw method //it is dynamic, that means it runs through the program's runtime //so write your code accordingly public void draw() { map.draw(); } //methods /** * Loads a CSV file, parses it and returns the parsed data accordingly * #param fileName name of the file that will be loaded * #return parsed data that comes from the file */ private Map<String, Float> loadLifeExpectancyfromCSV(String fileName) { Map<String, Float> lifeExpMap = new HashMap<String, Float>(); String[] rows = loadStrings(fileName); for (String row : rows) { String[] columns = row.split(","); float value = Float.parseFloat(columns[5]); lifeExpMap.put(columns[4], value); } return lifeExpMap; } } When I run this code this happens: The file "/data/LifeExpectancyWorldBank.csv" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable. Exception in thread "Animation Thread" java.lang.NullPointerException at app.LifeExpectancy.loadLifeExpectancyfromCSV(LifeExpectancy.java:59) at app.LifeExpectancy.setup(LifeExpectancy.java:27) at processing.core.PApplet.handleDraw(PApplet.java:2361) at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:240) at processing.core.PApplet.run(PApplet.java:2256) at java.lang.Thread.run(Thread.java:745 What am I missing?
Jahmm's KmeansLearner
I'm new with the Jahmm package, also I'm new with Java. I'm having an error in KMeansLearner that says Incompatible Types List<ObservationVector> cannot be converted to List<? extends Observation Vector> What does this mean? I have only observation vectors until now, and I declared it on headers. Can please anyone can tell how do I fix this? And if I want to use a <ObservationReal>, how does it affects the code? Here is my code: package jahmm; import be.ac.ulg.montefiore.run.jahmm.*; import be.ac.ulg.montefiore.run.jahmm.ForwardBackwardCalculator; import be.ac.ulg.montefiore.run.jahmm.Hmm; import be.ac.ulg.montefiore.run.jahmm.KMeansCalculator; import be.ac.ulg.montefiore.run.jahmm.ObservationVector; import be.ac.ulg.montefiore.run.jahmm.ObservationVector; import be.ac.ulg.montefiore.run.jahmm.OpdfDiscrete; import be.ac.ulg.montefiore.run.jahmm.OpdfMultiGaussian; import be.ac.ulg.montefiore.run.jahmm.ViterbiCalculator; import be.ac.ulg.montefiore.run.jahmm.draw.GenericHmmDrawerDot; import be.ac.ulg.montefiore.run.jahmm.io.ObservationReader; import be.ac.ulg.montefiore.run.jahmm.io.ObservationSequencesReader; import be.ac.ulg.montefiore.run.jahmm.io.ObservationVectorReader; import be.ac.ulg.montefiore.run.jahmm.learn.KMeansLearner; import be.ac.ulg.montefiore.run.jahmm.learn.BaumWelchLearner; import be.ac.ulg.montefiore.run.jahmm.learn.BaumWelchScaledLearner; import be.ac.ulg.montefiore.run.jahmm.toolbox.MarkovGenerator; import be.ac.ulg.montefiore.run.jahmm.ObservationReal; import be.ac.ulg.montefiore.run.jahmm.OpdfInteger; import java.io.*; import java.lang.*; import java.util.*; /** * * #author */ public class Jahmm { /** * #param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here //Instances instances; Reader reader; int i, j, k; try{ //String filename = argv[0]; String filex="dta_eat.seq"; //filex = "Desktop\R\dt_junto.csv"; String csvFileToRead = filex; reader = new FileReader(filex); List<ObservationVector> sequences = ObservationSequencesReader.readSequence(new ObservationVectorReader(), reader); reader.close(); OpdfMultiGaussianFactory gMix = new OpdfMultiGaussianFactory(3); KMeansLearner<ObservationVector> kml; kml = new KMeansLearner<ObservationVector>(6, gMix, sequences); Hmm<ObservationVector> initHmm = kml.iterate(); //Hmm<ObservationVector> fittedHmm = kml.learn(); //Hmm<ObservationVector> initHmm = kml.iterate(); } catch(Exception e){ e.printStackTrace(); } } } I'll really would appreciate your help.
you get List of Lists: Reader reader = new FileReader("vectors.seq"); List<List<ObservationVector>> v = ObservationSequencesReader. readSequences(new ObservationVectorReader(2), reader); reader.close(); See this example.
Simple Web Service adding two numbers
I have created a simple Webservice function as shown below; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ws; import javax.jws.WebService; /** * * #author Joe */ #WebService() public class Add2Int { public int add(int a, int b) { return (a+b); } } and I have created a very simple gui that allows the user to enter 2 numbers and which should output the result however this does not work? I tried it without the gui and it works but when i build the gui it does not work? here is my code for that side of things /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package myjavawsclient; //import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * * #author Joe */ public class Calculator extends JFrame implements FocusListener { JTextField value1 = new JTextField("", 5); JLabel plus = new JLabel("+"); JTextField value2 = new JTextField("",5); JLabel equals = new JLabel("="); JTextField sum = new JTextField("", 5); public Calculator() { super("The Calculator"); setSize(350,90); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); FlowLayout flow = new FlowLayout(FlowLayout.CENTER); setLayout(flow); // add the listners value1.addFocusListener(this); value2.addFocusListener(this); // set up sum field sum.setEditable(true); //add componets add(value1); add(plus); add(value2); add(equals); add(sum); setVisible(true); } public void focusGained(FocusEvent event){ try { // Call Web Service Operation ws.Add2IntService service = new ws.Add2IntService(); ws.Add2Int port = service.getAdd2IntPort(); // TODO initialize WS operation arguments here int result = 0; int result2 = 0; result = Integer.parseInt(value1.getText()); result2 = Integer.parseInt(value2.getText()); int total = port.add(result, result2); sum.setText("" +total); //float plusTotal = Float.parseFloat(value1.getText()) + Float.parseFloat(value2.getText()); } catch (Exception ex) { // TODO handle custom exceptions here //value1.setText("0"); //value2.setText("0"); //sum.setText("0"); } } public void focusLost(FocusEvent event){ focusGained(event); } /** * #param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Calculator frame = new Calculator(); } } I am not getting any errors I am just not getting any result from the 2 numbers, for example 1+1=2 but with my application it allows the user to enter 1 + 1 = ? but where the question mark is nothing gets shown. I was wondering if anyone could solve this problem for me. Oh and I am using NetBeans and GlassFish App server with WSDL Joe
You should declare add as a webmethod. try following: #WebMethod public int add(int a, int b){ return (a+b); }
My Fault! I forgot to start the App Server