I have a Java Web Application which allows a user to select a bunch of fields (with filters, aggregations etc.) which will then be used to create charts/graphs.
The database behind the application is a standard PostGreSQL 9.04 database but we are using the Hibernate ORM to access data.
The code I have right now creates an HQL Query (Hibernate Query Language) based on the users selections from the web interface. What I really need is some way to use that query to create a dataset that JFreeCharts can use to build the chart.
Are there any examples of JFreeChart and Hibernate integration? Having researched it myself I can't really find much other than this post on the Hibernate forum which says it can be done but giving no detail on how:
https://forum.hibernate.org/viewtopic.php?f=6&t=997556
To summarise:
I have an HQL Query, I want to use that to create a data source which JFreeCharts can use to create Pie/Bar/Stacked Bar/Line charts.
Any help would be much appreciated.
Absent an existing implementation, you might be inspired by one of the existing data model variations seen in org.jfree.data.jdbc.
I tried something. Here's the code for my entity class:
package com.gxet4n.jfreechart;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="mobile_tbl")
public class Mobile_tbl {
#Id
private int id;
#Column(name="mobile_brand")
private String mobile_brand;
#Column(name="unit_sale")
private int unit_sale;
// getters and setters
}
Then here's the code for my main class :
package com.gxet4n.jfreechart;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
public class PieChart_HQL {
public static void main( String[ ] args )throws Exception {
DefaultPieDataset dataset = new DefaultPieDataset( );
DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
try {
SessionFactory sessionFactory = new Configuration().configure().addAnnotatedClass(Mobile_tbl.class).buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query<?> query = session.createQuery("FROM Mobile_tbl");
List<Mobile_tbl> mobiles = (List<Mobile_tbl>)query.list();
session.close();
for (Mobile_tbl m : mobiles) {
dataset.setValue(m.getMobile_brand(), m.getUnit_sale());
}
for (Mobile_tbl m : mobiles) {
dataset2.setValue(m.getUnit_sale(),m.getMobile_brand(),"");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
JFreeChart chart = ChartFactory.createPieChart(
"Mobile Sales", // chart title
dataset, // data
true, // include legend
true,
false );
JFreeChart barChart = ChartFactory.createBarChart(
"Mobiles Sales",
"Mobile Brand",
"Unit Sale",
dataset2,
PlotOrientation.VERTICAL,
true, true, false);
int width = 560; /* Width of the image */
int height = 370; /* Height of the image */
File pieChart = new File( "Pie_Chart_HQL.png" );
ChartUtils.saveChartAsPNG(pieChart, chart, width, height);
File barchart = new File( "Bar_Chart_HQL.png" );
ChartUtils.saveChartAsPNG(barchart, barChart, width, height);
}
}
Finally there's the results :
I used hibernate core 5.2.12.Final and jfreechart 1.5.0
Related
I'm beginning in Neo4j java embedded graph.
I have made a first test but I cant visualize my graph in neo4j-community.
Here is my code for creating the graph :
package connection;
import java.io.File;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class embededdedGraph {
public static void main(String... args) throws Exception {
GraphDatabaseFactory graphDbFactory = new GraphDatabaseFactory();
File graphDir = new File("/home/nicolas/neo4j-community-3.5.14/data/databases/cars.db");
GraphDatabaseService graphDb = graphDbFactory.newEmbeddedDatabase(graphDir);
Transaction tx = graphDb.beginTx();
createNode(graphDb);
tx.close();
}
public static void createNode(GraphDatabaseService graphDb) {
Node car = graphDb.createNode();
car.addLabel(Label.label("Car"));
car.setProperty("make", "tesla");
car.setProperty("model", "model3");
Node owner = graphDb.createNode(Label.label("Person"));
owner.setProperty("firstName", "Oliver");
owner.setProperty("lastName", "John");
owner.createRelationshipTo(car, RelationshipType.withName("owner"));
}
}
Next I changed the value of "#dbms.active_database" to "dbms.active_database=cars.db in the /neo4j-community-3.5.14/conf/neo4.conf file.
When I restart the neo4j-community, the database name is "cars.db" but it indicated that there are no labels and relationships in it.
What is the problem I cannot figure?
Nicolas
It looks like you need to call tx.success() or tx.fail() before tx.close().
https://neo4j.com/docs/java-reference/3.5/javadocs/org/neo4j/graphdb/Transaction.html
I am also new at this API, I hope it helps
i'm starting a new Eclipse RCP application and it's my first time and i have a problem , i want to display list of my available database(by the way i'm using nosql database(MongoDB)) but my code seems not to work, can anyone help please , can anyone point me to a good tutorial
thanks for your time and help guys.
package test2.parts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.di.Persist;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCursor;
import org.eclipse.swt.widgets.Label;
public class SamplePart {
org.eclipse.swt.widgets.List list ;
private TableViewer tableViewer;
#Inject
private MPart part;
#PostConstruct
public void createComposite(Composite parent) {
parent.setLayout(new GridLayout(1, false));
Text txtInput = new Text(parent, SWT.BORDER);
txtInput.setMessage("Enter text to mark part as dirty");
txtInput.addModifyListener(e -> part.setDirty(true));
txtInput.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
list = new org.eclipse.swt.widgets.List(parent, SWT.BORDER);
tableViewer = new TableViewer(parent);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
tableViewer.setInput(createInitialDataModel());
tableViewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
}
#Focus
public void setFocus() {
tableViewer.getTable().setFocus();
}
#Persist
public void save() {
part.setDirty(false);
}
private List<String> createInitialDataModel() {
MongoClient mongoClient = new MongoClient("localhost", 27017);
ArrayList<String> dbs = new ArrayList<String>();
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
while (dbsCursor.hasNext()) {
list.add(dbsCursor.next());
}
return (List<String>) list;
}
}
The stack trace shows that the plug-in can't find the MongoClient class.
Eclipse plug-ins can only access code in other plug-ins or in jars included in the plug-in. They can't use jars which are just on the ordinary Java classpath.
So you will need to add the jar containing the MongoClient class in to your plugin and add it to the Bundle-Classpath in the MANIFEST.MF. You can do that in the MANIFEST.MF editor in the 'Classpath' section of the 'Runtime' tab.
You also need to include the jar in the build.properties file.
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.
I am trying to create a CQ 5.4 workflow which updates the description of the Digital Asset Image which started this workflow.
My Problem is when I compile and build this code the WorkFlow Process does not appear in the Process Step's drop down in CQ 5.4 author server instance.
Here is the code , Let me know if any other step is required or I am doing wrong somewhere,
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.commons.process.AbstractAssetWorkflowProcess;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.WorkflowProcess;
import com.day.cq.workflow.metadata.MetaDataMap;
#Component
#Service(WorkflowProcess.class)
#Properties({
#Property(name = "service.description", value = "Update the Image Description"),
#Property(name = "service.vendor", value = "******"),
#Property(name = "process.label", value = "Update the Image Description") })
public class RemoveImgPropBatchWorkFlowProcessStep extends AbstractAssetWorkflowProcess{
private static final Logger log = LoggerFactory.getLogger(RemoveImgPropBatchWorkFlowProcessStep.class);
#Override
public void execute(WorkItem workItem, WorkflowSession workFlowSesion, MetaDataMap meta)
throws WorkflowException {
// TODO Auto-generated method stub
log.info("RemoveImgPropBatchWorkFlowProcessStep Workflow called up");
workItem.getNode().setDescription("Image is updated");
}
}
The Issue is resolved, all the dependent bundles were not active hence the workflow process was not getting displayed. Regards, Yash
how to convert a set of hk80 grid to lat/lon?
HK 1980 Grid is EPSG 2326, while Lat/Long WGS84 is EPSG 4326
Or is there any is more suitible for doing this
I hope that the following code can help you. I need to use GeoTools to achieve your purpose. Also, you need to insert the relevant northing and easting for epsg 2326. However, I still cannot solve the exception problem yet. In order to use this code properly, you need to download and import all GeoTools jars besides gt-epsg-postgresql.
package org.geotools.tutorial;
import java.awt.geom.Point2D;
import java.io.File;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.factory.Hints;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.referencing.CRS;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.geotools.referencing.*;
/**
* Prompts the user for a shapefile and displays the contents on the screen in a map frame.
* <p>
* This is the GeoTools Quickstart application used in documentationa and tutorials. *
*/
public class quickstart {
/**
* GeoTools Quickstart demo application. Prompts the user for a shapefile and displays its
* contents on the screen in a map frame
*/
public static void main(String[] args) throws Exception {
//Point2D.Double srcProjec = new Point2D.Double (836694.050, 819069.800);
//Point2D.Double dstProjec = new Point2D.Double (132,37);
// display a data store file chooser dialog for shapefiles
//Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
//CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
//CoordinateReferenceSystem crs = factory.createCoordinateReferenceSystem("EPSG:4326");
CRSAuthorityFactory factory = CRS.getAuthorityFactory(true);
CoordinateReferenceSystem srcCRS = factory.createCoordinateReferenceSystem("EPSG:2326");
CoordinateReferenceSystem dstCRS = factory.createCoordinateReferenceSystem("EPSG:4326");
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(srcCRS, dstCRS, lenient);
double[] srcProjec = {818039, 836361};// easting, northing,
double[] dstProjec = {0, 0};
transform.transform(srcProjec, 0, dstProjec, 0, 1);
System.out.println("longitude: " + dstProjec[0] + ", latitude: " + dstProjec[1]);
}
}