How to extract relative Xpaths of a WebPage from a URL - dom

I am working on a program to list out the elements inside a webpage and their corresponding relative xpaths.
Using Java and JSoup, I want to extract relative Xpaths created dynamically for all the elements inside any given webPage. A complete and small working utility will definitely help me here.
I want something like:
//*[#id="menu-item-13686"]/a
Sample output:
Element Or Node or component Name: xxxx AND Xpath = //*[#id="menu-item-13686"]/a
Thank you

I think you can start with this.
Issue got fixed in version jOOX - 1.6.1 Compiled with Java 10
Refer https://github.com/jOOQ/jOOX/issues/158
The below code snippet selects all the elements and for each element prints out node name, tag name and CSS selector and Xpath that will uniquely select this element.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.joox.selector.CSS2XPath;
public class TestParser {
public static void main(String[] args) {
try {
Document doc = Jsoup.connect("https://theuserisdrunk.com/").get();
Elements elements = doc.select("*");
for (Element element : elements) {
String path = CSS2XPath.css2xpath(element.cssSelector(), true);
System.out.println("Node name : " + element.nodeName());
System.out.println(" Tag : " + element.tagName());
System.out.println(" CSS : " + element.cssSelector());
System.out.println(" XPath : " + path + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sample Output:
Node name : div
Tag : div
CSS : #mc-embedded-subscribe-form > div.clear:nth-child(4)
XPath : //*[#id='mc-embedded-subscribe-form']/div[#class='clear' or starts-with(#class, 'clear ') or ' clear' = substring(#class, string-length(#class) - string-length(' clear') + 1) or contains(#class, ' clear ')][count(preceding-sibling::*) = 4 - 1]
Node name : input
Tag : input
CSS : #mc-embedded-subscribe
XPath : //*[#id='mc-embedded-subscribe']
Node name : p
Tag : p
CSS : #mc_embed_signup > p.intern:nth-child(2)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 2 - 1]
Node name : a
Tag : a
CSS : #mc_embed_signup > p.intern:nth-child(2) > a
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 2 - 1]/a
Node name : p
Tag : p
CSS : #mc_embed_signup > p.intern:nth-child(3)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 3 - 1]
Node name : i
Tag : i
CSS : #mc_embed_signup > p.intern:nth-child(3) > i
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 3 - 1]/i
Node name : p
Tag : p
CSS : #mc_embed_signup > p.intern:nth-child(4)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 4 - 1]
Node name : a
Tag : a
CSS : #mc_embed_signup > p.intern:nth-child(4) > a:nth-child(1)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 4 - 1]/a[count(preceding-sibling::*) = 1 - 1]
Node name : a
Tag : a
CSS : #mc_embed_signup > p.intern:nth-child(4) > a:nth-child(2)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 4 - 1]/a[count(preceding-sibling::*) = 2 - 1]
Node name : i
Tag : i
CSS : #mc_embed_signup > p.intern:nth-child(4) > i
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 4 - 1]/i
Node name : a
Tag : a
CSS : #mc_embed_signup > p.intern:nth-child(4) > a:nth-child(4)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 4 - 1]/a[count(preceding-sibling::*) = 4 - 1]
Node name : a
Tag : a
CSS : #mc_embed_signup > p.intern:nth-child(4) > a:nth-child(5)
XPath : //*[#id='mc_embed_signup']/p[#class='intern' or starts-with(#class, 'intern ') or ' intern' = substring(#class, string-length(#class) - string-length(' intern') + 1) or contains(#class, ' intern ')][count(preceding-sibling::*) = 4 - 1]/a[count(preceding-sibling::*) = 5 - 1]
Node name : script
Tag : script
CSS : html > body > script:nth-child(3)
XPath : //html/body/script[count(preceding-sibling::*) = 3 - 1]
Node name : script
Tag : script
CSS : html > body > script:nth-child(4)
XPath : //html/body/script[count(preceding-sibling::*) = 4 - 1]

Related

JpaSystemException: No Dialect mapping for JDBC type: 1111

I have viewed some of the related question but the solutions on them are bit older. Most of them are using EntityManager. I have written the following native query in JpaRepository and when I get geojson as a String I'm getting the error mentioned in the title.
Here is my query
#Query(value = "SELECT\n"
+ " json_build_object(\n"
+ " 'type', 'FeatureCollection',\n"
+ " 'features', json_agg(\n"
+ " json_build_object(\n"
+ " 'type', 'Feature',\n"
+ " 'geometry', ST_AsGeoJSON(a.check_in_geom)\\:\\:json,\n"
+ " 'properties', json_build_object(\n"
+ " 'username', a.username,\n"
+ " 'users', (\n"
+ " -- Generate json array of \"users\"\n"
+ " SELECT array_to_json(array_agg(u.*)) \n"
+ " FROM users u \n"
+ " WHERE u.username = a.username\n"
+ " GROUP BY u.username\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " ) Json\n"
+ "FROM\n"
+ " attendances a, users u\n"
+ " WHERE a.username = u.username AND u.designation = 'Manager' AND date_trunc('day', a.created_at)\\:\\:DATE = '2022-04-04'"
+ " ;", nativeQuery = true)
String getAttendanceGeoJsonByDesignationAndDate(String designation, String dateStr);
For now I'm passing designation and date as static values.
When I run this query on Postgresql it runs successfully and return the expected geojson. But spring boot does not allow the result to be as String or it throws exception while running the query.
Please let me know how can I fix it. Also if I need to provide more detail, do let me know.

