I'm trying to extract establishments data from GooglePlaces API. It used to work initially, but after making a specific method for extracting the places (instead of in the main method), the program crushes. When debbuged it, it gets stuck in a java method called park (under LockSupport class from java). Reading about it, it says that this happens when there is more than 1 thread and there are sync problems. I'm very new at this and I don't know how to solve this in my code. In my mind, there is only 1 thread in this code, but I'm pretty sure I'm wrong. Please help. It crashes in a "for" commented below. Thanks so much!
package laundry;
import java.util.ArrayList;
import java.util.List;
import se.walkercrou.places.GooglePlaces;
import se.walkercrou.places.Param;
import se.walkercrou.places.Place;
import java.io.FileWriter; //add to import list
import java.io.IOException;
import java.io.Writer;
import static java.lang.Math.sqrt;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.location.Coordinates;
import se.walkercrou.places.exception.GooglePlacesException;
import se.walkercrou.places.exception.RequestDeniedException;
public class Laundry {
public static void main(String[] args) throws IOException {
List<Place> detailedPlaces = new ArrayList<>();
List<double[]> circlesPoint = new ArrayList<>();
double radio = 10;
Coordinates startingPoint = new Coordinates (-38.182476,144.552079,0);//geelong south west corner of the grid
Coordinates finalPoint = new Coordinates(-37.574381,145.415879,0); //north east of melbourne
GooglePlaces cliente = new GooglePlaces("keyof googlplaces");
MyResult result1=exploreGrid(startingPoint,finalPoint, radio, detailedPlaces, circlesPoint,cliente);
writeResultsCircles(result1.getPoints(),"c:\\outputCircles.txt" );
writeResultsPlaces(result1.getPlaces(), "c:\\outputPlaces.txt");
}
private static MyResult exploreGrid(Coordinates SWpoint,Coordinates NEpoint,double rad, List<Place> lugares, List<double[]> points,GooglePlaces client){
int iterationRow=0;
Coordinates workingPoint = new Coordinates(SWpoint.getLatitude(),SWpoint.getLongitude(),(float) 0.0);
List<Place> places = new ArrayList<>();
while (workingPoint.getLatitude()<NEpoint.getLatitude()){
while (workingPoint.getLongitude()<NEpoint.getLongitude()){
try {
places = client.getNearbyPlaces(workingPoint.getLatitude(), workingPoint.getLongitude(), rad*1000,GooglePlaces.MAXIMUM_RESULTS ,Param.name("types").value("laundry"));
if (places.size()==60){//si se llega al tope de resultados de getNearbyPlaces
iterationRow=1;
}
for (Place place : places) {
lugares.add(place.getDetails());//here is where it crashes
}
}catch (GooglePlacesException ex) {
System.out.println(ex.getCause());
}
double[] prePoint = {workingPoint.getLatitude(),workingPoint.getLongitude(),rad};
points.add(prePoint);
workingPoint.setLongitude(workingPoint.getLongitude()+rad*sqrt(3)*0.01134787);
}
iterationRow++;
if (isEven(iterationRow)){
workingPoint.setLongitude(SWpoint.getLongitude());
} else {
workingPoint.setLongitude(SWpoint.getLongitude()+rad*sqrt(3)*0.01134787/2);
}
workingPoint.setLatitude(workingPoint.getLatitude()+rad*3/2*0.00899416);
}
return new MyResult(lugares,points);
}
}
Related
My Task is to read some data from file, split it and then parse it to correct instance of class. So far so good, but I have a problem with the class Education, because every person has different education degree, so I don't know how to check that. The same problem comes with Insurance class, because for every person we have information for different period of time. So that is my problem basicaly.
I don't know how many instances of Education I have to create.
Here are two examples of the data that I have to read and parse:
--1--
"Plamen;Stoichev;Izmirliev;M;16.7.1980;206;Bulgaria;Sofiya;Studentski;1016;Opalchenska;21;;;P; William Gladstoine;15.9.1986;15.6.1993;S;William Gladstoine ;15.9.1993;30.6.1998;3.343;B; William Gladstoine;1.10.1999;1.6.2003;3.045" +
"2016;11;1015.20;2016;10;605.93;2016;9;701.61;2016;7;981.86;2016;4;1042.57;2016;3;919.87;2016;2;720.00;2015;12;969.75;2015;6;641.16;2015;3;811.76;2015;2;757.07;2014;12;1321.31;2014;11;863.39;2014;9;1539.51;2014;7;1159.62;2014;5;1295.59;2014;3;910.59;2014;1;1033.80";
--2--
Violeta;Konstantinova;Orlova;F;23.8. 1982;148;Bulgaria;Sofia;Izgrev;1008;King Boris III;123;5;26;P;William Gladstoine ;15.9.1988;15.6.1995;S;William Gladstoine ;15.9.1995;30.6.2000;4.069
2016;11;1587.70;2016;8;1524.04;2016;6;1273.10;2016;4;1129.08; 2016;2;1469.79;2015;12;927.91;2015;10;1116.83;2015;6;1143.05;2015;4;1348.82;
The SocialInsuranceRecord class has three parameters year, month, tax amount.
The Education class has level of degree, name of school, enrollment date, graduation date, average grade;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import DataObjects.address.Address;
import DataObjects.education.Education;
import DataObjects.insurance.SocialInsuranceRecord;
import DataObjects.personaldetails.Citizen;
import DataObjects.personaldetails.Gender;
public class GetDataFromFile {
private List<Citizen> citizents = new ArrayList<>();
private static final String FILE_PATH = "D:\\data.dat";
public List<Citizen> getCitizens() {
List<Citizen> list = new ArrayList<>();
try {
Scanner scanner = new Scanner(new String(Files.readAllBytes(Paths.get(FILE_PATH))));
while(scanner.hasNext()) {
Citizen citizen = parseCitizent(scanner.nextLine());
list.add(citizen);
}
}catch(Exception ex) {
ex.printStackTrace();
}
return list;
}
public Citizen parseCitizent(String nextLine) {
String[] split = nextLine.split("\\s*;");
Citizen citizen = new Citizen(split[0], split[1], split[2], Gender.valueOf(split[3]), LocalDate.parse(split[4]), Integer.parseInt(split[5]));
Address address = new Address(split[6], split[7], split[8], split[9], split[10], split[11], Integer.parseInt(split[11]), Integer.parseInt(split[12]));
citizen.setAddress(address);
List<Education> educations = new ArrayList<>();
// to do...
citizen.set_educations(educations);
List<SocialInsuranceRecord> socilInsuranceRecords = new ArrayList<>();
// to do...
citizen.set_socialInsuranceRecords(socilInsenter code hereuranceRecords);
return citizen;
}
}
package facerec;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.openimaj.feature.DoubleFVComparison;
import org.openimaj.image.FImage;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.RGBColour;
import org.openimaj.image.processing.face.alignment.RotateScaleAligner;
import org.openimaj.image.processing.face.detection.HaarCascadeDetector;
import org.openimaj.image.processing.face.detection.keypoints.FKEFaceDetector;
import org.openimaj.image.processing.face.detection.keypoints.KEDetectedFace;
import org.openimaj.image.processing.face.recognition.EigenFaceRecogniser;
import org.openimaj.image.processing.face.recognition.FaceRecognitionEngine;
import org.openimaj.image.typography.hershey.HersheyFont;
import org.openimaj.math.geometry.point.Point2d;
import org.openimaj.ml.annotation.Annotated;
import org.openimaj.ml.annotation.AnnotatedObject;
import org.openimaj.ml.annotation.ScoredAnnotation;
import org.openimaj.util.pair.IndependentPair;
import org.openimaj.video.VideoDisplay;
import org.openimaj.video.VideoDisplayListener;
import org.openimaj.video.capture.VideoCapture;
public class NewFaceRegister extends KeyAdapter implements VideoDisplayListener<MBFImage> {
private VideoCapture capture;
private VideoDisplay<MBFImage> videoFrame;
FKEFaceDetector faceDetector = new FKEFaceDetector(new HaarCascadeDetector());
private EigenFaceRecogniser<KEDetectedFace, String> recogniser = EigenFaceRecogniser.create(20, new RotateScaleAligner(), 1, DoubleFVComparison.CORRELATION, 0.9f);
FaceRecognitionEngine<KEDetectedFace, String> engine = FaceRecognitionEngine.create(faceDetector, recogniser);
Annotated<KEDetectedFace, String> faceobj;
private FImage currentFrame;
public NewFaceRegister() throws Exception {
capture = new VideoCapture(940, 720);
//engine = new CLMFaceTracker();
//engine.fpd = 120;
videoFrame = VideoDisplay.createVideoDisplay(capture);
videoFrame.addVideoListener(this);
SwingUtilities.getRoot(videoFrame.getScreen()).addKeyListener(this);
}
#Override
public synchronized void keyPressed(KeyEvent key) {
if (key.getKeyCode() == KeyEvent.VK_SPACE) {
this.videoFrame.togglePause();
} else if (key.getKeyChar() == 'c') {
// if (!this.videoFrame.isPaused())
// this.videoFrame.togglePause();
final String person = JOptionPane.showInputDialog(this.videoFrame.getScreen(), "Name der Person eingeben", "",
JOptionPane.QUESTION_MESSAGE);
final List<KEDetectedFace> faces = detectFaces();
if (faces.size() == 1) {
engine.train(faces.get(0), person);
//TODO Datenbankmethode aufrufen, welches das AnnotatedObject (faceObj) speichert.
} else {
System.out.println("Zu viele/wenige Gesichter im Bild");
}
//this.videoFrame.close();
} else
System.out.println("Wrong key");
}
private List<KEDetectedFace> detectFaces() {
return engine.getDetector().detectFaces(currentFrame);
}
#Override
public void afterUpdate(VideoDisplay<MBFImage> display) {
// do nothing
}
#Override
public synchronized void beforeUpdate(MBFImage frame) {
this.currentFrame = frame.flatten();
/*engine.track(frame);
engine.drawModel(frame, true, true, true, true, true);*/
final List<KEDetectedFace> faces = detectFaces();
for (KEDetectedFace face : faces) {
frame.drawShape(face.getBounds(), RGBColour.RED);
}
if (recogniser != null && recogniser.listPeople().size() >= 1) {
for (KEDetectedFace face : faces) {
List<IndependentPair<KEDetectedFace, ScoredAnnotation<String>>> name = engine.recogniseBest(face.getFacePatch());
if (name.size() > 0) {
final Point2d r = face.getBounds().getTopLeft();
frame.drawText(name.get(0).getSecondObject().toString(), r, HersheyFont.ROMAN_SIMPLEX, 15, RGBColour.GREEN);
}
}
}
}
public static void main(String[] args) throws Exception {
new NewFaceRegister();
}
}
Why do I get an OutOfMemoryError? I tryed it with an other Dedector and there it works?! I also looked in some other Questions for an Answer and i found one Solution and i excactly worked with it, but it also didn't worked.
It's my first time working with Openimaj.
Exception in thread "Thread-4" java.lang.OutOfMemoryError: Java heap space
at no.uib.cipr.matrix.AbstractDenseMatrix.<init>(AbstractDenseMatrix.java:47)
at no.uib.cipr.matrix.DenseMatrix.<init>(DenseMatrix.java:167)
at no.uib.cipr.matrix.SVD.<init>(SVD.java:98)
at no.uib.cipr.matrix.SVD.<init>(SVD.java:75)
at no.uib.cipr.matrix.SVD.factorize(SVD.java:146)
at org.openimaj.math.matrix.ThinSingularValueDecomposition.<init>(ThinSingularValueDecomposition.java:84)
at org.openimaj.math.matrix.ThinSingularValueDecomposition.<init>(ThinSingularValueDecomposition.java:69)
at org.openimaj.math.matrix.algorithm.pca.ThinSvdPrincipalComponentAnalysis.learnBasisNorm(ThinSvdPrincipalComponentAnalysis.java:56)
at org.openimaj.math.matrix.algorithm.pca.PrincipalComponentAnalysis.learnBasis(PrincipalComponentAnalysis.java:183)
at org.openimaj.math.matrix.algorithm.pca.PrincipalComponentAnalysis.learnBasis(PrincipalComponentAnalysis.java:170)
at org.openimaj.ml.pca.FeatureVectorPCA.learnBasis(FeatureVectorPCA.java:113)
at org.openimaj.image.model.EigenImages.train(EigenImages.java:125)
at org.openimaj.image.processing.face.feature.EigenFaceFeature$Extractor.train(EigenFaceFeature.java:167)
at org.openimaj.image.processing.face.recognition.EigenFaceRecogniser.beforeBatchTrain(EigenFaceRecogniser.java:159)
at org.openimaj.image.processing.face.recognition.LazyFaceRecogniser.retrain(LazyFaceRecogniser.java:139)
at org.openimaj.image.processing.face.recognition.LazyFaceRecogniser.annotate(LazyFaceRecogniser.java:153)
at org.openimaj.image.processing.face.recognition.EigenFaceRecogniser.annotate(EigenFaceRecogniser.java:55)
at org.openimaj.image.processing.face.recognition.FaceRecogniser.annotateBest(FaceRecogniser.java:115)
at org.openimaj.image.processing.face.recognition.FaceRecognitionEngine.recogniseBest(FaceRecognitionEngine.java:260)
at facerec.NewFaceRegister.beforeUpdate(NewFaceRegister.java:97)
at facerec.NewFaceRegister.beforeUpdate(NewFaceRegister.java:1)
at org.openimaj.video.VideoDisplay.fireBeforeUpdate(VideoDisplay.java:785)
at org.openimaj.video.VideoDisplay.run(VideoDisplay.java:522)
at java.lang.Thread.run(Unknown Source)
The reason you got failed is because of image processing algorithm used. I'm not sure what openimaj uses, but there are two workarounds possible for this:
Increase heap size, so that your application has more memory available for image processing. See How can I increase the JVM memory?
Decrease image size, so that your application will use less memory for processing.
Based on my own experience with face detection on mobile devices (limited memory as well), 940x720 seems to be more than enough for face detection. Feel free to resize into 640x480 (or similar), results should not be affected.
Remember that you can copy your initial image, resize it with any aspect ratio (i.g. 1.5), detect face on new resized image and return initial image with detected face coordinates multiplied on your aspect ratio.
This is the entire source code for the java file.
package gephifyer;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.gephi.data.attributes.api.AttributeColumn;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeModel;
import org.gephi.graph.api.DirectedGraph;
import org.gephi.graph.api.GraphController;
import org.gephi.graph.api.GraphModel;
import org.gephi.io.exporter.api.ExportController;
import org.gephi.io.importer.api.Container;
import org.gephi.io.importer.api.EdgeDefault;
import org.gephi.io.importer.api.ImportController;
import org.gephi.io.importer.spi.FileImporter;
import org.gephi.io.processor.plugin.DefaultProcessor;
import org.gephi.partition.api.Partition;
import org.gephi.partition.api.PartitionController;
import org.gephi.partition.plugin.NodeColorTransformer;
import org.gephi.preview.api.PreviewController;
import org.gephi.preview.api.PreviewModel;
import org.gephi.preview.api.PreviewProperty;
import org.gephi.preview.types.DependantOriginalColor;
import org.gephi.project.api.ProjectController;
import org.gephi.project.api.Workspace;
import org.gephi.ranking.api.Ranking;
import org.gephi.ranking.api.RankingController;
import org.gephi.ranking.plugin.transformer.AbstractSizeTransformer;
import org.gephi.statistics.plugin.Modularity;
import org.openide.util.Lookup;
import org.gephi.layout.plugin.force.StepDisplacement;
import org.gephi.layout.plugin.force.yifanHu.YifanHu;
import org.gephi.layout.plugin.force.yifanHu.YifanHuLayout;
import org.gephi.layout.plugin.openord.*;
public class Gephifyer {
public void doStuff(String[] args)
{
String filename = new String();
try{
filename = args[0];
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Supply the subreddit name as the argument.");
System.exit(0);
}
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
Workspace workspace = pc.getCurrentWorkspace();
ImportController importController = Lookup.getDefault().lookup(ImportController.class);
Container container;
try{
File file = new File(filename + ".csv");
//File file = new File(getClass().getResource("askscience.csv").toURI());
container = importController.importFile(file);
container.getLoader().setEdgeDefault(EdgeDefault.DIRECTED);
container.setAllowAutoNode(false); // don't create missing nodes
} catch (Exception ex) {
ex.printStackTrace();
return;
}
// Append imported data to graph api
importController.process(container, new DefaultProcessor(), workspace);
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
DirectedGraph directedGraph = graphModel.getDirectedGraph();
// Now let's manipulate the graph api, which stores / serves graphs
System.out.println("Nodes: " + directedGraph.getNodeCount() + "\nEdges: " + directedGraph.getEdgeCount());
//Run OpenOrd.
//OpenOrdLayout layout = new OpenOrdLayout(null);
YifanHuLayout layout = new YifanHuLayout(null, new StepDisplacement(0.95f));
layout.setGraphModel(graphModel);
layout.resetPropertiesValues();
layout.initAlgo();
layout.goAlgo();
while (layout.canAlgo()) // This is only possible because OpenOrd has a finite number of iterations.
{
layout.goAlgo();
}
AttributeModel attributemodel = Lookup.getDefault().lookup(AttributeController.class).getModel();
// Get modularity for coloring
Modularity modularity = new Modularity();
modularity.setUseWeight(true);
modularity.setRandom(true);
modularity.setResolution(1.0);
modularity.execute(graphModel, attributemodel);
// Partition with modularity
AttributeColumn modcol = attributemodel.getNodeTable().getColumn(Modularity.MODULARITY_CLASS);
PartitionController partitionController = Lookup.getDefault().lookup(PartitionController.class);
Partition p = partitionController.buildPartition(modcol, directedGraph);
NodeColorTransformer nodeColorTransformer = new NodeColorTransformer();
nodeColorTransformer.randomizeColors(p);
partitionController.transform(p, nodeColorTransformer);
// Ranking
RankingController rankingController = Lookup.getDefault().lookup(RankingController.class);
Ranking degreeRanking = rankingController.getModel().getRanking(Ranking.NODE_ELEMENT, Ranking.INDEGREE_RANKING);
AbstractSizeTransformer sizeTransformer = (AbstractSizeTransformer) rankingController.getModel().getTransformer(Ranking.NODE_ELEMENT, org.gephi.ranking.api.Transformer.RENDERABLE_SIZE);
sizeTransformer.setMinSize(5.0f);
sizeTransformer.setMaxSize(40.0f);
rankingController.transform(degreeRanking,sizeTransformer);
// Finally, the preview model
PreviewController previewController = Lookup.getDefault().lookup(PreviewController.class);
PreviewModel previewModel = previewController.getModel();
previewModel.getProperties().putValue(PreviewProperty.SHOW_NODE_LABELS, Boolean.TRUE);
previewModel.getProperties().putValue(PreviewProperty.NODE_LABEL_COLOR, new DependantOriginalColor(Color.BLACK));
previewModel.getProperties().putValue(PreviewProperty.NODE_LABEL_FONT, previewModel.getProperties().getFontValue(PreviewProperty.NODE_LABEL_FONT).deriveFont(8));
previewModel.getProperties().putValue(PreviewProperty.EDGE_CURVED, Boolean.FALSE);
previewModel.getProperties().putValue(PreviewProperty.EDGE_OPACITY, 50);
previewModel.getProperties().putValue(PreviewProperty.EDGE_RADIUS, 10f);
previewModel.getProperties().putValue(PreviewProperty.BACKGROUND_COLOR, Color.TRANSLUCENT);
previewController.refreshPreview();
System.out.println("starting export");
ExportController ec = Lookup.getDefault().lookup(ExportController.class);
try{
ec.exportFile(new File(filename + ".svg"));
}
catch (IOException ex){
ex.printStackTrace();
return;
}
System.out.println("Done.");
}
public static void main(String[] args)
{
Gephifyer g = new Gephifyer();
g.doStuff(args);
}
}
At its heart, it's the various demos' code cobbled together to do what I want it to do.
I expect a graph that looks like this svg file, but the result is this svg file. That is, the problem is that the above code yields a graph where the arrows aren't fully connected to the nodes, making it look a bit messy. I can't for my life tell where in the code that is happening, though I guess it would be in the preview model part.
previewModel.getProperties().putValue(PreviewProperty.EDGE_RADIUS, 10f); sets the distance of the arrows from the node.
i have axis m1114 ip camera
i want to display live streaming as well as record streaming using java. i tried following code but frame rate is very low
please suggest some api gives me more frame rate and recording functionality.
import java.io.File;
import java.net.URL;
import com.googlecode.javacpp.Loader;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.*;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_calib3d.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import demo.authenticator.MyAuthenticator;
import java.net.Authenticator;
import java.net.MalformedURLException;
import org.jcodec.api.SequenceEncoder;
public class Demo {
public static void main(String[] args) throws IOException {
CanvasFrame CamWindow = new CanvasFrame("Camera");
int i=0,j=0;
URL url = null ;
SequenceEncoder encoder=new SequenceEncoder(new File("video.mp4"));
try {
// Create a new URL object from the URL-string of our camera.
url = new URL("http://192.168.168.92/axis-cgi/jpg/image.cgi");
} catch (MalformedURLException m) {
m.getMessage();
}
// Check if this camera requires authentication.
// If so, then create and set the authenticator object.
MyAuthenticator authenticator = new MyAuthenticator("root",
"pass");
Authenticator.setDefault(authenticator);
Long stime=System.currentTimeMillis();
while(true){
i++;
//InputStream is = url.openStream();
BufferedImage image = ImageIO.read(url);
CamWindow.showImage(image);
// is.close();
/* if(i<100)
{
encoder.encodeImage(image);
}
else
{
if(j==0)
{
encoder.finish();
j++;
System.out.println("video saved");
System.out.println((System.currentTimeMillis()-stime)/1000+"seconds");
}
}*/
System.out.println((System.currentTimeMillis()-stime));
}
}
}
The Axis camera API is here: http://www.axis.com/files/manuals/vapix_video_streaming_52937_en_1307.pdf
You need to use this:
http:///axis-cgi/mjpg/video.cgi
instead of the image URL you have now. Getting a still image from the Axis camera will be very choppy. You need to use the Motion JPEG feed it spits out.
I have also gone through for these solutions and one of the good API i found is WEBCAM-Capture. I rate it good for some reasons
It is updated
It is open source
Many Examples
And most IMPORTANT its support from its developers is fast and accurate rather than other Camera supporting APIs.
Hope this would help you.
I have two classes viz. ExistInsert.java and TryExist.java . The complete code for ExistInsert is given below:
package tryexist;
import java.util.ArrayList;
import java.util.List;
import org.exist.xmldb.XQueryService;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
public class ExistInsert {
public static String URI = "xmldb:exist://localhost:8899/exist/xmlrpc";
public static String driver = "org.exist.xmldb.DatabaseImpl";
public static List mylist = new ArrayList();
public List insert_data(String xquery){
try{
Class c1 = Class.forName(driver);
Database database=(Database) c1.newInstance();
String collectionPath= "/db";
DatabaseManager.registerDatabase(database);
Collection col=DatabaseManager.getCollection(URI+collectionPath);
XQueryService service = (XQueryService) col.getService("XQueryService","1.0");
service.setProperty("indent", "yes");
ResourceSet result = service.query(xquery);
ResourceIterator i = result.getIterator();
while(i.hasMoreResources()){
Resource r =i.nextResource();
mylist.add(((String)r.getContent()));
}
}
catch(Exception e){
System.out.println(e);
}
return mylist;
}
public void draw_bar(List values, List years ){
try{
//DefaultPieDataset data = new DefaultPieDataset();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(int j=0;j<values.size();j++){
dataset.addValue();
}
//JFreeChart chart = ChartFactory.createPieChart("TEST PEICHART", data, true, true, Locale.ENGLISH);
JFreeChart chart2 = ChartFactory.createLineChart("Assets", "X","Y",dataset , PlotOrientation.VERTICAL, true, true, true);
ChartFrame frame = new ChartFrame("TEST", chart2);
frame.setVisible(true);
frame.setSize(500, 500);
}
catch(Exception e){
System.out.println(e);
}
}
}
Here the function insert_data executes a xquery and return the result into list of String. The function draw_bar draws a barchart using the arguments viz values and years as list. The main problem I faced was converting the List into the Comparable, which is the requirement of dataset.addValue() . In my main program TryExist.java I have:
package tryexist;
import java.util.ArrayList;
import java.util.List;
public class Tryexist {
public static void main(String[] args) throws Exception{
ExistInsert exist = new ExistInsert();
String query = "Some query Here"
List resp = exist.insert_data(query);
List years = new ArrayList();
for (int i=2060;i<=2064;i++){
years.add(i);
}
System.out.println(years);
System.out.println(resp);
exist.draw_bar(resp,years);
}
}
Now executing query returns years and resp as [2060, 2061, 2062, 2063, 2064] and [32905657, 3091102752, 4756935449, 7954664475, 11668355950] respectively. Then How do I edit dataset.addValue() in ExistInsert.java so that I can pass above obtained values resp and years into draw_bar to make a bar diagram for the data passed.?
A complete example using DefaultCategoryDataset, BarChartDemo1, is included in the distribution and illustrated below. Click on the class name to see the source code. The example uses instances of String as column and row keys, but any Comparable can by used, as discussed here.