Add Symbol () in report ssrs

I have code :
CourseName + ' ' + isnull(GradeLevel,'')) as CourseName
The result :
Permit Working High 3
How to make result like this :
Permit Working High (3)
CourseName + ' ' +
CASE
WHEN GradeLevel IS NULL THEN ''
ELSE '(' + GradeLevel + ')'
END
AS CourseName

An identification variable must be provided for a range variable declaration

I'm trying to use this query in my jpa but it doesn't work:
List<Object[]> query = em.createQuery("SELECT Tstat.idStatistiques, TL.codeLieu, TL.materiel, TL.zone, sum(Tstat.colis) as colis, Tstat.defaut, sum(Tstat.nbreDefaut) as nbreDefaut,"
+ " sum(Tstat.nonLu) as nonLu, sum(Tstat.multiple) as multiple, sum(Tstat.nonRecu) as nonRecu, sum(Tstat.incoherent) as incoherent, sum(Tstat.requete) as requete , "
+ "sum(Tstat.tempsFonctionnement) as tempsFonctionnement, SUM(Tstat.tempsUtilisation) as tempsUtilisation, Tstat.modeFonctionnement FROM "
+ "( SELECT CURRENT_DATE as horodatage, St.idStatistiques, St.colis, St.defaut, St.nbreDefaut, St.nonLu, St.requete, St.multiple, St.nonRecu, St.incoherent, St.tempsFonctionnement, St.tempsUtilisation, St.modeFonctionnement FROM Statistique St )"
+ " UNION "
+ "(SELECT h.horodatage, h.idStatistiques, h.colis, h.defaut, h.nbreDefaut, h.nonLu, h.nonRecu, h.requete, h.multiple, h.incoherent, h.tempsFonctionnement, h.tempsUtilisation, h.modeFonctionnement FROM Statistiqueshisto h )"
+ " Tstat "
+ "LEFT JOIN (SELECT * FROM Lieux) as TL on Tstat.idStatistiques = TL.code_VI WHERE idStatistiques like :A ").setParameter("A", 0040+"%").getResultList();
This gives me error
The expression is invalid, which means it does not follow the JPQL
grammar.

Google Earth API Javascript Tour animation

I'm trying to implement Google Earth API tour in javascript. I tried parsekml method, but i couldn't make any tour. I have one question... Does javascript with Google Earth API support tour? I don't want use fetchkml or import from any other link. Here I have enclosed my sample code. Any help...?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Google Earth-Practice</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">#import "static/examples.css";</style>
<style type="text/css">#import "static/prettify/prettify.css";</style>
<script type="text/javascript" src="static/prettify/prettify.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi?hl=en&key=ABQIAAAAwbkbZLyhsmTCWXbTcjbgbRSzHs7K5SvaUdm8ua-Xxy_-2dYwMxQMhnagaawTo7L1FE1-amhuQxIlXw"></script>
<script type="text/javascript">
/* <![CDATA[ */
var ge;
var i=1;;
var l=1;
var Excel;
var value;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
// add some layers
// ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
// ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
document.getElementById('installed-plugin-version').innerHTML =ge.getPluginVersion().toString();
}
function failureCB(errorCode) {
}
function my_function()
{
return Excel.Workbooks.Open("C:/TEST.xls").ActiveSheet.Cells(l,i).Value;
}
//where l is number of rows and i are columns...
function DrawVector()
{
//where l is number of rows and i are columns...
//var i=1;
//var l=1;
var z=1;
var line=[];
document.getElementById('loadingImage').style.visibility='visible';
document.getElementById('Fly').style.visibility='visible'
Excel = new ActiveXObject("Excel.Application");
Excel.Visible = false;
do
{
a=my_function()
if (a!=null)
{
//var t=prompt("hello");
line[z]=a;
z++;
i++;
}
else
{
l++;
i=1;
//document.write("<br />");
}
b = my_function()
}while(a!=null || b!=null);
var lineStringPlacemark = ge.createPlacemark('');
var lineString = ge.createLineString('');
lineStringPlacemark.setGeometry(lineString);
lineString.setExtrude(true);
lineString.setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);
// Add LineString points
for(i=1;i<z;i=i+4)
{
var placemark = ge.createPlacemark('');
var icon = ge.createIcon('');
icon.setHref('https://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/256/Map-Marker-Flag--Right-Chartreuse.png');
var style = ge.createStyle(''); //create a new style
style.getIconStyle().setIcon(icon);
style.getIconStyle().setScale(3.0); //apply the icon to the style
//style.getColor().set('ffffffff');
placemark.setStyleSelector(style); //apply the style to the placemark
// Set the placemark's location.
var point = ge.createPoint('');
point.setLatitude(line[i+1]);
point.setLongitude(line[i+2]);
point.setAltitude(line[i+3]);
point.setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);
placemark.setGeometry(point);
placemark.setName(line[i]);
// Add the placemark to Earth.
ge.getFeatures().appendChild(placemark);
lineString.getCoordinates().pushLatLngAlt(line[i+1],line[i+2],line[i+3]);
}// lineString.getCoordinates().pushLatLngAlt(38.885278,-77.701944,1900);
// lineString.getCoordinates().pushLatLngAlt(38.769167,-77.901944,2700);
// Create a style and set width and color of line
lineStringPlacemark.setStyleSelector(ge.createStyle(''));
var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
lineStyle.setWidth(4);
var polyColor = lineStringPlacemark.getStyleSelector().getPolyStyle().getColor();
//polyColor.set('ffffffff');
polyColor.setA(127);
polyColor.setB(0);
polyColor.setG(255);
polyColor.setR(0);
//lineStyle.polystyle.color = '990000ff';
lineStyle.getColor().set('ffffffff'); // aabbggrr format
//polystyle color = 66FFF700;
//lineString.getPolyStyle(polystyle);// Add the feature to Earth
ge.getFeatures().appendChild(lineStringPlacemark);
document.getElementById('loadingImage').style.visibility='hidden';
}
function showSun() {
ge.getSun().setVisibility(true);
ge.getTime().getControl().setVisibility(ge.VISIBILITY_SHOW);
}
function KmlView()
{ DrawVector();
var name='start';
var kmlString = ''
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">'
+ ' <Document>'
+'<Camera> <altitudeMode>relativeToGround</altitudeMode>'
+ ' <longitude>-77.451111</longitude>'
+ ' <latitude>38.935278</latitude>'
+ ' <altitude>10000 </altitude>'
+ ' <heading>-105.948935</heading>'
+ ' <tilt>93</tilt>'
+ '<range>50</range>'
+ ' </Camera>'
+ ' <open>1</open> '
+ ' <gx:Tour> '
+ ' <name>Play me</name> '
+ ' <gx:Playlist> '
+ ' <gx:FlyTo> '
+ ' <gx:duration>2.0</gx:duration> '
+ ' <gx:flyToMode>bounce</gx:flyToMode> '
+ ' <LookAt> '
+ ' <longitude>-77.451111</longitude> '
+ ' <latitude> 38.935278</latitude> '
+ ' <altitude>900</altitude> '
+ ' <heading>-123.948935</heading> '
+ ' <tilt>63.0957450</tilt> '
+ ' <range>469.850414</range> '
+ ' <gx:altitudeMode>relativeToGround </gx:altitudeMode> '
+ ' </LookAt> '
+ ' </gx:FlyTo> '
+ ' <gx:AnimatedUpdate> '
+ ' <gx:duration>0.0</gx:duration> '
+ ' <Update> '
+ ' <targetHref/> '
+ ' <Change> '
+ ' <Placemark targetId="Fly1"> '
+ ' <gx:balloonVisibility>1</gx:balloonVisibility> '
+ ' </Placemark> '
+ ' </Change> '
+ ' </Update> '
+ ' </gx:AnimatedUpdate> '
+ ' <gx:AnimatedUpdate> '
+ ' <gx:duration>0.0</gx:duration> '
+ ' <Update> '
+ ' <targetHref/> '
+ ' <Change> '
+ ' <Placemark targetId="Fly1">'
+ ' <gx:balloonVisibility>0</gx:balloonVisibility> '
+ ' </Placemark> '
+ ' </Change> '
+ ' </Update> '
+ ' </gx:AnimatedUpdate> '
+ ' <gx:FlyTo> '
+ ' <gx:duration>20</gx:duration> '
+ ' <gx:flyToMode>smooth</gx:flyToMode> '
+ ' <LookAt> '
+ ' <longitude>-77.701944</longitude> '
+ ' <latitude>38.885278</latitude> '
+ ' <altitude>1900</altitude> '
+ ' <heading>-123.948935</heading> '
+ ' <tilt>63.117317</tilt> '
+ ' <range>792.665540</range> '
+ ' <gx:altitudeMode>relativeToGround</gx:altitudeMode> '
+ ' </LookAt> '
+ ' </gx:FlyTo> '
+ ' <gx:AnimatedUpdate> '
+ ' <gx:duration>0.0</gx:duration> '
+ ' <Update> '
+ ' <targetHref/> '
+ ' <Change> '
+ ' <Placemark targetId="Fly2"> '
+ ' <gx:balloonVisibility>1</gx:balloonVisibility> '
+ ' </Placemark> '
+ ' </Change> '
+ ' </Update> '
+ ' </gx:AnimatedUpdate> '
+ ' <gx:AnimatedUpdate> '
+ ' <gx:duration>0.0</gx:duration> '
+ ' <Update> '
+ ' <targetHref/> '
+ ' <Change> '
+ ' <Placemark targetId="Fly2"> '
+ ' <gx:balloonVisibility>0</gx:balloonVisibility> '
+ ' </Placemark> '
+ ' </Change> '
+ ' </Update> '
+ ' </gx:AnimatedUpdate> '
+ ' <gx:FlyTo> '
+ ' <gx:duration>30</gx:duration>'
+ ' <gx:flyToMode>smooth</gx:flyToMode> '
+ ' <LookAt> '
+ ' <longitude>-77.901944</longitude> '
+ ' <latitude>38.769167</latitude> '
+ ' <altitude>2700</altitude> '
+ ' <heading>-123.948935</heading> '
+ ' <tilt>63.063392</tilt> '
+ ' <range>633.666023</range> '
+ ' <altitudeMode>relativeToGround</altitudeMode> '
+ ' </LookAt> '
+ ' </gx:FlyTo> '
+ ' <gx:AnimatedUpdate> '
+ ' <gx:duration>0.0</gx:duration> '
+ ' <Update> '
+ ' <targetHref/> '
+ ' <Change> '
+ ' <Placemark targetId="onland"> '
+ ' <gx:balloonVisibility>1</gx:balloonVisibility> '
+ ' </Placemark> '
+ ' </Change> '
+ ' </Update> '
+ ' </gx:AnimatedUpdate> '
+ ' </gx:Playlist> '
+ ' </gx:Tour> '
+ ' <Placemark id="Fly1"> '
+ ' <name> </name> '
+ ' <description> '
+ ' KIAD Starting point... </description> '
+ ' <Point> '
+ ' <gx:altitudeMode>relativeToGround</gx:altitudeMode> '
+ ' </Point> '
+ ' </Placemark> '
+ ' <Placemark id="Fly2"> '
+ ' <name></name> '
+ ' <description>We reached LOULU...</description> '
+ ' <Point> '
+ ' <gx:altitudeMode>relativeToGround</gx:altitudeMode> '
+ ' </Point> '
+ ' </Placemark> '
+ ' <Placemark id="onland"> '
+ ' <name></name> '
+ ' <description> '
+ ' <![CDATA[ RNDLI. '
+ ' You<gx:balloonVisibility>1</gx:balloonVisibility> '
+ ' Reached your destination]]> '
+ ' </description> '
+ ' <Point> '
+ ' </Point> '
+ ' </Placemark> '
+ ' <ScreenOverlay>'
+ ' <name>Absolute Positioning: Top left</name>'
+ ' <visibility>1</visibility>'
+ ' <Icon>'
+ ' <href>https://cdn4.iconfinder.com/data/icons/32x32-free-design-icons/32/Target.png</href>'
+ ' </Icon>'
+ ' <overlayXY x="0.5" y=".5" xunits="fraction" yunits="fraction"/>'
+ ' <screenXY x="0.5" y=".5" xunits="fraction" yunits="fraction"/>'
+ ' <rotation>2.37878630116985</rotation>'
+ ' <size x=".1" y=".1" xunits="fraction" yunits="fraction"/>'
+ ' </ScreenOverlay>'
+ ' </Document>'
+ ' </kml>';
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
ge.getView().setAbstractView(kmlObject.getAbstractView());
//ge.getTourPlayer().setTour(kmlObject);
// ge.getTourPlayer().play();
}
function hideSun() {
ge.getSun().setVisibility(false);
}
/* ]]> */
</script>
</head>
<body onload="if(window.prettyPrint)prettyPrint();init();" bgcolor=#87CEEB>
<h1>Google Earth -Practice</h1>
<dl>
</dl>
<div style="clear: both;"></div>
<div id="ui" style="position: relative;">
<div id="map3d_container" style="border: 1px solid #000; width: 800px; height: 800px;">
<div id="map3d" style="height: 100%;"></div>
</div>
<div id="extra-ui" style="position: absolute; left: 820px; top: 0;">
Starting Point:<input type="text" name="fname">
Destination Point: <input type="text" name="lname"><br><br/><br/>
<center><input type="button" onclick="KmlView()" value="Start"/><br/><br/></center><br/><br/>
<form id="Fly" style="visibility:hidden">
<input type="button" onclick="showSun()" value="Show Sun"/><br/><br/><br/>
<input type="button" onclick="hideSun()" value="Hide Sun"/><br/><br/><br/>
<img id="loadingImage" src="C:\Users\h118093\Downloads\Load2.gif" height="50%" width="50%" style="visibility:hidden" alt="Ready To Fly...."/>
</form>
</div>
</div>
</body>
</html>
How to make tour on Google Earth using javascript without fetchkml?
According to Google's Earth API site, Touring is supported via the javascript API to just play tours already encoded in the KML. Google's Touring API web-page: https://developers.google.com/earth/documentation/touring
Google's documentation on the above web-page link contains examples how to invoke a tour in a KML. The code you supplied above just loads the KML into the Google Earth plugin. Your code does not invoke the tour.
Your next step is to invoke the tour properly via the ge.getTourPlayer().setTour(object) and ge.getTourPlayer().play() methods shown on that page. You should be able to utilize the "Simple Tour" example shown on Google's touring documentation web page.
I tried out your code, and got it to play the tour when coded properly according to the info on Google's touring web page. However, your kmlString has some errors in it too. You don't have closing /Document and /kml tags. And to get the "Simple Tour" to work you actually need to remove the Document tag entirely.
[FYI ... you do know this API is going to be turned off by Google on 12/12/2015? You will need to begin looking for a tour alternative if you plan to utilize it past the end of this year.]
Edited answer to add code changes:
var kmlString = ''
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">'
//+ ' <Document>' //<---------delete this line
:
: <clipped>
:
+ ' </gx:Tour>'
+ '</kml>'; //<---------add this line
kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
//ge.getView().setAbstractView(kmlObject.getAbstractView()); //<---------delete this line unless you need it for other purposes
ge.getTourPlayer().setTour(kmlObject); //<---------add these two lines
ge.getTourPlayer().play();

ERROR: duplicate key value violates unique constraint "xak1fact_dim_relationship"

I am getting the below error while deleting some rows and updating the table based on a condition from java. My database is PostgreSQL 8.4. Below is the error:
ERROR: duplicate key value violates unique
constraint "xak1fact_dim_relationship"
The code cuasing this issue is below:
/**
* Commits job. This does the following:
* <OL>
* <LI> cancel previous datamart states </LI>
* <LI> drop diabled derived objects </LI>
* <LI> flip mirror relationships for objects with next states </LI>
* <LI> advance rolloff_state from start1 to complete1, from start2 to complete </LI>
* <LI> set 1/0 internal states to 0/-1 </LI>
* <LI> remove header objects with no letter rows </LI>
* <LI> mark mirror rel as OS if children are missing (e.g., semantic w/o agg build) </LI>
* <LI> mark mirror rel as OS if int-map not in sync with dim base (e.g., int-map SQL w/o semantic) </LI>
* </OL>
*/
protected void CommitJobUnprotected()
throws SQLException
{
if (_repl.epiCenterCon== null)
throw makeReplacementError(0);
boolean oldAutoCommitStatus = _repl.epiCenterCon.getAutoCommit();
try
{
_repl.epiCenterCon.setAutoCommit(false);
Statement stmt = null;
boolean committed = false;
synchronized (SqlRepl.metaChangeLock)
{
try
{
stmt = _repl.epiCenterCon.createStatement();
// update internal states for fact_dim_relationship
metaExec(stmt, "DELETE from fact_dim_relationship WHERE internal_state = -1 AND " +
" EXISTS (SELECT 1 FROM fact_dim_relationship WHERE internal_state = 1)",
" SELECT 1 from fact_dim_relationship WHERE internal_state = -1 AND " +
" EXISTS (SELECT 1 FROM fact_dim_relationship WHERE internal_state = 1)"); /*1*/
metaExec( stmt, "UPDATE fact_dim_relationship SET internal_state = internal_state - 1 " +
" WHERE EXISTS (SELECT 1 FROM fact_dim_relationship inner1 " +
" WHERE inner1.internal_state = 1 " +
" AND inner1.fact_tbl_key = fact_dim_relationship.fact_tbl_key " +
" AND inner1.dim_base_key = fact_dim_relationship.dim_base_key ) ",
" SELECT 1 FROM fact_dim_relationship " +
" WHERE EXISTS (SELECT 1 FROM fact_dim_relationship inner1 " +
" WHERE inner1.internal_state = 1 " +
" AND inner1.fact_tbl_key = fact_dim_relationship.fact_tbl_key " +
" AND inner1.dim_base_key = fact_dim_relationship.dim_base_key ) "); /*5*/
System.out.println("Update done on fact_dim_relationship");
_repl.doDrop(SqlReplLogger.DB_META, stmt, "fact_agg", "SELECT fact_agg_key FROM fact_agg f WHERE " +
" NOT EXISTS (SELECT 1 FROM fact_agg_letter l WHERE " +
" f.fact_agg_key = l.fact_agg_key) "); /*6*/
_repl.doDrop(SqlReplLogger.DB_META, stmt, "dim_base_agg", "SELECT dim_base_agg_key FROM dim_base_agg d WHERE " +
" NOT EXISTS (SELECT 1 FROM dim_base_agg_letter l WHERE " +
" d.dim_base_agg_key = l.dim_base_agg_key) "); /*6*/
CheckOutOfSync(stmt, "fact_agg", null); /*7*/
CheckOutOfSync(stmt, "dim_base_agg", null); /*7*/
metaExec( stmt, " update mirror_relationship set relation_to_current = 'Out Of Sync' " +
" where dim_col_intmap_key is not null " +
" and relation_to_current = 'One Back' " +
" and not exists ( " +
" select 1 " +
" from mirror_relationship m2, dim_col_view c, dim_col_intmap i " +
" where m2.dim_base_key = c.dim_base_key " +
" and c.dim_col_key = i.dim_col_key " +
" and i.dim_col_intmap_key = mirror_relationship.dim_col_intmap_key " +
" and m2.relation_to_current = 'One Back') ",
" SELECT 1 FROM mirror_relationship " +
" where dim_col_intmap_key is not null " +
" and relation_to_current = 'One Back' " +
" and not exists ( " +
" select 1 " +
" from mirror_relationship m2, dim_col_view c, dim_col_intmap i " +
" where m2.dim_base_key = c.dim_base_key " +
" and c.dim_col_key = i.dim_col_key " +
" and i.dim_col_intmap_key = mirror_relationship.dim_col_intmap_key " +
" and m2.relation_to_current = 'One Back') "); /*8*/
// clean out the tables used by mombuilder, aggbuilder, and semantics
metaExec( stmt, "delete from relation_intermediary", "select 1 from relation_intermediary" );
_repl.epiCenterCon.commit();
committed = true;
}
finally
{
safeMetaRollbackIfNeeded( committed );
_repl.safeClose( null, stmt );
}
} // end synchronized block
}
finally
{
_repl.epiCenterCon.setAutoCommit(oldAutoCommitStatus);
}
}
The first delete statement ran well, but while running the update it is throwing the above exception....! We support the SQLServer, Oracle and DB2, and the same code runs fine with other DBs. By the way we run these statements in a READ_COMMITTED transaction level and we are setting the autocommit off if anything fails in between we safely rolls back. If i run the above code with autocommit true the code works fine! But we should not do so. I am suspecting the Multi version concurrency control feature of PostgreSQL, am i wrongly setting the Isolation level? Please help me as early as possible. I can provide what ever the info you want.
If it is only this particular set of queries, use SET CONSTRAINT:
BEGIN;
SET CONSTRAINT = xak1fact_dim_relationship DEFERRED;
-- Do your SQL
COMMIT;
If this is a very common case, you can change your database schema to you can, change your database schema to support INITIALLY DEFERRED.