repo
string
commit
string
message
string
diff
string
geebee/homeauto
5cc6e1297490eade86ae0ce478822ab931d8707c
homeauto first checkin
diff --git a/README b/README new file mode 100644 index 0000000..97b5553 --- /dev/null +++ b/README @@ -0,0 +1,39 @@ +Michael Goldberger - March 2009 +v 0.1 + +Python, Perl, JavaScript, and SVG Home Automation Control & Display Setup + +HOW TO SET-UP THE FILES: +========================= + Inside the "apache" folder there is... + An SVG document, "htdocs/apt.svg". + This file contains the floorplan diagram. + A JavaScript file, "htdocs/main.js". + This file contains the JavaScript functions for creating the badges, the AJAX request functions, and some other goodies. + A Python CGI file, "cgi-bin/acceptJSON.cgi". + This file accepts input from the Python hardware abstraction and outputs (in JSON format) the sensor ID and status to the SVG document. + + The "htdocs/*" files should go inside the apache DocumentRoot folder (currently hardcoded to "C:\Apache2\htdocs" in the "xPL/xplpython.py" file) + + The "cgi-bin/*" files should go inside an Apache ScriptAlias tag (usually one level above htdocs, and the folder is called cgi-bin). + + In order to allow the SVG document to receive update notices from the hardware sensors, the USB->COM port driver has to be installed. + NB: see the setups folder for more info + +HOW TO RUN IT: +=============== + + Once the files are all setup as described above, start the Perl xPL hub which bridges all of the xPL network segments and receives xPL messages. + xPL/xplhub.pl + + And, start the Python xPL/JSON Bridge. + xPL/xplpython.py + + At this point, the Perl stdout device should be showing the Python script's connection, + and the Python stdout device should be showing the status messages of the sensors for which it is receiving data. + + If you navigate to http://<host>/apt.svg and manually activate the sensor, within 5 seconds (changable in main.js), + the Status badge for the javascript ID assigned to the device with a correspoinding hex ID, it will + change to GREEN, for when the sensor is ready to be armed, + and RED when it is in ALERT status (also meaning that the zone to which this sensor belongs cannot be armed) + diff --git a/apache/cgi-bin/acceptJSON.cgi b/apache/cgi-bin/acceptJSON.cgi new file mode 100644 index 0000000..6c9475f --- /dev/null +++ b/apache/cgi-bin/acceptJSON.cgi @@ -0,0 +1,20 @@ +#!C:/Python26/python.exe + +import cgi,json + +#print "Content-Type: text/x-json\n" +form = cgi.FieldStorage() + +jsId = form['jsId'].value +sensorStatus = form['sensorStatus'].value + +jsonReply = {'sensor':{'jsId':jsId,'sensorStatus':sensorStatus}} +jsonReply = json.dumps(jsonReply) + +file_object = open("C:/Apache2/htdocs/sensorStatus.json","w") +file_object.write(jsonReply) +file_object.close() + +print "Content-Type: text/plain\n" +print "jsId Is: " + jsId + ", sensorStatus Is: " + sensorStatus + diff --git a/apache/htdocs/apt.svg b/apache/htdocs/apt.svg new file mode 100644 index 0000000..bbb97ac --- /dev/null +++ b/apache/htdocs/apt.svg @@ -0,0 +1,315 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="744.09448819" + height="1052.3622047" + id="svg2" + onload="createBadge('den_south_windows', 'normal'); createBadge('den_south_windows', 'alert')" + sodipodi:version="0.32" + inkscape:version="0.46" + sodipodi:docname="apt.svg" + inkscape:output_extension="org.inkscape.output.svg.inkscape" + inkscape:export-xdpi="90" + inkscape:export-ydpi="90"> + <defs + id="defs4"> + <inkscape:perspective + sodipodi:type="inkscape:persp3d" + inkscape:vp_x="0 : 526.18109 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_z="744.09448 : 526.18109 : 1" + inkscape:persp3d-origin="372.04724 : 350.78739 : 1" + id="perspective67" /> + </defs> + <sodipodi:namedview + id="base" + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1.0" + gridtolerance="10000" + guidetolerance="10" + objecttolerance="10" + inkscape:pageopacity="0.0" + inkscape:pageshadow="2" + inkscape:zoom="1" + inkscape:cx="3.0713" + inkscape:cy="640" + inkscape:document-units="px" + inkscape:current-layer="layer1" + showgrid="true" + inkscape:snap-global="true" + inkscape:window-width="1680" + inkscape:window-height="1001" + inkscape:window-x="0" + inkscape:window-y="22"> + <inkscape:grid + type="xygrid" + id="grid2385" /> + </sodipodi:namedview> + <metadata + id="metadata7"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + </cc:Work> + </rdf:RDF> + </metadata> + <g + inkscape:label="Layer 1" + inkscape:groupmode="layer" + id="layer1"> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 290,1042.3622 L 290,992.36218 L 380,992.36218 L 380,1042.3622 L 290,1042.3622 z" + id="front_door" + inkscape:label="Front Door" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 290,1002.3622 L 230,1002.3622" + id="path2391" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.92582011px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 379.92857,1002.3622 L 439.92857,1002.3622" + id="path2393" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.95742708px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 230,1002.4039 L 230,892.40385" + id="path2395" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 440,1002.3622 L 440,812.36218" + id="path2397" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 410,812.36218 L 470,812.36218" + id="path2401" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 410,742.36218 L 470,742.36218" + id="path2403" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.96844751px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 440,742.39106 L 440,592.32857" + id="path2405" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.94868332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 440,522.31218 L 440,432.31218" + id="path2407" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 230,602.36218 L 230,822.36218" + id="path2411" /> + <path + inkscape:label="Back Door" + id="back_door" + d="M 320,132.36218 L 320,82.362166 L 410,82.362166 L 410,132.36218 L 320,132.36218 z" + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1.00024998px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 230,532.35921 L 230,432.30921" + id="path3215" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 230,432.36218 L 60,432.36218 L 60,122.36218 L 320,122.36218" + id="path3217" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 410,122.36218 L 680,122.36218" + id="path3219" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 680,122.36218 L 680,432.36218 L 440,432.36218" + id="path3221" /> + <rect + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.66574901;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.33149803,0.66574901,0.33287451,0.66574901;stroke-dashoffset:0" + id="den_east_windows" + width="29.834251" + height="80.223137" + x="59.832874" + y="202.30617" + inkscape:label="Den - East Windows" /> + <rect + inkscape:label="Den - South Windows" + y="-580.9848" + x="118.72849" + height="80.223137" + width="29.834251" + id="den_south_windows" + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.665749;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.331498,0.665749,0.3328745,0.665749;stroke-dashoffset:0" + transform="matrix(-6.5451402e-3,0.9999786,-0.9999786,-6.5451402e-3,0,0)" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 440,482.36218 L 680,482.36218 L 680,622.36218 C 680,622.36218 440,622.36218 440,622.36218" + id="bathroom" + inkscape:label="Bathroom" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 440,632.36218 L 680,632.36218 L 680,992.36218 L 440,992.36218" + id="kitchen" + inkscape:label="Kitchen" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 230,962.36218 L 50,962.36218 L 50,732.36218 L 230,732.36218" + id="north_bedroom" + inkscape:label="North Bedroom" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 230,672.36218 L 50,672.36218 L 50,462.36218 L 50,452.36218 L 230,452.36218 L 230,452.36218" + id="south_bedroom" + inkscape:label="South Bedroom" /> + <rect + inkscape:label="South Bedroom Windows" + y="492.36218" + x="50" + height="80.223137" + width="29.834251" + id="south_bedroom_windows" + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.66574901;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.33149803,0.66574901,0.33287451,0.66574901;stroke-dashoffset:0" /> + <rect + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.66574901;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.33149803,0.66574901,0.33287451,0.66574901;stroke-dashoffset:0" + id="north_bedroom_windows" + width="29.834251" + height="80.223137" + x="50" + y="842.13904" + inkscape:label="North Bedroom Windows" /> + <rect + inkscape:label="Kitchen - South Windows" + y="662.36218" + x="650.16577" + height="80.223137" + width="29.834251" + id="kitchen_south_windows" + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.66574901;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.33149803,0.66574901,0.33287451,0.66574901;stroke-dashoffset:0" /> + <rect + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.66574901;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.33149803,0.66574901,0.33287451,0.66574901;stroke-dashoffset:0" + id="kitchen_north_windows" + width="29.834251" + height="80.223137" + x="650.16577" + y="842.36218" + inkscape:label="Kitchen - North Windows" /> + <rect + inkscape:label="Den - East Windows" + y="512.13904" + x="650.16577" + height="80.223137" + width="29.834251" + id="rect3259" + style="fill:none;fill-opacity:0.76785714999999999;stroke:#000000;stroke-width:0.66574901;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:1.33149803,0.66574901,0.33287451,0.66574901;stroke-dashoffset:0" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 200,822.36218 L 260,822.36218" + id="path3261" /> + <path + id="path3267" + d="M 200,892.36218 L 260,892.36218" + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 200,602.36218 L 260,602.36218" + id="path3269" /> + <path + id="path3271" + d="M 200,532.36218 L 260,532.36218" + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + <path + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" + d="M 410,522.36218 L 470,522.36218" + id="path3273" /> + <path + id="path3275" + d="M 410,592.36218 L 470,592.36218" + style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + <text + xml:space="preserve" + style="font-size:18.12547874px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + x="402.9361" + y="92.023323" + id="text3277" + transform="scale(0.8189884,1.2210185)"><tspan + sodipodi:role="line" + id="tspan3279" + x="402.9361" + y="92.023323">Back Door</tspan></text> + <text + transform="scale(0.8189884,1.2210185)" + id="text3281" + y="837.3028" + x="366.30554" + style="font-size:18.12547874px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + xml:space="preserve"><tspan + y="837.3028" + x="366.30554" + id="tspan3283" + sodipodi:role="line">Front Door</tspan></text> + <text + xml:space="preserve" + style="font-size:18.12547874px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + x="-1116.2377" + y="148.25552" + id="text3285" + transform="matrix(-8.0502581e-3,-0.8189488,1.2209595,-1.2002018e-2,0,0)"><tspan + sodipodi:role="line" + id="tspan3287" + x="-1116.2377" + y="148.25552">North Bedroom</tspan></text> + <text + transform="matrix(-4.295411e-3,-0.8189771,1.2210017,-6.4039691e-3,0,0)" + id="text3289" + y="152.93236" + x="-761.12207" + style="font-size:18.12547874px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + xml:space="preserve"><tspan + y="152.93236" + x="-761.12207" + id="tspan3291" + sodipodi:role="line">South Bedroom</tspan></text> + <text + xml:space="preserve" + style="font-size:19.11533165px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + x="602.89313" + y="-417.19034" + id="text3293" + transform="matrix(-1.4224842e-3,0.8637129,-1.1577882,-2.3587189e-3,0,0)"><tspan + sodipodi:role="line" + id="tspan3295" + x="602.89313" + y="-417.19034">Bathroom</tspan></text> + <text + transform="matrix(4.9164247e-3,0.9010032,-1.1098256,8.8717541e-3,0,0)" + id="text3297" + y="-428.7836" + x="839.01984" + style="font-size:19.94102669px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + xml:space="preserve" + inkscape:transform-center-x="80.06936" + inkscape:transform-center-y="111.8916"><tspan + y="-428.7836" + x="839.01984" + id="tspan3299" + sodipodi:role="line">Kitchen</tspan></text> + <text + transform="scale(0.7781854,1.2850408)" + id="text3301" + y="241.04301" + x="408.22031" + style="font-size:57.86774826px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" + xml:space="preserve"><tspan + y="241.04301" + x="408.22031" + sodipodi:role="line" + id="tspan3305">Den</tspan></text> + </g> + <script type="text/ecmascript" src="main.js"/> +</svg> diff --git a/apache/htdocs/main.js b/apache/htdocs/main.js new file mode 100644 index 0000000..fd23527 --- /dev/null +++ b/apache/htdocs/main.js @@ -0,0 +1,87 @@ +var svgNS = "http://www.w3.org/2000/svg"; + +ajaxSensorStatus = setInterval("loadXMLDoc('http://localhost/sensorStatus.json')", 5000); + +function createBadge(sensorId, sensorStatus) +{ + + var centerX = Math.abs(parseInt(document.getElementById(sensorId).getAttributeNS(null,"y"))); + var centerY = Math.abs(parseInt(document.getElementById(sensorId).getAttributeNS(null,"x"))); + var radius = 13; + + switch (sensorStatus) + { + case "normal": + fillColor="green"; + break; + case "alert": + fillColor="red"; + break; + default: + fillColor="black"; + } + + //create a new circle element and set the attributes + var circle = document.createElementNS(svgNS,"circle"); + circle.setAttributeNS(null,"id",fillColor + "Badge"); + circle.setAttributeNS(null,"cx",centerX); + circle.setAttributeNS(null,"cy",centerY); + circle.setAttributeNS(null,"r",radius); + circle.setAttributeNS(null,"fill",fillColor); + circle.setAttributeNS(null,"style","visibility:hidden;"); + + document.getElementById("layer1").appendChild(circle); + document.getElementById('layer1').setAttribute("transform", "scale(0.79)"); +} + +var xmlhttp; + +function loadXMLDoc(url) +{ + xmlhttp=null; + xmlhttp=new XMLHttpRequest(); + + if (xmlhttp!=null) + { + xmlhttp.onreadystatechange=state_Change; + xmlhttp.open("GET",url,true); + xmlhttp.send(null); + } + else + { + alert("Get Firefox, Tool!"); + window.location = "http://www.mozilla.com/firefox/"; + } +} + +function badgeStatus(sensorStatus) +{ + switch (sensorStatus) + { + case "normal": + document.getElementById('redBadge').style.visibility = 'hidden'; + document.getElementById('greenBadge').style.visibility = 'visible'; + break; + case "alert": + document.getElementById('greenBadge').style.visibility = 'hidden'; + document.getElementById('redBadge').style.visibility = 'visible'; + break; + default: + alert("Sensor Should NOT Be Sending A Status Of: " + sensorStatus); + } +} + + + +function state_Change() +{ + if (xmlhttp.readyState==4) + {// 4 = "loaded" + responseJSON = eval("(" + xmlhttp.responseText + ")"); + + sensorId = responseJSON.sensor.jsId; + sensorStatus = responseJSON.sensor.sensorStatus; + + badgeStatus(sensorStatus); + } +} diff --git a/xPL/SensorLookup.py b/xPL/SensorLookup.py new file mode 100644 index 0000000..f3ddda7 --- /dev/null +++ b/xPL/SensorLookup.py @@ -0,0 +1,90 @@ +import sqlite3 + +class Sensor: + try: + conn = sqlite3.connect('devices.db') + isConn = True + print "Connection to devices.db established" + except: + isConn = False + print "DB Connection Failed" + + def __init__(self): + pass + + def closeDBConn(self): + if self.isConn == True: + self.conn.close() + self.isConn = False + print "Connection object closed, no DB operations will work unless you sqlite3.connect(db) again." + else: + print "Connection Doesn't Exist" + + def getSingleSensor (self, sqlColumn = None, sqlValue = None): + if self.isConn == False: + print "You need a DB connection in order to get..." + return None + + if sqlColumn == 'type': + print "Use getSensorsOfType(type) function to get all " + sqlValue + " devices" + return None + + if sqlColumn != None and sqlValue != None: + c = self.conn.cursor() + queryParams = (sqlValue,) + query = "select * from sensors where " + sqlColumn + " = ?" + c.execute(query, queryParams) + + resultSet = [] + returnRS = {} + + for row in c: + resultSet.append(row) + + + if len(resultSet) == 1: + returnRS['id'] = resultSet[0][0] + returnRS['hexid'] = resultSet[0][1] + returnRS['name'] = resultSet[0][2] + returnRS['type'] = resultSet[0][3] + + return returnRS + else: + print "Wrong number of records returned (0 or more than 1)" + return None + + else: + print "You didn't pass the column and/or value" + return None + + def getSensorsOfType(self, sensorType): + if self.isConn == False: + print "You need a DB connection in order to get..." + return None + + if sensorType != None: + c = self.conn.cursor() + queryParams = (sensorType,) + + if sensorType == "all" or sensorType == "ALL": + query = "select * from sensors" + c.execute(query) + else: + query = "select * from sensors where type = ?" + c.execute(query, queryParams) + + resultSet = [] + for row in c: + resultSet.append(row) + + if len(resultSet) == 0: + print "0 records returned" + return None + else: + print str(len(resultSet)) + " record(s) returned" + return resultSet + + else: + print "You didn't pass the column and/or value" + return None + diff --git a/xPL/devices.db b/xPL/devices.db new file mode 100644 index 0000000..fb1df2f Binary files /dev/null and b/xPL/devices.db differ diff --git a/xPL/setups/linux/ftdi_sio.tar.gz b/xPL/setups/linux/ftdi_sio.tar.gz new file mode 100644 index 0000000..497a796 Binary files /dev/null and b/xPL/setups/linux/ftdi_sio.tar.gz differ diff --git a/xPL/setups/linux/rfxcom_drivers.README b/xPL/setups/linux/rfxcom_drivers.README new file mode 100644 index 0000000..7b2a738 --- /dev/null +++ b/xPL/setups/linux/rfxcom_drivers.README @@ -0,0 +1,7 @@ +http://www.ftdichip.com/Drivers/VCP.htm: + + Required for FT2232H and FT4232H support. + Required for 2.4 kernels that require FT2232 support. FT2232 support included in kernel 2.6.9 or greater. Developed by Bill Ryder. Instructions in ReadMe file. + + All other devices included in kernel 2.4.20 or greater (see ReadMe for 232R device support). + diff --git a/xPL/setups/windows/windows.zip b/xPL/setups/windows/windows.zip new file mode 100644 index 0000000..56634d3 Binary files /dev/null and b/xPL/setups/windows/windows.zip differ diff --git a/xPL/xplhub.pl b/xPL/xplhub.pl new file mode 100644 index 0000000..b0b82ab --- /dev/null +++ b/xPL/xplhub.pl @@ -0,0 +1,165 @@ +#!/usr/bin/perl +################################################################################ +# +# xPL Hub for Perl +# +# Version 1.1 +# +# Copyright (C) 2003 John Bent +# http://www.xpl.myby.co.uk/ +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# Linking this library statically or dynamically with other modules is +# making a combined work based on this library. Thus, the terms and +# conditions of the GNU General Public License cover the whole +# combination. +# As a special exception, the copyright holders of this library give you +# permission to link this library with independent modules to produce an +# executable, regardless of the license terms of these independent +# modules, and to copy and distribute the resulting executable under +# terms of your choice, provided that you also meet, for each linked +# independent module, the terms and conditions of the license of that +# module. An independent module is a module which is not derived from +# or based on this library. If you modify this library, you may extend +# this exception to your version of the library, but you are not +# obligated to do so. If you do not wish to do so, delete this +# exception statement from your version. +# +################################################################################ +use strict; +use warnings; + +use IO::Socket; +use IO::Select; +use Sys::Hostname; + +my ( + $foundport, + $xpl_socket, + $msg, + $fromaddr, + @localaddr +); + +my %hubs = (); + + +sub broadcastMessage { + my $ipaddr = inet_aton('127.0.0.1'); + my $portaddr = sockaddr_in($_[1], $ipaddr); + my $sockUDP = IO::Socket::INET->new(PeerPort => $_[1], + Proto => 'udp' + ); + if (!defined($sockUDP)) { + print "Error sending xPL message to port $_[1].\n"; + return; + } + $sockUDP->autoflush(1); + $sockUDP->sockopt(SO_BROADCAST,1); + $sockUDP->send($_[0],0,$portaddr); + close $sockUDP; +} + +sub getparam { +# Retrieves a parameter from the body of an xPL message + my $buff = $_[0]; + $buff = substr($buff,index($buff,"}"),length($buff)-index($buff,"}")); + $buff = substr($buff,index($buff,"{")+2,length($buff)-index($buff,"{")-2); + $buff = substr($buff,0,index($buff,"}")-1); + my %params = map { split /=/, $_, 2 } split /\n/, $buff ; + return $params{$_[1]}; +} + +sub gethdrparam { +# Retrieves a parameter from the header of an xPL message + my $buff = $_[0]; + $buff = substr($buff,index($buff,"{")+2,length($buff)-index($buff,"{")-2); + $buff = substr($buff,0,index($buff,"}")-1); + my %params = map { split /=/, $_, 2 } split /\n/, $buff ; + return $params{$_[1]}; +} + +sub getmsgtype { +# Returns the type of an xPL message, e.g. xpl-stat, xpl-trig or xpl-cmnd + return lc substr($_[0],0,8); +} + +sub getmsgschema { +# This routine accepts an xPL message and returns the message schema, in lowercase characters + my $buff = $_[0]; + $buff = substr($buff,index($buff,"}")+2,length($buff)-index($buff,"}")-2); + $buff = substr($buff,0,index($buff,"\n")); + return lc $buff; +} + +sub getlocalips { + my $hostname = Sys::Hostname::hostname(); + my($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($hostname); + return @addrs; +} + +sub isMessageLocal { + foreach my $ip (@localaddr) { + if ($ip eq $_[0]) { + return 1; + } + } + return 0; +} + + + +$xpl_socket = IO::Socket::INET->new( + Proto => 'udp', + LocalPort => 3865, +); + +die "The hub could not bind to port 3865. Make sure you are not already running an xPL hub.\n" unless $xpl_socket; + +# Get all local IP addresses +@localaddr = getlocalips(); + +print "xPL Hub for Perl (version 1.0) ready.\n\n"; + +while (defined($xpl_socket)) { + $fromaddr = recv($xpl_socket,$msg,1500,0); + my($port, $ipaddr) = sockaddr_in($fromaddr); + # Check for heartbeat/config message + if (getmsgtype($msg) eq 'xpl-stat' && getmsgschema($msg) =~ "^(config\.(app|end))|(hbeat\.(app|end))") { + # Is the message local? + if (isMessageLocal($ipaddr)) { + $port = getparam($msg,"port"); + # If we've not got it, then add it + if (!defined($hubs{$port})) { + $hubs{$port} = gethdrparam($msg,"source"); + print "xPL process $hubs{$port} detected on port $port.\n"; + } + elsif (getmsgschema($msg) =~ "^(config\.end)|(hbeat\.end)") { + # Device is shutting down, so remove it + delete $hubs{$port}; + } + + } + } + # Broadcast the message to all listening ports + foreach my $hub (keys %hubs) { + broadcastMessage($msg,$hub); + } +} + +close($xpl_socket); + +1; diff --git a/xPL/xplpython.py b/xPL/xplpython.py new file mode 100644 index 0000000..a68c33f --- /dev/null +++ b/xPL/xplpython.py @@ -0,0 +1,82 @@ +from socket import * +from SensorLookup import Sensor +import re,select,sys +import json +import urllib + +message_buffer = 1500 +messageDict = {} +jsonRequest = {} +xpl_port = 50002 +computername = gethostname() +xpl_ip = gethostbyname(gethostname()) +xpl_instance = "monitor." + computername +UDPSock = socket(AF_INET,SOCK_DGRAM) +addr = ("0.0.0.0",xpl_port) + +def validInstance (computername): + newComputerName = re.sub('(-|\.|!|;)', '', computername) + newComputerName = newComputerName[:16] + return newComputerName + +def sendxplmsg (msgType='xpl-stat', source='mikesha.monitor', target='*', appName='hbeat.app', interval=5, port=50002): + hbSock = socket(AF_INET,SOCK_DGRAM) + hbSock.setsockopt(SOL_SOCKET,SO_BROADCAST,1) + msg = msgType + "\n{\nhop=1\nsource=" + source + "\ntarget=" + target + "\n}\n" + appName + "\n{\ninterval=" + str(interval) + "\nport=" + str(port) + "\n}\n" + hbSock.sendto(msg,("255.255.255.255",3865)) + +computername = validInstance(computername) + +try : + UDPSock.bind(addr) +except : + xpl_port = 50000 + addr = (xpl_ip,xpl_port) + + try : + UDPSock.bind(addr) + except : + xpl_port += 1 + +print "xPL Monitor bound to port: " + str(xpl_port) + +sendxplmsg(port=xpl_port) + +while UDPSock : + readable, writeable, errored = select.select([UDPSock],[],[],60) + + if len(readable) == 1 : + data,addr = UDPSock.recvfrom(message_buffer) + messageArray = data.splitlines() + try: + for msgLine in messageArray: + if msgLine == '{': + messageArray.remove(msgLine) + elif msgLine == '}': + messageArray.remove(msgLine) + except: + print "No Curly Braces To Remove" + + if messageArray[0] == 'xpl-trig': + for msgLine in messageArray: + if msgLine.find('=') != -1: + kvArray = msgLine.partition('=') + messageDict[kvArray[0]] = kvArray[2] + + deviceId = re.match('([a-z|A-Z]+.*[0-9]+.*).([0-9]+[a-z]+)', messageDict['device']) + sensorType = deviceId.group(1) + sensorHexId = deviceId.group(2) + + sensor = Sensor() + ds10a = sensor.getSingleSensor('id',1) + + + if messageDict['command'] == 'alert': + jsonRequest = {'jsId': ds10a['name'], 'sensorStatus': 'alert'} + print "Sensor (Type:" + sensorType + ", ID: " + sensorHexId + ") is reporting its status as: OPEN" + if messageDict['command'] == 'normal': + jsonRequest = {'jsId': ds10a['name'], 'sensorStatus': 'normal'} + print "Sensor (Type:" + sensorType + ", ID: " + sensorHexId + ") is reporting its status as: CLOSED" + + # send http-post + request = urllib.urlopen("http://localhost/cgi-bin/acceptJSON.cgi", urllib.urlencode(jsonRequest))
Chabela/controlador-de-tiempo-II-Avance
320df69bda6b4387c9a483844a0c9544e82296a4
second commit
diff --git a/README b/README new file mode 100644 index 0000000..e69de29 diff --git a/creandofiltro.py b/creandofiltro.py new file mode 100644 index 0000000..a21a5b4 --- /dev/null +++ b/creandofiltro.py @@ -0,0 +1,32 @@ +import panta +import sys +import os +import time +try: + import pygtk + require('2.0') +except: + pass +try: + import gtk + from gtk import glade + +except: + print "no tienes el modulo instalado" + time.sleep(2) + sys.exit(1) + +def ventanaaviso(tiempo): + ventana=gtk.Window(gtk.WINDOW_TOPLEVEL) + ventana.resize(200,200) + fijo=gtk.Fixed() + etiqueta=gtk.Label(tiempo) + etiqueta.show() + boton=gtk.Button() + boton.show() + fijo.add(boton) + ventana.add(fijo) + ventana.show() + print "ya" + +ventanaaviso(2) diff --git a/evoluciongeek.PNG b/evoluciongeek.PNG new file mode 100644 index 0000000..829e723 Binary files /dev/null and b/evoluciongeek.PNG differ diff --git a/executando.py b/executando.py new file mode 100644 index 0000000..3bd6c9b --- /dev/null +++ b/executando.py @@ -0,0 +1,59 @@ +import panta +import sys +import os +import time +try: + import pygtk + require('2.0') +except: + pass +try: + import gtk + from gtk import glade + +except: + print "no tienes el modulo instalado" + time.sleep(2) + sys.exit(1) + +class time: + + def __init__(self): + + self.gladefile="tiempo.glade" + self.conjuntos=gtk.glade.XML(self.gladefile) + self.ventanaIngreso=self.conjuntos.get_widget("VentanaPrincipal") + self.ventanaAviso=self.conjuntos.get_widget("ventanaaviso") + self.diccionario={"on_BotonEnvio_clicked":self.on_BotonEnvio_clicked, + "on_botonojo_clicked":self.on_botonojo_clicked} + self.conjuntos.signal_autoconnect(self.diccionario) + self.ingresoTiempo=self.conjuntos.get_widget("EntradaDeTiempo") +## def ventanaaviso(self,tiempo): +## self.ventana=gtk.Window(gtk.POPUT) +## self.etiqueta=gtk.Label(tiempo) +## self.etiqueta.show() +## self.boton=gtk.Button(self.etiqueta) +## self.boton.show() +## self.ventana.add(self.boton) +## self.ventana.show() + + def on_BotonEnvio_clicked(self,widget): + self.ventanaIngreso.destroy() + import time + while gtk.events_pending(): + gtk.main_iteration() + tiempo=self.ingresoTiempo.get_text() + tiempo=int(tiempo) + time.sleep(tiempo) + print tiempo + panta.p() + def on_botonojo_clicked(self,widget): + print "adios" + + def on_BotonAdmin_clicked(self,widget): + self.ventanaSuspension.destroy() + + +if __name__=="__main__": + timetime=time() + gtk.main() diff --git a/geeks.PNG b/geeks.PNG new file mode 100644 index 0000000..25f6cb4 Binary files /dev/null and b/geeks.PNG differ diff --git a/imagenes.py b/imagenes.py new file mode 100644 index 0000000..811d2bd --- /dev/null +++ b/imagenes.py @@ -0,0 +1,10 @@ +import time + +tiempo=2 +while tiempo<20: + lista=["imagenes/ubuntu1.jpg","imagenes/ubuntu2.jpg","imagenes/ubuntu3.jpg","imagenes/ubuntu4.jpg","imagenes/ubuntufinal.png"] + aleatorio=random.randrange(1,len(lista)) + fondex=lista[aleatorio] + print fondex + time.sleep(2) + tiempo+=2 diff --git a/imagenes/logo.png b/imagenes/logo.png new file mode 100644 index 0000000..bcda4ea Binary files /dev/null and b/imagenes/logo.png differ diff --git a/imagenes/pantallon.py b/imagenes/pantallon.py new file mode 100644 index 0000000..e618c52 --- /dev/null +++ b/imagenes/pantallon.py @@ -0,0 +1,52 @@ +import time +import pygame +from pygame.locals import * + + +class protectordepantalla: + def __init__(self): + self.imagen = pygame.image.load("imagenes/logo.png").convert_alpha() + self.ver = self.imagen.get_rect() + self.ver.move_ip(100,100) + def tecla(self): + self.teclas=pygame.key.get_pressed() + if self.teclas[K_SPACE]: + pygame.quit() + + + + +salir=False +protectores = pygame.display.set_mode((560,840),pygame.FULLSCREEN) +pygame.display.set_caption('Protector de pantallas') + +#cargamos una imagen +#convertimo (convert_alpha) la superficie creada por load a u formato de color que permite imprimirrla mucho mas rapidas sobre la pantalla +logotipo=pygame.image.load('imagenes/ubuntu.PNG').convert_alpha() +protectores.blit(logotipo,(0,0)) +#se muestra los cambios en la pantalla +pygame.display.flip() + +# objetos +temporizador = pygame.time.Clock() +protectores = protectordepantalla() + +while not salir: + protectordepantalla.tecla() + + # actualizacion grafica + protectores.blit(fondo, (0, 0)) + protectores.blit(protectores.imagen, protectores.ver) + pygame.display.flip() + + temporizador.tick(60) + # gestion de eventos + for evento in pygame.event.get(): + if evento.type == pygame.QUIT: + salir = True + +protecto() +#esperemos que cierre la ventana +pygame.event.set_allowed(None) +pygame.event.set_allowed(pygame.QUIT) +pygame.event.wait() diff --git a/imagenes/puntero.png b/imagenes/puntero.png new file mode 100644 index 0000000..4388740 Binary files /dev/null and b/imagenes/puntero.png differ diff --git a/imagenes/ubuntu1.png b/imagenes/ubuntu1.png new file mode 100644 index 0000000..8e04b6f Binary files /dev/null and b/imagenes/ubuntu1.png differ diff --git a/imagenes/ubuntu2.png b/imagenes/ubuntu2.png new file mode 100644 index 0000000..cff76dc Binary files /dev/null and b/imagenes/ubuntu2.png differ diff --git a/imagenes/ubuntu3.png b/imagenes/ubuntu3.png new file mode 100644 index 0000000..54c44d4 Binary files /dev/null and b/imagenes/ubuntu3.png differ diff --git a/imagenes/ubuntu4.png b/imagenes/ubuntu4.png new file mode 100644 index 0000000..4bd4737 Binary files /dev/null and b/imagenes/ubuntu4.png differ diff --git a/imagenes/ubuntufinal.png b/imagenes/ubuntufinal.png new file mode 100644 index 0000000..6f112be Binary files /dev/null and b/imagenes/ubuntufinal.png differ diff --git a/panta.py b/panta.py new file mode 100644 index 0000000..e0fd779 --- /dev/null +++ b/panta.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +import gtk +import pygame +import random +import time +from pygame.locals import * +from pygame.sprite import Sprite +import os, sys + + +class protectordepantalla(Sprite): + + def __init__(self): + self.image = pygame.image.load("imagenes/puntero.png").convert_alpha() + self.rect = self.image.get_rect() + self.rect.move_ip(0, 0) + + def update(self): + teclas = pygame.key.get_pressed() + if teclas[K_SPACE]: + pygame.quit() + + + +def p(): + salir = False + + # creacion de la ventana + screen = pygame.display.set_mode((640, 480)) + pygame.display.set_caption("Protector de Pantalla") + tiempo=2 + while tiempo<10: + + lista=["imagenes/ubuntu1.png","imagenes/ubuntu2.png","imagenes/ubuntu3.png","imagenes/ubuntu4.png","imagenes/ubuntufinal.png"] + + aleatorio=random.randrange(1,len(lista)) + + + fondex=lista[aleatorio] + print fondex + fondo = pygame.image.load(fondex).convert() + logotipo = pygame.image.load("imagenes/logo.png").convert_alpha() + fondo.blit(logotipo, (500, 340)) + tiempo+=2 + + + + + # objetos + temporizador = pygame.time.Clock() + protege = protectordepantalla() + + while not salir: + protege.update() + + # actualizacion grafica + sys.stdout.write(os.popen('clear').read()) + screen.blit(fondo, (1,1)) + screen.blit(protege.image, protege.rect) + pygame.display.flip() + + temporizador.tick(10) + # gestion de eventos + for evento in pygame.event.get(): + if evento.type == pygame.QUIT: + salir = True + + diff --git a/panta.pyc b/panta.pyc new file mode 100644 index 0000000..0981c0d Binary files /dev/null and b/panta.pyc differ diff --git a/tiempo.glade b/tiempo.glade new file mode 100644 index 0000000..53501c4 --- /dev/null +++ b/tiempo.glade @@ -0,0 +1,215 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> +<!--Generated with glade3 3.4.3 on Tue Apr 13 16:42:41 2010 --> +<glade-interface> + <widget class="GtkWindow" id="VentanaPrincipal"> + <property name="width_request">250</property> + <property name="height_request">250</property> + <property name="visible">True</property> + <property name="title" translatable="yes">Tiempo Py</property> + <signal name="destroy" handler="on_VentanaPrincipal_destroy"/> + <child> + <widget class="GtkFixed" id="fixed1"> + <property name="visible">True</property> + <child> + <widget class="GtkImage" id="image1"> + <property name="width_request">259</property> + <property name="height_request">250</property> + <property name="visible">True</property> + <property name="pixbuf">evoluciongeek.PNG</property> + </widget> + </child> + <child> + <widget class="GtkLabel" id="EtiquetaPrincipal"> + <property name="width_request">129</property> + <property name="height_request">36</property> + <property name="visible">True</property> + <property name="label" translatable="yes">control</property> + </widget> + <packing> + <property name="x">62</property> + <property name="y">25</property> + </packing> + </child> + <child> + <widget class="GtkLabel" id="etiquetaTiempo"> + <property name="width_request">90</property> + <property name="height_request">36</property> + <property name="visible">True</property> + <property name="label" translatable="yes">Tiempo</property> + </widget> + <packing> + <property name="x">23</property> + <property name="y">140</property> + </packing> + </child> + <child> + <widget class="GtkEntry" id="EntradaDeTiempo"> + <property name="width_request">96</property> + <property name="height_request">33</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="has_frame">False</property> + <property name="shadow_type">GTK_SHADOW_OUT</property> + </widget> + <packing> + <property name="x">126</property> + <property name="y">145</property> + </packing> + </child> + <child> + <widget class="GtkButton" id="BotonEnvio"> + <property name="width_request">96</property> + <property name="height_request">51</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="label" translatable="yes">gtk-execute</property> + <property name="use_stock">True</property> + <property name="response_id">0</property> + <signal name="clicked" handler="on_BotonEnvio_clicked"/> + </widget> + <packing> + <property name="x">127</property> + <property name="y">194</property> + </packing> + </child> + </widget> + </child> + </widget> + <widget class="GtkWindow" id="VentanaSuspension"> + <property name="extension_events">GDK_EXTENSION_EVENTS_ALL</property> + <property name="type">GTK_WINDOW_POPUP</property> + <property name="title" translatable="yes">Tiempo Admin</property> + <signal name="destroy" handler="on_VentanaSuspension_destroy"/> + <child> + <widget class="GtkFixed" id="fixed2"> + <property name="visible">True</property> + <child> + <widget class="GtkLabel" id="EtiquetaAdminPrincipal"> + <property name="width_request">100</property> + <property name="height_request">43</property> + <property name="visible">True</property> + <property name="label" translatable="yes">Administrador</property> + </widget> + <packing> + <property name="x">300</property> + <property name="y">230</property> + </packing> + </child> + <child> + <widget class="GtkLabel" id="EtiquetaAdminUser"> + <property name="width_request">87</property> + <property name="height_request">28</property> + <property name="visible">True</property> + <property name="label" translatable="yes">Admin</property> + </widget> + <packing> + <property name="x">218</property> + <property name="y">315</property> + </packing> + </child> + <child> + <widget class="GtkLabel" id="EtiquetaAdminClave"> + <property name="width_request">78</property> + <property name="height_request">28</property> + <property name="visible">True</property> + <property name="label" translatable="yes">Clave</property> + </widget> + <packing> + <property name="x">225</property> + <property name="y">391</property> + </packing> + </child> + <child> + <widget class="GtkEntry" id="EntradaAdminClave"> + <property name="width_request">100</property> + <property name="height_request">29</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + </widget> + <packing> + <property name="x">340</property> + <property name="y">390</property> + </packing> + </child> + <child> + <widget class="GtkEntry" id="EntradaAdminUser"> + <property name="width_request">100</property> + <property name="height_request">29</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + </widget> + <packing> + <property name="x">339</property> + <property name="y">314</property> + </packing> + </child> + <child> + <widget class="GtkButton" id="BotonAdmin"> + <property name="width_request">94</property> + <property name="height_request">38</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="label" translatable="yes">gtk-ok</property> + <property name="use_stock">True</property> + <property name="response_id">0</property> + <signal name="clicked" handler="on_BotonAdmin_clicked"/> + </widget> + <packing> + <property name="x">395</property> + <property name="y">472</property> + </packing> + </child> + <child> + <widget class="GtkImage" id="image2"> + <property name="width_request">105</property> + <property name="height_request">212</property> + <property name="visible">True</property> + <property name="pixbuf">geeks.PNG</property> + </widget> + <packing> + <property name="x">494</property> + <property name="y">218</property> + </packing> + </child> + </widget> + </child> + </widget> + <widget class="GtkWindow" id="ventanaaviso"> + <property name="type">GTK_WINDOW_POPUP</property> + <signal name="destroy" handler="on_ventanaaviso_destroy"/> + <child> + <widget class="GtkFixed" id="fixed3"> + <property name="visible">True</property> + <child> + <widget class="GtkButton" id="botonojo"> + <property name="width_request">159</property> + <property name="height_request">43</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="label" translatable="yes">button</property> + <property name="response_id">0</property> + <signal name="clicked" handler="on_botonojo_clicked"/> + </widget> + <packing> + <property name="x">9</property> + <property name="y">93</property> + </packing> + </child> + <child> + <widget class="GtkLabel" id="label1"> + <property name="width_request">108</property> + <property name="height_request">26</property> + </widget> + <packing> + <property name="x">41</property> + <property name="y">51</property> + </packing> + </child> + </widget> + </child> + </widget> +</glade-interface> diff --git a/uubuntu2.jpg b/uubuntu2.jpg new file mode 100644 index 0000000..2547d80 Binary files /dev/null and b/uubuntu2.jpg differ diff --git a/uubuntu3.jpg b/uubuntu3.jpg new file mode 100644 index 0000000..161fc1c Binary files /dev/null and b/uubuntu3.jpg differ
jalkanen/Priha
d9db4fc8765a89a5142250a8fade9b9934d0ba2b
Ignoring Jackrabbit artifacts.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1658dd0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/repository +/repository.xml
jalkanen/Priha
fc3eaeb5ece52b012e8b6f3d01a96b2a85ef5130
Added info on compilation.
diff --git a/README b/README index 24e6054..4d76cfb 100644 --- a/README +++ b/README @@ -1,76 +1,93 @@ This is Priha, a JSR-170 Java Content Repository implementation. Unlike the all-singing, all-dancing, fully CRM-certified implementations, Priha is targeted at small applications, embedders and hobbyists, who like to have a simple repository model with as few external dependencies as possible. You can start off with Priha, and then just simply switch to a more efficient solution (like Jackrabbit) once you start to need the performance / reliability. The word "priha" is an ancient Finnish word and it roughly means a "young man". It is not in common use these days, except as an idiom "ylen sankia priha" ("a very chubby young man"). Which, if you ever were to use it correctly in the presence of a Finnish person, would probably get you a free beer and plenty of questions. GOALS ===== The goals of the project are: * Provide a "good enough" implementation to ship with JSPWiki 3.0. * Optimize for fast fetching of medium-sized text objects (i.e. wikipages) * Good storage of large binaries (i.e. attachments) * Provide integrated versioning * Provide an SPI so that different types of providers can be used without hiding the JSR structure to something which cannot be understood by a mortal man. * Provide an SPI so powerful that JSPWiki can be easily migrated and keep the existing clarity of its Providers. * Scalability up to medium size systems (200 wikis, each with 2000 pages, total of 400,000 nodes). * Ships with as few external libraries as possible The anti-goals (i.e. the things I don't particularly want to pay attention to, because they are not useful (yet) in JSPWiki context) are: * Transactions support * HA or clustering support. These should be left to an industrial-scale JSR implementation. * JNDI * Custom Nodetypes REQUIREMENTS ============ Priha requires and takes advantage of Java 5 (JDK 1.5). To compile and run the JCR tests you need the included libraries. To run Priha, you need: * a JAXP-compliant XML parser library somewhere in your classpath (the one with JDK5 is fine) * jcr-1.0.jar somewhere in the classpath as well That's it! See doc/Configuration.txt for further information about how Priha is configured. + +COMPILATION +=========== + +Priha uses Apache Ant to compile, and Apache Ivy for managing dependencies. Ivy will +be downloaded automatically if you don't have it already installed. + +To compile, run "ant". This creates the JAR file under /build. + +To run the full test suite, run "ant jcrtests". This will create a test report in +/tests/reports. + +If you use Eclipse, the use of IvyDE is highly recommended. Otherwise you will need +to install the dependencies manually with Ant first, then tweak the classpath within +Eclipse. + + LICENSE ======= Priha is licensed under the Apache 2.0 license. Please see the LICENSE file in the same directory as this document.
jalkanen/Priha
28bada78f2b610820719311b3a9ff87fa41a1c40
Bumped version to 0.7.6 - partly to test GitHub integration.
diff --git a/ChangeLog b/ChangeLog index 9a46e61..108a450 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,519 @@ +2010-04-21 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.7.6 + + * Changed configuration to use Apache Ivy and moved project source + code repo to GitHub. + 2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.5 * Fixed a number of memory leaks. 2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.4 * The "I think I optimized something but I've got a flu" -release. * Session Item cache is now configurable (and slightly bigger by default) * SessionProvider.itemExists() is now slightly smarter when checking for cached items. * Allowed overriding priha.properties from system properties. 2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.3 * Optimization of ProviderManager.loadNode() and Item.enterState(). Especially the latter helps reading quite a lot. * EhCacheProvider.exists() was confusing Nodes with Properties sometimes. * ObservationManager now correctly sends events for Node reordering. 2010-01-04 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.2 * Implemented Observation. It does not *quite* work yet, but it's only nine errors until TCK pass. 2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> * Fixed XML import tests for versioning by properly checking for checked-in Nodes in XMLImport. You may test Versioning, but the TCK tests are disabled. You can turn them on by editing Release.DESCRIPTORS and setting Repository.OPTION_VERSIONING_SUPPORTED to STR_TRUE. * 0.7.1 * FileProvider speedup - added internal cache for mangleName(). 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 3615355..2f7c294 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ - public static final int MINORREVISION = 5; + public static final int MINORREVISION = 6; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_TRUE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } }
jalkanen/Priha
34d41b3c27988088a4f945f56083814ba7b896e3
Added JCR dependency; fixed ivy stuff to go under lib/ivy so as not to confuse everything.
diff --git a/.classpath b/.classpath index 82b92ab..4d3a702 100644 --- a/.classpath +++ b/.classpath @@ -1,19 +1,18 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src/java"/> <classpathentry kind="src" path="tests/java"/> <classpathentry kind="src" path="tests/tck"/> <classpathentry kind="src" path="src/generated-sources"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3.8.1"/> <classpathentry exported="true" kind="lib" path="tests/etc"/> <classpathentry kind="lib" path="etc"/> - <classpathentry kind="lib" path="lib/jcr-1.0.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="lib" path="lib/hector-0.6.0-10.jar"/> <classpathentry kind="lib" path="lib/libthrift-r917130.jar"/> <classpathentry kind="lib" path="lib/apache-cassandra-0.6.0-rc1.jar"/> <classpathentry kind="lib" path="tests/lib/high-scale-lib.jar"/> <classpathentry kind="lib" path="tests/lib/clhm-production.jar"/> <classpathentry kind="con" path="org.apache.ivyde.eclipse.cpcontainer.IVYDE_CONTAINER/?ivyXmlPath=ivy.xml&amp;confs=*"/> <classpathentry kind="output" path="build"/> </classpath> diff --git a/build.xml b/build.xml index 4de4899..89fd634 100644 --- a/build.xml +++ b/build.xml @@ -1,401 +1,393 @@ <?xml version="1.0"?> <!-- Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project name="Priha" default="jar" xmlns:ivy="antlib:org.apache.ivy.ant"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> - <include name="*.jar" /> + <include name="**/*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> - - <!-- Jackrabbit is only included if it has been installed with maven --> - <fileset dir="${user.home}"> - <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> - <include name=".m2/repository/commons-collections/**/*3.2.jar"/> - <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> - <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> - </fileset> </path> <!-- ================================= target: resolve ================================= --> <target name="resolve" description="--> retrieve dependencies with ivy" depends="init-ivy"> - <ivy:retrieve /> + <ivy:retrieve pattern="lib/ivy/[type]/[artifact]-[revision].[ext]" sync="true"/> </target> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile" depends="resolve"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> <src path="src/java"/> <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> <src path="tests/java"/> <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> <delete dir="tests/build"/> </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> <!-- ***************************************************************** --> <!-- Distribution package building. Use "ant dist" to build the distro package, and "ant srczip" to create a source tarball. --> <target name="srczip" depends="compile"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-src.zip"> <zipfileset dir="." excludes="build/** tests/build/** repository*/** tests/reports/** *.log doc/javadoc/**" prefix="priha-${version}"/> </zip> </target> <target name="dist" depends="jar,javadoc"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-bin.zip"> <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> <zipfileset dir="." includes="ChangeLog README LICENSE NOTICE doc/**" prefix="priha-${version}"/> <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> <zipfileset dir="lib" includes="ehcache-*.jar hsqldb-*.jar" prefix="priha-${version}/extras-lib"/> </zip> </target> <!-- Installs the distribution archives by checking out the SVN project. Needs svn and gpg binaries in the shell path. --> <target name="dist-install" depends="srczip,dist"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <!-- Check out code --> <exec executable="svn"> <arg value="co"/> <arg value="https://svn.ecyrd.com/repos/priha/site"/> <arg value="build/priha-site"/> </exec> <!-- Install archives --> <property name="destdir" value="build/priha-site/WebContent/download/priha-${version}"/> <delete dir="${destdir}"/> <mkdir dir="${destdir}"/> <copy file="build/priha-${version}-bin.zip" todir="${destdir}"/> <copy file="build/priha-${version}-src.zip" todir="${destdir}"/> <exec executable="gpg"> <arg value="-sba"/> <arg value="${destdir}/priha-${version}-src.zip"/> </exec> <exec executable="gpg"> <arg value="-sba"/> <arg value="${destdir}/priha-${version}-bin.zip"/> </exec> <!-- Figure out file lengths. We need a bit of Javascript to build the sizes in megabytes --> <length file="build/priha-${version}-bin.zip" property="binsize"/> <length file="build/priha-${version}-src.zip" property="srcsize"/> <script language="javascript"> <![CDATA[ var binsize = project.getProperty("binsize"); var srcsize = project.getProperty("srcsize"); var binmegas = Math.round((binsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); var srcmegas = Math.round((srcsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); project.setNewProperty("binsizemegs", binmegas); project.setNewProperty("srcsizemegs", srcmegas); ]]> </script> <!-- Modify page --> <loadfile property="message" srcFile="build/priha-site/downloadmessage.html"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens"> <param type="token" name="srcurl" value="download/priha-${version}/priha-${version}-src.zip"/> <param type="token" name="binurl" value="download/priha-${version}/priha-${version}-bin.zip"/> <param type="token" name="version" value="${version}"/> <param type="token" name="srcsize" value="${srcsizemegs}"/> <param type="token" name="binsize" value="${binsizemegs}"/> </filterreader> </filterchain> </loadfile> <replaceregexp file="build/priha-site/WebContent/download.html" flags="gs" match="&lt;!-- STARTMAGIC -->(.*)&lt;!-- ENDMAGIC -->" replace="&lt;!-- STARTMAGIC -->${message}&lt;!-- ENDMAGIC -->"/> <echo> OK, I'm done. Please examine the contents of build/priha-site/WebContent/download.html prior to checking in the code with "svn commit". </echo> </target> <!-- This set of properties installs Apache Ivy --> <property name="ivy.install.version" value="2.1.0" /> <condition property="ivy.home" value="${env.IVY_HOME}"> <isset property="env.IVY_HOME" /> </condition> <property name="ivy.home" value="${user.home}/.ant" /> <property name="ivy.jar.dir" value="${ivy.home}/lib" /> <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" /> <target name="download-ivy" unless="offline"> <mkdir dir="${ivy.jar.dir}"/> <!-- download Ivy from web site so that it can be used even without any special installation --> <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" dest="${ivy.jar.file}" usetimestamp="true"/> </target> <target name="init-ivy" depends="download-ivy"> <!-- try to load ivy here from ivy home, in case the user has not already dropped it into ant's lib dir (note that the latter copy will always take precedence). We will not fail as long as local lib dir exists (it may be empty) and ivy is in at least one of ant's lib dir or the local lib dir. --> <path id="ivy.lib.path"> <fileset dir="${ivy.jar.dir}" includes="*.jar"/> </path> <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/> </target> </project> diff --git a/ivy.xml b/ivy.xml index 4dffca7..6398923 100644 --- a/ivy.xml +++ b/ivy.xml @@ -1,61 +1,65 @@ <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd"> <info organisation="priha.org" module="priha" status="integration"> </info> <dependencies> + <dependency org="javax.jcr" name="jcr" rev="1.0"/> + <!-- These are for Cassandra deployment --> <dependency org="org.perf4j" name="perf4j" rev="0.9.12"/> <dependency org="commons-lang" name="commons-lang" rev="2.4"/> <dependency org="commons-collections" name="commons-collections" rev="3.2.1"/> <dependency org="com.googlecode.json-simple" name="json-simple" rev="1.1"/> <dependency org="log4j" name="log4j" rev="1.2.14"/> <dependency org="commons-pool" name="commons-pool" rev="1.5.3"/> <dependency org="com.google.collections" name="google-collections" rev="1.0"/> <!-- Other dependencies --> <dependency org="javax.servlet" name="servlet-api" rev="2.4"/> <dependency org="net.sf.ehcache" name="ehcache" rev="1.6.2"/> <dependency org="concurrent" name="concurrent" rev="1.3.4"/> <!-- Doug Lea's --> <dependency org="org.slf4j" name="slf4j-api" rev="1.5.3"/> <dependency org="org.slf4j" name="slf4j-simple" rev="1.5.3"/> + <dependency org="org.apache.jackrabbit" name="jackrabbit-core" rev="1.6.1"/> + <!-- The versions don't matter probably much. --> <dependency org="hsqldb" name="hsqldb" rev="1.8.0.10"/> <dependency org="com.h2database" name="h2" rev="1.1.118"/> <!-- Dumb dependencies which probably get fetched 'cos I don't know how to use configurations properly yet. --> <exclude org="org.hibernate" module="hibernate"/> <exclude module="aspectjweaver"/> <exclude module="aspectjrt"/> <exclude module="spring"/> <exclude module="cglib"/> <exclude module="dom4j"/> <exclude module="jsr305"/> </dependencies> </ivy-module> diff --git a/lib/jcr-1.0.jar b/lib/jcr-1.0.jar deleted file mode 100644 index e6efb26..0000000 Binary files a/lib/jcr-1.0.jar and /dev/null differ
jalkanen/Priha
f824225f572dbcef61ced9546067777406e31b8b
Switched to use Apache Ivy for dependency management and removed a number of JAR files. Added Cassandra provider (non-functional yet).
diff --git a/.classpath b/.classpath index 6554b4f..82b92ab 100644 --- a/.classpath +++ b/.classpath @@ -1,20 +1,19 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src/java"/> <classpathentry kind="src" path="tests/java"/> <classpathentry kind="src" path="tests/tck"/> <classpathentry kind="src" path="src/generated-sources"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3.8.1"/> <classpathentry exported="true" kind="lib" path="tests/etc"/> <classpathentry kind="lib" path="etc"/> <classpathentry kind="lib" path="lib/jcr-1.0.jar"/> - <classpathentry kind="lib" path="lib/javax.servlet.jar"/> - <classpathentry kind="lib" path="lib/slf4j-api-1.5.3.jar"/> - <classpathentry kind="lib" path="lib/slf4j-simple-1.5.3.jar"/> - <classpathentry kind="lib" path="lib/ehcache-1.6.0.jar"/> - <classpathentry kind="lib" path="lib/concurrent-1.3.4.jar"/> - <classpathentry kind="lib" path="lib/hsqldb-1.8.0.10.jar"/> - <classpathentry kind="lib" path="lib/h2-1.1.118.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="lib" path="lib/hector-0.6.0-10.jar"/> + <classpathentry kind="lib" path="lib/libthrift-r917130.jar"/> + <classpathentry kind="lib" path="lib/apache-cassandra-0.6.0-rc1.jar"/> + <classpathentry kind="lib" path="tests/lib/high-scale-lib.jar"/> + <classpathentry kind="lib" path="tests/lib/clhm-production.jar"/> + <classpathentry kind="con" path="org.apache.ivyde.eclipse.cpcontainer.IVYDE_CONTAINER/?ivyXmlPath=ivy.xml&amp;confs=*"/> <classpathentry kind="output" path="build"/> </classpath> diff --git a/.project b/.project index 22915b3..f18fe15 100644 --- a/.project +++ b/.project @@ -1,17 +1,23 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>priha</name> <comment></comment> <projects> </projects> <buildSpec> + <buildCommand> + <name>org.eclipse.wst.common.project.facet.core.builder</name> + <arguments> + </arguments> + </buildCommand> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> + <nature>org.eclipse.wst.common.project.facet.core.nature</nature> </natures> </projectDescription> diff --git a/build.xml b/build.xml index db0edca..4de4899 100644 --- a/build.xml +++ b/build.xml @@ -1,364 +1,401 @@ <?xml version="1.0"?> <!-- Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> -<project name="Priha" default="jar"> +<project name="Priha" default="jar" xmlns:ivy="antlib:org.apache.ivy.ant"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> <include name="*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> <!-- Jackrabbit is only included if it has been installed with maven --> <fileset dir="${user.home}"> <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> <include name=".m2/repository/commons-collections/**/*3.2.jar"/> <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> </fileset> </path> + <!-- ================================= + target: resolve + ================================= --> + <target name="resolve" description="--> retrieve dependencies with ivy" depends="init-ivy"> + <ivy:retrieve /> + </target> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> - <target name="compile"> + <target name="compile" depends="resolve"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> <src path="src/java"/> <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> <src path="tests/java"/> <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> <delete dir="tests/build"/> </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> <!-- ***************************************************************** --> <!-- Distribution package building. Use "ant dist" to build the distro package, and "ant srczip" to create a source tarball. --> <target name="srczip" depends="compile"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-src.zip"> <zipfileset dir="." excludes="build/** tests/build/** repository*/** tests/reports/** *.log doc/javadoc/**" prefix="priha-${version}"/> </zip> </target> <target name="dist" depends="jar,javadoc"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-bin.zip"> <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> <zipfileset dir="." includes="ChangeLog README LICENSE NOTICE doc/**" prefix="priha-${version}"/> <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> <zipfileset dir="lib" includes="ehcache-*.jar hsqldb-*.jar" prefix="priha-${version}/extras-lib"/> </zip> </target> <!-- Installs the distribution archives by checking out the SVN project. Needs svn and gpg binaries in the shell path. --> <target name="dist-install" depends="srczip,dist"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <!-- Check out code --> <exec executable="svn"> <arg value="co"/> <arg value="https://svn.ecyrd.com/repos/priha/site"/> <arg value="build/priha-site"/> </exec> <!-- Install archives --> <property name="destdir" value="build/priha-site/WebContent/download/priha-${version}"/> <delete dir="${destdir}"/> <mkdir dir="${destdir}"/> <copy file="build/priha-${version}-bin.zip" todir="${destdir}"/> <copy file="build/priha-${version}-src.zip" todir="${destdir}"/> <exec executable="gpg"> <arg value="-sba"/> <arg value="${destdir}/priha-${version}-src.zip"/> </exec> <exec executable="gpg"> <arg value="-sba"/> <arg value="${destdir}/priha-${version}-bin.zip"/> </exec> <!-- Figure out file lengths. We need a bit of Javascript to build the sizes in megabytes --> <length file="build/priha-${version}-bin.zip" property="binsize"/> <length file="build/priha-${version}-src.zip" property="srcsize"/> <script language="javascript"> <![CDATA[ var binsize = project.getProperty("binsize"); var srcsize = project.getProperty("srcsize"); var binmegas = Math.round((binsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); var srcmegas = Math.round((srcsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); project.setNewProperty("binsizemegs", binmegas); project.setNewProperty("srcsizemegs", srcmegas); ]]> </script> <!-- Modify page --> <loadfile property="message" srcFile="build/priha-site/downloadmessage.html"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens"> <param type="token" name="srcurl" value="download/priha-${version}/priha-${version}-src.zip"/> <param type="token" name="binurl" value="download/priha-${version}/priha-${version}-bin.zip"/> <param type="token" name="version" value="${version}"/> <param type="token" name="srcsize" value="${srcsizemegs}"/> <param type="token" name="binsize" value="${binsizemegs}"/> </filterreader> </filterchain> </loadfile> <replaceregexp file="build/priha-site/WebContent/download.html" flags="gs" match="&lt;!-- STARTMAGIC -->(.*)&lt;!-- ENDMAGIC -->" replace="&lt;!-- STARTMAGIC -->${message}&lt;!-- ENDMAGIC -->"/> <echo> OK, I'm done. Please examine the contents of build/priha-site/WebContent/download.html prior to checking in the code with "svn commit". </echo> </target> + <!-- This set of properties installs Apache Ivy --> + + <property name="ivy.install.version" value="2.1.0" /> + <condition property="ivy.home" value="${env.IVY_HOME}"> + <isset property="env.IVY_HOME" /> + </condition> + <property name="ivy.home" value="${user.home}/.ant" /> + <property name="ivy.jar.dir" value="${ivy.home}/lib" /> + <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" /> + + <target name="download-ivy" unless="offline"> + + <mkdir dir="${ivy.jar.dir}"/> + <!-- download Ivy from web site so that it can be used even without any special installation --> + <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" + dest="${ivy.jar.file}" usetimestamp="true"/> + </target> + + <target name="init-ivy" depends="download-ivy"> + <!-- try to load ivy here from ivy home, in case the user has not already dropped + it into ant's lib dir (note that the latter copy will always take precedence). + We will not fail as long as local lib dir exists (it may be empty) and + ivy is in at least one of ant's lib dir or the local lib dir. --> + <path id="ivy.lib.path"> + <fileset dir="${ivy.jar.dir}" includes="*.jar"/> + + </path> + <taskdef resource="org/apache/ivy/ant/antlib.xml" + uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/> + </target> + </project> diff --git a/ivy.xml b/ivy.xml new file mode 100644 index 0000000..4dffca7 --- /dev/null +++ b/ivy.xml @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> +<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd"> + <info + organisation="priha.org" + module="priha" + status="integration"> + </info> + + <dependencies> + <!-- These are for Cassandra deployment --> + <dependency org="org.perf4j" name="perf4j" rev="0.9.12"/> + <dependency org="commons-lang" name="commons-lang" rev="2.4"/> + <dependency org="commons-collections" name="commons-collections" rev="3.2.1"/> + <dependency org="com.googlecode.json-simple" name="json-simple" rev="1.1"/> + <dependency org="log4j" name="log4j" rev="1.2.14"/> + <dependency org="commons-pool" name="commons-pool" rev="1.5.3"/> + <dependency org="com.google.collections" name="google-collections" rev="1.0"/> + + <!-- Other dependencies --> + <dependency org="javax.servlet" name="servlet-api" rev="2.4"/> + <dependency org="net.sf.ehcache" name="ehcache" rev="1.6.2"/> + <dependency org="concurrent" name="concurrent" rev="1.3.4"/> <!-- Doug Lea's --> + + <dependency org="org.slf4j" name="slf4j-api" rev="1.5.3"/> + <dependency org="org.slf4j" name="slf4j-simple" rev="1.5.3"/> + + <!-- The versions don't matter probably much. --> + <dependency org="hsqldb" name="hsqldb" rev="1.8.0.10"/> + <dependency org="com.h2database" name="h2" rev="1.1.118"/> + + <!-- Dumb dependencies which probably get fetched 'cos I don't know how to use configurations + properly yet. --> + <exclude org="org.hibernate" module="hibernate"/> + <exclude module="aspectjweaver"/> + <exclude module="aspectjrt"/> + <exclude module="spring"/> + <exclude module="cglib"/> + <exclude module="dom4j"/> + <exclude module="jsr305"/> + </dependencies> + +</ivy-module> diff --git a/lib/apache-cassandra-0.6.0-rc1.jar b/lib/apache-cassandra-0.6.0-rc1.jar new file mode 100644 index 0000000..95b27f1 Binary files /dev/null and b/lib/apache-cassandra-0.6.0-rc1.jar differ diff --git a/lib/commons-logging-api.jar b/lib/commons-logging-api.jar deleted file mode 100644 index ade9a13..0000000 Binary files a/lib/commons-logging-api.jar and /dev/null differ diff --git a/lib/concurrent-1.3.4.jar b/lib/concurrent-1.3.4.jar deleted file mode 100644 index 551f347..0000000 Binary files a/lib/concurrent-1.3.4.jar and /dev/null differ diff --git a/lib/ehcache-1.6.0.jar b/lib/ehcache-1.6.0.jar deleted file mode 100644 index 1b7894d..0000000 Binary files a/lib/ehcache-1.6.0.jar and /dev/null differ diff --git a/lib/h2-1.1.118.jar b/lib/h2-1.1.118.jar deleted file mode 100644 index 4fa881b..0000000 Binary files a/lib/h2-1.1.118.jar and /dev/null differ diff --git a/lib/hector-0.6.0-10.jar b/lib/hector-0.6.0-10.jar new file mode 100644 index 0000000..7ca3fd2 Binary files /dev/null and b/lib/hector-0.6.0-10.jar differ diff --git a/lib/hsqldb-1.8.0.10.jar b/lib/hsqldb-1.8.0.10.jar deleted file mode 100644 index e010269..0000000 Binary files a/lib/hsqldb-1.8.0.10.jar and /dev/null differ diff --git a/lib/jackrabbit-1.0.jar b/lib/jackrabbit-1.0.jar deleted file mode 100644 index 78ab9a6..0000000 Binary files a/lib/jackrabbit-1.0.jar and /dev/null differ diff --git a/lib/javax.servlet.jar b/lib/javax.servlet.jar deleted file mode 100644 index e6c7feb..0000000 Binary files a/lib/javax.servlet.jar and /dev/null differ diff --git a/lib/junit.jar b/lib/junit.jar deleted file mode 100755 index 2ec606f..0000000 Binary files a/lib/junit.jar and /dev/null differ diff --git a/lib/libthrift-r917130.jar b/lib/libthrift-r917130.jar new file mode 100644 index 0000000..896cdb2 Binary files /dev/null and b/lib/libthrift-r917130.jar differ diff --git a/lib/log4j.jar b/lib/log4j.jar deleted file mode 100644 index 493a3cc..0000000 Binary files a/lib/log4j.jar and /dev/null differ diff --git a/lib/slf4j-api-1.5.3.jar b/lib/slf4j-api-1.5.3.jar deleted file mode 100644 index 01b3e7c..0000000 Binary files a/lib/slf4j-api-1.5.3.jar and /dev/null differ diff --git a/lib/slf4j-simple-1.5.3.jar b/lib/slf4j-simple-1.5.3.jar deleted file mode 100644 index 6206881..0000000 Binary files a/lib/slf4j-simple-1.5.3.jar and /dev/null differ diff --git a/lib/xercesImpl-2.6.2.jar b/lib/xercesImpl-2.6.2.jar deleted file mode 100644 index 14c3162..0000000 Binary files a/lib/xercesImpl-2.6.2.jar and /dev/null differ diff --git a/src/java/org/priha/providers/CassandraProvider.java b/src/java/org/priha/providers/CassandraProvider.java new file mode 100644 index 0000000..1819e88 --- /dev/null +++ b/src/java/org/priha/providers/CassandraProvider.java @@ -0,0 +1,284 @@ +package org.priha.providers; + +import java.io.UnsupportedEncodingException; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import java.util.logging.Logger; + +import javax.jcr.*; + +import me.prettyprint.cassandra.service.CassandraClient; +import me.prettyprint.cassandra.service.CassandraClientPool; +import me.prettyprint.cassandra.service.CassandraClientPoolFactory; +import me.prettyprint.cassandra.service.Keyspace; + +import org.apache.cassandra.thrift.*; +import org.apache.thrift.TException; +import org.priha.core.ItemType; +import org.priha.core.RepositoryImpl; +import org.priha.core.WorkspaceImpl; +import org.priha.nodetype.QNodeDefinition; +import org.priha.path.Path; +import org.priha.path.PathFactory; +import org.priha.util.ConfigurationException; +import org.priha.util.QName; + +/** + * Provides backing store using Apache Cassandra NoSQL solution. + * <p> + * Uses the following ColumnFamily configuration: + * + * ColumnFamily : UUIDMap + * name = uuid + * comparewith = BytesType + * "path" : path + * + * SuperColumnFamily : Content + * name = Workspace + * columntype = super + * comparewith = UTF8Type + * comparesubcolumnswith = UTF8Type + * + * key : value[] = Path : Properties[] + * + * special key "_childnodes" lists all names of childnodes in order + * + * ColumnFamily : Config + * name = <Workspaces> + * comparewith = UTF8Type + * key : value = workspace : name + */ +public class CassandraProvider implements RepositoryProvider +{ + private static final String DEFAULT_KEYSPACE = "Priha"; + private static final String PROP_WORKSPACES = "workspaces"; + private static final String PROP_CONNECTIONS = "connections"; + private Logger log = Logger.getLogger( getClass().getName() ); + + // These are just temporary and assume a single connection + private String m_connection; + private int m_port; + + private CassandraClientPool m_clientPool = CassandraClientPoolFactory.INSTANCE.get(); + + private Keyspace getKeyspace() throws RepositoryException + { + try + { + CassandraClient c = m_clientPool.borrowClient(m_connection,m_port); + + return c.getKeyspace(DEFAULT_KEYSPACE); + } + catch( Exception e ) + { + throw new RepositoryException("Unable to get Cassandra client",e); + } + } + + private void returnKeyspace( Keyspace c ) + { + try + { + if( c != null ) m_clientPool.releaseClient(c.getClient()); + } + catch( Exception e ){} // FIXME: Shouldn't. + } + + public void addNode(StoreTransaction tx, Path path, QNodeDefinition definition) throws RepositoryException + { + Keyspace ks = ((CassandraTransaction)tx).keyspace; + +// ColumnPath columnPath = ThriftGlue.createColumnPath("Content", +// superColumnName, columnName); + } + + public void close(WorkspaceImpl ws) + { + // TODO Auto-generated method stub + + } + + public Path findByUUID(WorkspaceImpl ws, String uuid) throws ItemNotFoundException, RepositoryException + { + Keyspace ks = null; + + try + { + ks = getKeyspace(); + + Column c = ks.getColumn("path", ThriftGlue.createColumnPath("UUIDMap", null, uuid.getBytes("UTF-8")) ); + + return PathFactory.getPath( new String(c.value,"UTF-8") ); + } + catch( NotFoundException e ) + { + throw new ItemNotFoundException("There is no such UUID "+uuid); + } + catch (Exception e) + { + throw new RepositoryException("Unable to get column ",e); + } + finally + { + returnKeyspace(ks); + } + } + + public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException + { + // TODO Auto-generated method stub + return null; + } + + public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws PathNotFoundException, RepositoryException + { + // TODO Auto-generated method stub + return null; + } + + public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) throws RepositoryException + { + // TODO Auto-generated method stub + return false; + } + + public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws RepositoryException + { + // TODO Auto-generated method stub + return null; + } + + public List<QName> listProperties(WorkspaceImpl ws, Path path) throws PathNotFoundException, RepositoryException + { + // TODO Auto-generated method stub + return null; + } + + public Collection<String> listWorkspaces() throws RepositoryException + { + Keyspace ks = null; + + try + { + ks = getKeyspace(); + + //ks.getRangeSlice("path", ThriftGlue.createColumnParent( "Workspaces", null ); + + return null; + } + catch (Exception e) + { + throw new RepositoryException("Unable to get column ",e); + } + finally + { + returnKeyspace(ks); + } + } + + public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) + throws RepositoryException, + NoSuchWorkspaceException + { + // TODO Auto-generated method stub + + } + + public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer property) throws RepositoryException + { + // TODO Auto-generated method stub + + } + + public void remove(StoreTransaction tx, Path path) throws RepositoryException + { + // TODO Auto-generated method stub + + } + + public void reorderNodes(StoreTransaction tx, Path path, List<Path> childOrder) throws RepositoryException + { + // TODO Auto-generated method stub + + } + + public void start(RepositoryImpl repository, Properties properties) throws ConfigurationException + { + String[] workspaces = properties.getProperty( PROP_WORKSPACES, "default" ).split( "\\s" ); + String[] connections = properties.getProperty( PROP_CONNECTIONS, "localhost:9160" ).split("\\s"); + + // FIXME: Should make this run across multiple connections; now just one + + if( connections.length > 1 ) + { + throw new ConfigurationException("Currently only a single connection is allowed"); + } + + String[] host = connections[0].split(":"); + m_connection = host[0]; + if( host.length > 1 ) m_port = Integer.parseInt(host[1]); + + log.info("Connecting to Cassandra service on host '"+m_connection+"', port "+m_port); + + Keyspace ks = null; + + // + // Write the workspaces into the config part. + // + try + { + ks = getKeyspace(); + + for( String ws : workspaces ) + { + ks.insert(ws, + ThriftGlue.createColumnPath("Config", null, "Workspaces".getBytes("UTF-8")), + ws.getBytes("UTF-8")); + } + } + catch (Exception e) + { + throw new ConfigurationException("Failed to start Cassandra", e); + } + finally + { + returnKeyspace(ks); + } + } + + public void stop(RepositoryImpl rep) + { + } + + public void storeCancelled(StoreTransaction tx) throws RepositoryException + { + ((CassandraTransaction)tx).close(); + } + + public void storeFinished(StoreTransaction tx) throws RepositoryException + { + ((CassandraTransaction)tx).close(); + } + + public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException + { + return new CassandraTransaction(ws); + } + + private class CassandraTransaction extends BaseStoreTransaction + { + public Keyspace keyspace; + + public CassandraTransaction(WorkspaceImpl ws) throws RepositoryException + { + super(ws); + keyspace = getKeyspace(); + } + + public void close() + { + returnKeyspace(keyspace); + } + } +} diff --git a/tests/etc/cassandranocache.properties b/tests/etc/cassandranocache.properties new file mode 100644 index 0000000..baf86b3 --- /dev/null +++ b/tests/etc/cassandranocache.properties @@ -0,0 +1,21 @@ +# +# The main Priha configuration file. +# +# Please see doc/Configuring.txt on information how to configure this. + +# +# Simplest possible configuration: uncomment the following line +# to used the defaults and define a directory to store stuff. +# +#priha.provider.defaultProvider.directory=/tmp/priha/ + +priha.providers = cassandraprovider + +priha.provider.cassandraprovider.class = org.priha.providers.CassandraProvider +priha.provider.cassandraprovider.workspaces = default testworkspace +priha.provider.cassandraprovider.connections = localhost:9170 + + + + + diff --git a/tests/etc/log4j.properties b/tests/etc/log4j.properties new file mode 100644 index 0000000..4d20e66 --- /dev/null +++ b/tests/etc/log4j.properties @@ -0,0 +1,40 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# for production, you should probably set the root to INFO +# and the pattern to %c instead of %l. (%l is slower.) + +# output messages into a rolling log file as well as stdout +log4j.rootLogger=INFO,stdout,R + +# stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%5p %d{HH:mm:ss,SSS} %m%n + +# rolling log file +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.file.maxFileSize=20MB +log4j.appender.file.maxBackupIndex=50 +log4j.appender.R.layout=org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern=%5p [%t] %d{ISO8601} %F (line %L) %m%n +# Edit the next line to point to your logs directory +log4j.appender.R.File=/var/log/cassandra/system.log + +# Application logging options +#log4j.logger.com.facebook=DEBUG +#log4j.logger.com.facebook.infrastructure.gms=DEBUG +#log4j.logger.com.facebook.infrastructure.db=DEBUG diff --git a/tests/etc/storage-conf.xml b/tests/etc/storage-conf.xml new file mode 100644 index 0000000..b63e1b8 --- /dev/null +++ b/tests/etc/storage-conf.xml @@ -0,0 +1,386 @@ +<!-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. +--> +<Storage> + <!--======================================================================--> + <!-- Basic Configuration --> + <!--======================================================================--> + + <!-- + ~ The name of this cluster. This is mainly used to prevent machines in + ~ one logical cluster from joining another. + --> + <ClusterName>Priha Test Cluster</ClusterName> + + <!-- + ~ Turn on to make new [non-seed] nodes automatically migrate the right data + ~ to themselves. (If no InitialToken is specified, they will pick one + ~ such that they will get half the range of the most-loaded node.) + ~ If a node starts up without bootstrapping, it will mark itself bootstrapped + ~ so that you can't subsequently accidently bootstrap a node with + ~ data on it. (You can reset this by wiping your data and commitlog + ~ directories.) + ~ + ~ Off by default so that new clusters and upgraders from 0.4 don't + ~ bootstrap immediately. You should turn this on when you start adding + ~ new nodes to a cluster that already has data on it. (If you are upgrading + ~ from 0.4, start your cluster with it off once before changing it to true. + ~ Otherwise, no data will be lost but you will incur a lot of unnecessary + ~ I/O before your cluster starts up.) + --> + <AutoBootstrap>false</AutoBootstrap> + + <!-- + ~ Keyspaces and ColumnFamilies: + ~ A ColumnFamily is the Cassandra concept closest to a relational + ~ table. Keyspaces are separate groups of ColumnFamilies. Except in + ~ very unusual circumstances you will have one Keyspace per application. + + ~ There is an implicit keyspace named 'system' for Cassandra internals. + --> + <Keyspaces> + <Keyspace Name="Priha"> + <!-- + ~ ColumnFamily definitions have one required attribute (Name) + ~ and several optional ones. + ~ + ~ The CompareWith attribute tells Cassandra how to sort the columns + ~ for slicing operations. The default is BytesType, which is a + ~ straightforward lexical comparison of the bytes in each column. + ~ Other options are AsciiType, UTF8Type, LexicalUUIDType, TimeUUIDType, + ~ and LongType. You can also specify the fully-qualified class + ~ name to a class of your choice extending + ~ org.apache.cassandra.db.marshal.AbstractType. + ~ + ~ SuperColumns have a similar CompareSubcolumnsWith attribute. + ~ + ~ BytesType: Simple sort by byte value. No validation is performed. + ~ AsciiType: Like BytesType, but validates that the input can be + ~ parsed as US-ASCII. + ~ UTF8Type: A string encoded as UTF8 + ~ LongType: A 64bit long + ~ LexicalUUIDType: A 128bit UUID, compared lexically (by byte value) + ~ TimeUUIDType: a 128bit version 1 UUID, compared by timestamp + ~ + ~ (To get the closest approximation to 0.3-style supercolumns, you + ~ would use CompareWith=UTF8Type CompareSubcolumnsWith=LongType.) + ~ + ~ An optional `Comment` attribute may be used to attach additional + ~ human-readable information about the column family to its definition. + ~ + ~ The optional KeysCached attribute specifies + ~ the number of keys per sstable whose locations we keep in + ~ memory in "mostly LRU" order. (JUST the key locations, NOT any + ~ column values.) Specify a fraction (value less than 1), a percentage + ~ (ending in a % sign) or an absolute number of keys to cache. + ~ KeysCached defaults to 200000 keys. + ~ + ~ The optional RowsCached attribute specifies the number of rows + ~ whose entire contents we cache in memory. Do not use this on + ~ ColumnFamilies with large rows, or ColumnFamilies with high write:read + ~ ratios. Specify a fraction (value less than 1), a percentage (ending in + ~ a % sign) or an absolute number of rows to cache. + ~ RowsCached defaults to 0, i.e., row cache is off by default. + ~ + ~ Remember, when using caches as a percentage, they WILL grow with + ~ your data set! + --> + <ColumnFamily Name="Config" CompareWith="UTF8Type" + Comment="Stores Priha configuration, including workspace data"/> + + + + <ColumnFamily Name="Standard1" CompareWith="BytesType"/> + <ColumnFamily Name="Standard2" + CompareWith="UTF8Type" + KeysCached="100%"/> + <ColumnFamily Name="StandardByUUID1" CompareWith="TimeUUIDType" /> + <ColumnFamily Name="Super1" + ColumnType="Super" + CompareWith="BytesType" + CompareSubcolumnsWith="BytesType" /> + <ColumnFamily Name="Super2" + ColumnType="Super" + CompareWith="UTF8Type" + CompareSubcolumnsWith="UTF8Type" + RowsCached="10000" + KeysCached="50%" + Comment="A column family with supercolumns, whose column and subcolumn names are UTF8 strings"/> + + <!-- + ~ Strategy: Setting this to the class that implements + ~ IReplicaPlacementStrategy will change the way the node picker works. + ~ Out of the box, Cassandra provides + ~ org.apache.cassandra.locator.RackUnawareStrategy and + ~ org.apache.cassandra.locator.RackAwareStrategy (place one replica in + ~ a different datacenter, and the others on different racks in the same + ~ one.) + --> + <ReplicaPlacementStrategy>org.apache.cassandra.locator.RackUnawareStrategy</ReplicaPlacementStrategy> + + <!-- Number of replicas of the data --> + <ReplicationFactor>1</ReplicationFactor> + + <!-- + ~ EndPointSnitch: Setting this to the class that implements + ~ AbstractEndpointSnitch, which lets Cassandra know enough + ~ about your network topology to route requests efficiently. + ~ Out of the box, Cassandra provides org.apache.cassandra.locator.EndPointSnitch, + ~ and PropertyFileEndPointSnitch is available in contrib/. + --> + <EndPointSnitch>org.apache.cassandra.locator.EndPointSnitch</EndPointSnitch> + + </Keyspace> + </Keyspaces> + + <!-- + ~ Authenticator: any IAuthenticator may be used, including your own as long + ~ as it is on the classpath. Out of the box, Cassandra provides + ~ org.apache.cassandra.auth.AllowAllAuthenticator and, + ~ org.apache.cassandra.auth.SimpleAuthenticator + ~ (SimpleAuthenticator uses access.properties and passwd.properties by + ~ default). + ~ + ~ If you don't specify an authenticator, AllowAllAuthenticator is used. + --> + <Authenticator>org.apache.cassandra.auth.AllowAllAuthenticator</Authenticator> + + <!-- + ~ Partitioner: any IPartitioner may be used, including your own as long + ~ as it is on the classpath. Out of the box, Cassandra provides + ~ org.apache.cassandra.dht.RandomPartitioner, + ~ org.apache.cassandra.dht.OrderPreservingPartitioner, and + ~ org.apache.cassandra.dht.CollatingOrderPreservingPartitioner. + ~ (CollatingOPP colates according to EN,US rules, not naive byte + ~ ordering. Use this as an example if you need locale-aware collation.) + ~ Range queries require using an order-preserving partitioner. + ~ + ~ Achtung! Changing this parameter requires wiping your data + ~ directories, since the partitioner can modify the sstable on-disk + ~ format. + --> + <Partitioner>org.apache.cassandra.dht.RandomPartitioner</Partitioner> + + <!-- + ~ If you are using an order-preserving partitioner and you know your key + ~ distribution, you can specify the token for this node to use. (Keys + ~ are sent to the node with the "closest" token, so distributing your + ~ tokens equally along the key distribution space will spread keys + ~ evenly across your cluster.) This setting is only checked the first + ~ time a node is started. + + ~ This can also be useful with RandomPartitioner to force equal spacing + ~ of tokens around the hash space, especially for clusters with a small + ~ number of nodes. + --> + <InitialToken></InitialToken> + + <!-- + ~ Directories: Specify where Cassandra should store different data on + ~ disk. Keep the data disks and the CommitLog disks separate for best + ~ performance + --> + <CommitLogDirectory>/var/lib/cassandra/commitlog</CommitLogDirectory> + <DataFileDirectories> + <DataFileDirectory>/var/lib/cassandra/data</DataFileDirectory> + </DataFileDirectories> + + + <!-- + ~ Addresses of hosts that are deemed contact points. Cassandra nodes + ~ use this list of hosts to find each other and learn the topology of + ~ the ring. You must change this if you are running multiple nodes! + --> + <Seeds> + <Seed>127.0.0.1</Seed> + </Seeds> + + + <!-- Miscellaneous --> + + <!-- Time to wait for a reply from other nodes before failing the command --> + <RpcTimeoutInMillis>10000</RpcTimeoutInMillis> + <!-- Size to allow commitlog to grow to before creating a new segment --> + <CommitLogRotationThresholdInMB>128</CommitLogRotationThresholdInMB> + + + <!-- Local hosts and ports --> + + <!-- + ~ Address to bind to and tell other nodes to connect to. You _must_ + ~ change this if you want multiple nodes to be able to communicate! + ~ + ~ Leaving it blank leaves it up to InetAddress.getLocalHost(). This + ~ will always do the Right Thing *if* the node is properly configured + ~ (hostname, name resolution, etc), and the Right Thing is to use the + ~ address associated with the hostname (it might not be). + --> + <ListenAddress>localhost</ListenAddress> + <!-- internal communications port --> + <StoragePort>7000</StoragePort> + + <!-- + ~ The address to bind the Thrift RPC service to. Unlike ListenAddress + ~ above, you *can* specify 0.0.0.0 here if you want Thrift to listen on + ~ all interfaces. + ~ + ~ Leaving this blank has the same effect it does for ListenAddress, + ~ (i.e. it will be based on the configured hostname of the node). + --> + <ThriftAddress>localhost</ThriftAddress> + <!-- Thrift RPC port (the port clients connect to). --> + <ThriftPort>9170</ThriftPort> + <!-- + ~ Whether or not to use a framed transport for Thrift. If this option + ~ is set to true then you must also use a framed transport on the + ~ client-side, (framed and non-framed transports are not compatible). + --> + <ThriftFramedTransport>false</ThriftFramedTransport> + + + <!--======================================================================--> + <!-- Memory, Disk, and Performance --> + <!--======================================================================--> + + <!-- + ~ Access mode. mmapped i/o is substantially faster, but only practical on + ~ a 64bit machine (which notably does not include EC2 "small" instances) + ~ or relatively small datasets. "auto", the safe choice, will enable + ~ mmapping on a 64bit JVM. Other values are "mmap", "mmap_index_only" + ~ (which may allow you to get part of the benefits of mmap on a 32bit + ~ machine by mmapping only index files) and "standard". + ~ (The buffer size settings that follow only apply to standard, + ~ non-mmapped i/o.) + --> + <DiskAccessMode>auto</DiskAccessMode> + + <!-- + ~ Size of compacted row above which to log a warning. (If compacted + ~ rows do not fit in memory, Cassandra will crash. This is explained + ~ in http://wiki.apache.org/cassandra/CassandraLimitations and is + ~ scheduled to be fixed in 0.7.) + --> + <RowWarningThresholdInMB>512</RowWarningThresholdInMB> + + <!-- + ~ Buffer size to use when performing contiguous column slices. Increase + ~ this to the size of the column slices you typically perform. + ~ (Name-based queries are performed with a buffer size of + ~ ColumnIndexSizeInKB.) + --> + <SlicedBufferSizeInKB>64</SlicedBufferSizeInKB> + + <!-- + ~ Buffer size to use when flushing memtables to disk. (Only one + ~ memtable is ever flushed at a time.) Increase (decrease) the index + ~ buffer size relative to the data buffer if you have few (many) + ~ columns per key. Bigger is only better _if_ your memtables get large + ~ enough to use the space. (Check in your data directory after your + ~ app has been running long enough.) --> + <FlushDataBufferSizeInMB>32</FlushDataBufferSizeInMB> + <FlushIndexBufferSizeInMB>8</FlushIndexBufferSizeInMB> + + <!-- + ~ Add column indexes to a row after its contents reach this size. + ~ Increase if your column values are large, or if you have a very large + ~ number of columns. The competing causes are, Cassandra has to + ~ deserialize this much of the row to read a single column, so you want + ~ it to be small - at least if you do many partial-row reads - but all + ~ the index data is read for each access, so you don't want to generate + ~ that wastefully either. + --> + <ColumnIndexSizeInKB>64</ColumnIndexSizeInKB> + + <!-- + ~ Flush memtable after this much data has been inserted, including + ~ overwritten data. There is one memtable per column family, and + ~ this threshold is based solely on the amount of data stored, not + ~ actual heap memory usage (there is some overhead in indexing the + ~ columns). + --> + <MemtableThroughputInMB>64</MemtableThroughputInMB> + <!-- + ~ Throughput setting for Binary Memtables. Typically these are + ~ used for bulk load so you want them to be larger. + --> + <BinaryMemtableThroughputInMB>256</BinaryMemtableThroughputInMB> + <!-- + ~ The maximum number of columns in millions to store in memory per + ~ ColumnFamily before flushing to disk. This is also a per-memtable + ~ setting. Use with MemtableThroughputInMB to tune memory usage. + --> + <MemtableOperationsInMillions>0.3</MemtableOperationsInMillions> + <!-- + ~ The maximum time to leave a dirty memtable unflushed. + ~ (While any affected columnfamilies have unflushed data from a + ~ commit log segment, that segment cannot be deleted.) + ~ This needs to be large enough that it won't cause a flush storm + ~ of all your memtables flushing at once because none has hit + ~ the size or count thresholds yet. For production, a larger + ~ value such as 1440 is recommended. + --> + <MemtableFlushAfterMinutes>60</MemtableFlushAfterMinutes> + + <!-- + ~ Unlike most systems, in Cassandra writes are faster than reads, so + ~ you can afford more of those in parallel. A good rule of thumb is 2 + ~ concurrent reads per processor core. Increase ConcurrentWrites to + ~ the number of clients writing at once if you enable CommitLogSync + + ~ CommitLogSyncDelay. --> + <ConcurrentReads>8</ConcurrentReads> + <ConcurrentWrites>32</ConcurrentWrites> + + <!-- + ~ CommitLogSync may be either "periodic" or "batch." When in batch + ~ mode, Cassandra won't ack writes until the commit log has been + ~ fsynced to disk. It will wait up to CommitLogSyncBatchWindowInMS + ~ milliseconds for other writes, before performing the sync. + + ~ This is less necessary in Cassandra than in traditional databases + ~ since replication reduces the odds of losing data from a failure + ~ after writing the log entry but before it actually reaches the disk. + ~ So the other option is "periodic," where writes may be acked immediately + ~ and the CommitLog is simply synced every CommitLogSyncPeriodInMS + ~ milliseconds. + --> + <CommitLogSync>periodic</CommitLogSync> + <!-- + ~ Interval at which to perform syncs of the CommitLog in periodic mode. + ~ Usually the default of 10000ms is fine; increase it if your i/o + ~ load is such that syncs are taking excessively long times. + --> + <CommitLogSyncPeriodInMS>10000</CommitLogSyncPeriodInMS> + <!-- + ~ Delay (in milliseconds) during which additional commit log entries + ~ may be written before fsync in batch mode. This will increase + ~ latency slightly, but can vastly improve throughput where there are + ~ many writers. Set to zero to disable (each entry will be synced + ~ individually). Reasonable values range from a minimal 0.1 to 10 or + ~ even more if throughput matters more than latency. + --> + <!-- <CommitLogSyncBatchWindowInMS>1</CommitLogSyncBatchWindowInMS> --> + + <!-- + ~ Time to wait before garbage-collection deletion markers. Set this to + ~ a large enough value that you are confident that the deletion marker + ~ will be propagated to all replicas by the time this many seconds has + ~ elapsed, even in the face of hardware failures. The default value is + ~ ten days. + --> + <GCGraceSeconds>864000</GCGraceSeconds> +</Storage> diff --git a/tests/java/org/priha/providers/AllTests.java b/tests/java/org/priha/providers/AllTests.java index 08ce2b6..c77e90b 100644 --- a/tests/java/org/priha/providers/AllTests.java +++ b/tests/java/org/priha/providers/AllTests.java @@ -1,38 +1,39 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; public class AllTests extends AbstractTest { public static Test suite() { TestSuite suite = new TestSuite("Provider tests"); suite.addTest( FileProviderTest.suite() ); suite.addTest( JdbcProviderTest.suite() ); + suite.addTest( CassandraProviderTest.suite() ); return suite; } } diff --git a/tests/java/org/priha/providers/CassandraProviderTest.java b/tests/java/org/priha/providers/CassandraProviderTest.java new file mode 100644 index 0000000..a90d451 --- /dev/null +++ b/tests/java/org/priha/providers/CassandraProviderTest.java @@ -0,0 +1,197 @@ +/* + Priha - A JSR-170 implementation library. + + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.priha.providers; + +import java.io.IOException; + +import javax.jcr.*; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.version.VersionException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.cassandra.thrift.CassandraDaemon; +import org.apache.thrift.transport.TTransportException; +import org.priha.AbstractTest; +import org.priha.RepositoryManager; +import org.priha.TestUtil; +import org.priha.core.RepositoryImpl; +import org.priha.core.SessionImpl; + +public class CassandraProviderTest extends AbstractTest +{ + SessionImpl m_session; + static EmbeddedCassandraService cassandra = null; + + public void setUp() throws Exception + { + super.setUp(); + + System.setProperty("storage-config", "tests/etc"); + + if( cassandra == null ) + { + cassandra = new EmbeddedCassandraService(); + + cassandra.init(); + + // spawn cassandra in a new thread + Thread t = new Thread(cassandra); + t.setDaemon(true); + t.start(); + } + + RepositoryImpl rep = RepositoryManager.getRepository("cassandranocache.properties"); + m_session = rep.login(new SimpleCredentials("foo",new char[0])); + } + + public void tearDown() throws Exception + { + TestUtil.emptyRepo(m_session.getRepository()); + m_session.logout(); + + super.tearDown(); + } + + private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU + + public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException + { + Node nd = m_session.getRootNode().addNode(UTF8_NAME); + nd.setProperty(UTF8_NAME, UTF8_NAME); + + m_session.save(); + + Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); + Property p2 = nd2.getProperty(UTF8_NAME); + + assertEquals(UTF8_NAME,nd2.getName()); + assertEquals(UTF8_NAME,p2.getName()); + assertEquals(UTF8_NAME,p2.getString()); + } + + /** + * JCR names are case-sensitive, so let's check that all these work. + */ + @SuppressWarnings("unused") + public void testCase1() throws Exception + { + Node nd = m_session.getRootNode().addNode("Test One"); + nd.setProperty("Property One","KILL"); + + m_session.save(); + + try + { + Node nd2 = (Node)m_session.getItem("/test one"); + fail("Found with wrong case"); + } + catch( PathNotFoundException e ) {} + + + try + { + Property p2 = (Property)m_session.getItem("/Test One/property one"); + fail("Found property with wrong case"); + } + catch( PathNotFoundException e ) {} + } + + @SuppressWarnings("unused") + public void testCase2() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("B", "foo"); + m_session.save(); + + try + { + Node nd2 = (Node)m_session.getItem("/a"); + fail("Found with wrong case"); + } + catch( PathNotFoundException e ) {} + + + try + { + Property p2 = (Property)m_session.getItem("/A/b"); + fail("Found property with wrong case"); + } + catch( PathNotFoundException e ) {} + + } + + public void testCase3() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("x","foo-a"); + + Node nd2 = m_session.getRootNode().addNode("a"); + nd2.setProperty("x","foo-b"); + + m_session.save(); + + assertFalse("same",nd.isSame(nd2)); + + Node nda = (Node) m_session.getItem("/A"); + assertEquals("foo-a",nda.getProperty("x").getString()); + + Node ndb = (Node) m_session.getItem("/a"); + assertEquals("foo-b",ndb.getProperty("x").getString()); + } + + public void testPropertyCase1() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("x","foo-a"); + nd.setProperty("X","foo-b"); + + m_session.save(); + + Node nda = (Node) m_session.getItem("/A"); + assertEquals("foo-a",nda.getProperty("x").getString()); + assertEquals("foo-b",nda.getProperty("X").getString()); + } + public static Test suite() + { + return new TestSuite( CassandraProviderTest.class ); + } + + /** + * Simple embedded cassandra service + */ + public static class EmbeddedCassandraService implements Runnable + { + + CassandraDaemon cassandraDaemon; + + public void init() throws TTransportException, IOException + { + cassandraDaemon = new CassandraDaemon(); + cassandraDaemon.init(null); + } + + public void run() + { + cassandraDaemon.start(); + } + } +} diff --git a/tests/lib/clhm-production.jar b/tests/lib/clhm-production.jar new file mode 100644 index 0000000..028f505 Binary files /dev/null and b/tests/lib/clhm-production.jar differ diff --git a/tests/lib/high-scale-lib.jar b/tests/lib/high-scale-lib.jar new file mode 100644 index 0000000..421a436 Binary files /dev/null and b/tests/lib/high-scale-lib.jar differ
jalkanen/Priha
53fb7afa7a202607a51606ef473d5509b640423b
Just added the other options as well.
diff --git a/tests/etc/priha.properties b/tests/etc/priha.properties index 1e21ccf..777ec37 100644 --- a/tests/etc/priha.properties +++ b/tests/etc/priha.properties @@ -1,12 +1,31 @@ # # The main Priha configuration file. # # Please see doc/Configuring.txt on information how to configure this. # For testing, we just use the plain FileProvider with no caches or anything. priha.providers = fileprovider +# Define the Fileprovider + priha.provider.fileprovider.class = org.priha.providers.FileProvider priha.provider.fileprovider.directory = /tmp/priha/fileprovider/ priha.provider.fileprovider.workspaces = default testworkspace + +# A jdbc provider + +priha.provider.jdbc.class = org.priha.providers.JdbcProvider +priha.provider.jdbc.connectionUrl = jdbc:hsqldb:file:/tmp/testdb +priha.provider.jdbc.driverClass = org.hsqldb.jdbcDriver +priha.provider.jdbc.username = sa +priha.provider.jdbc.password = +priha.provider.jdbc.workspaces = default testworkspace + +# Ehcache + +priha.provider.ehcache.class = org.priha.providers.EhCachingProvider +priha.provider.ehcache.realProvider = fileprovider +priha.provider.ehcache.size = 25000 +priha.provider.ehcache.workspaces = default testworkspace +priha.provider.ehcache.cacheName = jdbc.ehcache \ No newline at end of file
jalkanen/Priha
b59d6228142ab1fd4776b7481eed34bea565e63a
Added the option of creating a FileBinarySource from a Stream.
diff --git a/src/java/org/priha/core/binary/FileBinarySource.java b/src/java/org/priha/core/binary/FileBinarySource.java index be9b588..a005259 100644 --- a/src/java/org/priha/core/binary/FileBinarySource.java +++ b/src/java/org/priha/core/binary/FileBinarySource.java @@ -1,49 +1,65 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.binary; import java.io.*; +import org.priha.util.FileUtil; + /** * Represents a BinarySource which is backed by a File on the * Filesystem itself. */ public class FileBinarySource implements BinarySource { private File m_file; + /** + * Creates a temporary file for the given InputStream. + */ + public FileBinarySource( InputStream in ) throws IOException + { + m_file = File.createTempFile("priha", "bin"); + + OutputStream out = new FileOutputStream(m_file); + + FileUtil.copyContents(in, out); + + out.close(); + } + public FileBinarySource( File f ) { m_file = f; } public long getLength() { return m_file.length(); } public InputStream getStream() throws FileNotFoundException { return new FileInputStream( m_file ); } public FileBinarySource clone() { return new FileBinarySource(m_file); } }
jalkanen/Priha
8068e095b131d3ccb19ff92af96537311f6ebfae
Cleaned away some annoying memory leaks by making sure that at close() and logout() all references are cleared properly.
diff --git a/ChangeLog b/ChangeLog index 08844ad..9a46e61 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,518 @@ +2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.7.5 + + * Fixed a number of memory leaks. + 2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.4 * The "I think I optimized something but I've got a flu" -release. * Session Item cache is now configurable (and slightly bigger by default) * SessionProvider.itemExists() is now slightly smarter when checking for cached items. * Allowed overriding priha.properties from system properties. 2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.3 * Optimization of ProviderManager.loadNode() and Item.enterState(). Especially the latter helps reading quite a lot. * EhCacheProvider.exists() was confusing Nodes with Properties sometimes. * ObservationManager now correctly sends events for Node reordering. 2010-01-04 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.2 * Implemented Observation. It does not *quite* work yet, but it's only nine errors until TCK pass. 2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> * Fixed XML import tests for versioning by properly checking for checked-in Nodes in XMLImport. You may test Versioning, but the TCK tests are disabled. You can turn them on by editing Release.DESCRIPTORS and setting Repository.OPTION_VERSIONING_SUPPORTED to STR_TRUE. * 0.7.1 * FileProvider speedup - added internal cache for mangleName(). 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index d24dc6e..3615355 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ - public static final int MINORREVISION = 4; + public static final int MINORREVISION = 5; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_TRUE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/PropertyImpl.java b/src/java/org/priha/core/PropertyImpl.java index f8e243a..bc97821 100644 --- a/src/java/org/priha/core/PropertyImpl.java +++ b/src/java/org/priha/core/PropertyImpl.java @@ -1,723 +1,724 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.PropertyDefinition; import javax.jcr.version.VersionException; import org.priha.core.values.StreamValueImpl; import org.priha.core.values.StringValueImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.Path; import org.priha.providers.ValueContainer; public class PropertyImpl extends ItemImpl implements Property, Comparable<PropertyImpl> { private enum Multi { UNDEFINED, SINGLE, MULTI } private ValueContainer m_value = ValueContainer.UNDEFINED_CONTAINER; private Multi m_multi = Multi.UNDEFINED; PropertyDefinition m_definition; private boolean m_transient = false; public PropertyImpl( SessionImpl session, Path path, QPropertyDefinition propDef ) { super( session, path ); if( propDef != null ) { setDefinition( propDef.new Impl(session) ); // m_type = propDef.getRequiredType(); } } public boolean getBoolean() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE boolean value from a MULTI property "+m_path); return getValue().getBoolean(); } public Calendar getDate() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE date value from a MULTI property "+m_path); return getValue().getDate(); } public PropertyDefinition getDefinition() throws RepositoryException { return m_definition; } public double getDouble() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE double value from a MULTI property "+m_path); return getValue().getDouble(); } public long getLength() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE length value from a MULTI property "+m_path); return getLength( m_value.getValue() ); } /** * Returns the length of a single Value. * @param v * @return * @throws ValueFormatException * @throws IllegalStateException * @throws RepositoryException */ private long getLength( Value v ) throws ValueFormatException, IllegalStateException, RepositoryException { if( v.getType() == PropertyType.BINARY ) { try { return ((StreamValueImpl)v).getLength(); } catch (IOException e) { throw new RepositoryException("Unable to get length "+e.getMessage()); } } return v.getString().length(); } public long[] getLengths() throws ValueFormatException, RepositoryException { if( m_multi != Multi.MULTI ) throw new ValueFormatException(); long[] lengths = new long[getValues().length]; for( int i = 0; i < getValues().length; i++ ) { lengths[i] = getLength( getValues()[i] ); } return lengths; } public long getLong() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException(); return getValue().getLong(); } public NodeImpl getNode() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE reference value from a MULTI property "+m_path); if( getValue().getType() != PropertyType.REFERENCE ) throw new ValueFormatException(); String uuid = getValue().getString(); NodeImpl nd = m_session.getNodeByUUID( uuid ); return nd; } public InputStream getStream() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException(); return getValue().getStream(); } public String getString() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE string value from a MULTI property "+m_path); return getValue().getString(); } public int getType() throws RepositoryException { return m_value.getType(); } public ValueImpl getValue() throws ValueFormatException, RepositoryException { if( m_multi != Multi.SINGLE ) throw new ValueFormatException("Attempted to get a SINGLE Value object from a MULTI property "+m_path); if( m_value == null ) throw new RepositoryException("Internal error: Value is null for "+m_path); // // Clones the value as per the Javadoc // ValueContainer vc = m_value.deepClone(getSession()); return vc.getValue(); } public Value[] getValues() throws ValueFormatException, RepositoryException { if( m_multi != Multi.MULTI ) throw new ValueFormatException("Attempted to get a MULTI Value object from a SINGLE property "+m_path); return m_session.getValueFactory().cloneValues(m_value.getValues()); } /** * Differs from setValue(), as it does not mark the item modified. * * @param value * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void loadValue( ValueImpl value ) throws VersionException, LockException, ConstraintViolationException, RepositoryException { if( m_multi == Multi.MULTI ) throw new ValueFormatException("Attempted to set a SINGLE Value object to a MULTI property "+getPath()); if( value == null ) { remove(); return; } m_value = new ValueContainer(value); m_multi = Multi.SINGLE; } public void setValue(Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { QNodeType parentType = getParent().getPrimaryQNodeType(); if( !m_session.isSuper() ) { if( !parentType.canSetProperty( getQName(), value ) ) throw new ConstraintViolationException("Setting of this property is forbidden"); if( !getParent().isCheckedOut() ) throw new VersionException("Parent node is not checked out"); if( getParent().isLockedWithoutToken() ) throw new LockException("Parent node is locked"); } if( getType() != PropertyType.UNDEFINED && value != null && getType() != value.getType() ) { throw new ValueFormatException("Attempt to set a different type value to this property"); } loadValue( (ValueImpl)value ); if( !isNew() ) { enterState( ItemState.UPDATED ); } else { enterState( ItemState.NEW ); getParent().enterState( ItemState.UPDATED ); } } public void setValue(Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // if( getType() == PropertyType.UNDEFINED ) // m_type = propertyType; int propertyType = getType(); if( propertyType == PropertyType.UNDEFINED ) { if( values.length > 0 && values[0] != null ) { int type = values[0].getType(); propertyType = type; } else { // // This is the difficult bit. The system could not figure out an explicit // node type for this Property (based on the parent node), and the // values array is empty, so we can't use that one either. So we do the - // only thing we can - tell the user that he's being stupid. + // only thing we can - assume something. // + propertyType = PropertyType.STRING; //throw new ValueFormatException("Cannot add an empty Value array when there is no explicit type defined in the parent Node."+getInternalPath()); } } if( propertyType != PropertyType.UNDEFINED && values != null && values.length >= 1 && values[0] != null && propertyType != values[0].getType() ) { throw new ValueFormatException("Attempt to set a different type value to this property"); } setValue( values, propertyType ); } public void setValue(Value[] values, int propertyType) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { QNodeType parentType = getParent().getPrimaryQNodeType(); if( !m_session.isSuper() ) { if( !parentType.canSetProperty( getQName(), values ) ) throw new ConstraintViolationException("Setting of this property is forbidden:"); if( !getParent().isCheckedOut() ) throw new VersionException("Parent node is not checked out"); if( getParent().isLockedWithoutToken() ) throw new LockException("Parent node is locked"); } if( values == null ) { remove(); return; } values = compactValueArray( values ); loadValue(values, propertyType); if( m_value != null ) { if( isNew() ) { // The Property has just been added. getParent().enterState( ItemState.UPDATED ); } enterState( ItemState.UPDATED ); } else { getParent().enterState( ItemState.UPDATED ); } } /** * Differs from setValue() in the sense that it does not mark it modified. * * @param values * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void loadValue(Value[] values, int propertyType) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( m_multi == Multi.SINGLE ) throw new ValueFormatException("Attempted to set a MULTI Value object to a SINGLE property "+m_path); /* if( propertyType == PropertyType.UNDEFINED ) throw new ValueFormatException("Cannot load an UNDEFINED value"); */ if( values == null ) { remove(); return; } m_value = new ValueContainer(values, propertyType); m_multi = Multi.MULTI; } /** * Compacts away the null values of the array. It also ensures that all * the Values in the array are of the same type. * * @param values * @return * @throws ValueFormatException */ private Value[] compactValueArray(Value[] values) throws ValueFormatException { ArrayList<Value> ls = new ArrayList<Value>(); int type = PropertyType.UNDEFINED; for( int i = 0; i < values.length; i++ ) { if( values[i] != null ) { if( type == PropertyType.UNDEFINED ) type = values[i].getType(); else if( values[i].getType() != type ) throw new ValueFormatException("All Values must be of the same type!"); ls.add( values[i] ); } } return ls.toArray( new Value[ls.size()] ); } public void setValue(String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { remove(); return; } setValue( m_session.getValueFactory().createValue(value, getType() == PropertyType.UNDEFINED ? PropertyType.STRING : getType() ) ); } public void setValue(String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { QNodeType parentType = getParent().getPrimaryQNodeType(); if( !m_session.isSuper() ) { if( !parentType.canSetProperty( getQName(), new StringValueImpl("") ) ) throw new ConstraintViolationException("Setting of this property is forbidden:"); if( !getParent().isCheckedOut() ) throw new VersionException("Parent node is not checked out"); } if( values == null ) { remove(); return; } if( getType() != PropertyType.UNDEFINED && getType() != PropertyType.STRING ) { throw new ValueFormatException("Attempt to set a different type value to this property"); } ArrayList<Value> ls = new ArrayList<Value>(); for( int i = 0; i < values.length; i++ ) { if( values[i] != null ) ls.add( m_session.getValueFactory().createValue( values[i] )); } setValue( ls.toArray( new Value[ls.size()] ), PropertyType.STRING ); } public void setValue(InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { remove(); return; } setValue( m_session.getValueFactory().createValue(value, getType() == PropertyType.UNDEFINED ? PropertyType.BINARY : getType() ) ); } public void setValue(long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { setValue( m_session.getValueFactory().createValue(value) ); } public void setValue(double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { setValue( m_session.getValueFactory().createValue(value) ); } public void setValue(Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { remove(); } setValue( m_session.getValueFactory().createValue(value) ); } public void setValue(boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { setValue( m_session.getValueFactory().createValue(value, getType() == PropertyType.UNDEFINED ? PropertyType.BOOLEAN : getType() ) ); } public void setValue(Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { remove(); } else { try { setValue( m_session.getValueFactory().createValue(value.getUUID(), PropertyType.REFERENCE) ); } catch( UnsupportedRepositoryOperationException e ) { throw new ValueFormatException("Node is not referenceable"); } } } public void setValue( String value, int type ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { remove(); } else { setValue( m_session.getValueFactory().createValue(value,type) ); } } public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { Node parent = getParent(); parent.save(); } public String toString() { String path; try { path = getInternalPath().toString(m_session); } catch( Exception e ) { path = getInternalPath().toString(); } try { return "Property("+m_multi+")["+path+"="+((m_multi == Multi.SINGLE && m_value != null) ? getValue().toString() : (PropertyType.nameFromValue(getType())+"["+getValues().length+"]"))+"]"; } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Error?"; } public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { // // Sanity check - the primary type cannot be deleted unless this is a super session. // if( !getSession().isSuper() && getName().equals("jcr:primaryType") && getInternalPath().getParentPath().isRoot() ) return; NodeImpl nd = getParent(); nd.removeProperty(this); enterState( ItemState.REMOVED ); } public void setDefinition(PropertyDefinition pd) { m_definition = pd; if( m_definition != null ) { m_multi = m_definition.isMultiple() ? Multi.MULTI : Multi.SINGLE; } } /** * A PropertyImpl is equal to another PropertyImpl if * <ul> * <li>Paths are equal</li> * <li>Definitions are equal</li> * <li>All values are equal (in case of a multi-valued object)</li> * </ul> */ @Override public boolean equals( Object obj ) { if( !(obj instanceof PropertyImpl) ) return false; if( obj == this ) return true; PropertyImpl pi = (PropertyImpl) obj; if( !pi.m_path.equals(m_path) ) return false; try { if( m_multi == Multi.SINGLE && pi.m_multi == Multi.SINGLE ) { return getValue().equals(pi.getValue()); } else if( m_multi == Multi.MULTI && pi.m_multi == Multi.MULTI ) { if( getValues().length == pi.getValues().length ) { for( int i = 0; i < getValues().length; i++ ) { if( !getValues()[i].equals(pi.getValues()[i]) ) return false; } return true; } } } catch( RepositoryException e ) { // TODO: WHat to do here? } return false; } // FIXME: Is not consistent with equals. public int compareTo(PropertyImpl o) { int res = m_path.toString().compareTo(o.m_path.toString()); if( res == 0 ) { res = m_session.getWorkspace().getName().compareTo( o.m_session.getWorkspace().getName() ); } return res; } /** * Transient properties are never saved - they just live within the Session. * * @param b True, if you want to turn this property into a transient property. */ public void setTransient( boolean b ) { m_transient = true; } /** * Returns true, if this property is transient. * * @return True or false. */ public boolean isTransient() { return m_transient; } @Override protected void preSave() throws RepositoryException { super.preSave(); if( getType() == PropertyType.UNDEFINED && !m_definition.isMultiple() ) throw new ConstraintViolationException("Property must not be of type UNDEFINED, unless it's a multiproperty: "+getInternalPath()); } public ValueContainer getValueContainer() { return m_value; } } diff --git a/src/java/org/priha/core/ProviderManager.java b/src/java/org/priha/core/ProviderManager.java index f583ae3..f68a5fd 100644 --- a/src/java/org/priha/core/ProviderManager.java +++ b/src/java/org/priha/core/ProviderManager.java @@ -19,675 +19,686 @@ package org.priha.core; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import javax.jcr.version.VersionException; import org.priha.core.values.QNameValue; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.RepositoryProvider; import org.priha.providers.StoreTransaction; import org.priha.providers.ValueContainer; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * This is a front-end class for managing multiple providers * for a single repository. * <p> * The ProviderManager is a singleton per Repository. */ public class ProviderManager implements ItemStore { private HashMap<String,ProviderInfo> m_workspaceAccess; private ProviderInfo[] m_providers; private RepositoryImpl m_repository; private Logger log = Logger.getLogger(ProviderManager.class.getName()); private String m_defaultWorkspaceName; public ProviderManager( RepositoryImpl repository ) throws ConfigurationException { m_repository = repository; initialize(); } public static final String PROP_PRIHA_PROVIDERS = "priha.providers"; public static final String PROP_PRIHA_PROVIDER_PREFIX = "priha.provider."; public static final String DEFAULT_PROVIDERLIST = "defaultProvider"; /** * Initializes all the Providers defined in the property file. * * @throws ConfigurationException If the properties would define an illegal configuration. */ private void initialize() throws ConfigurationException { m_workspaceAccess = new HashMap<String,ProviderInfo>(); String providerList = m_repository.getProperty( PROP_PRIHA_PROVIDERS ); if( providerList == null ) throw new ConfigurationException("Required property missing",PROP_PRIHA_PROVIDERS); String[] providers = providerList.split("\\s"); if( providers.length == 0 ) throw new ConfigurationException("Empty property",PROP_PRIHA_PROVIDERS); m_providers = new ProviderInfo[providers.length]; for( int i = 0; i < providers.length; i++ ) { Properties props = filterProperties(m_repository,providers[i]); String className = props.getProperty("class"); if( className == null ) throw new ConfigurationException("Provider "+providers[i]+" does not declare a class name. "+ "There should be a property called '"+PROP_PRIHA_PROVIDER_PREFIX+providers[i]+".class' in your properties."); String workspaceList = props.getProperty("workspaces","default"); String[] workspaces = workspaceList.split("\\s"); if( m_defaultWorkspaceName == null ) { if( workspaces.length == 0 ) throw new ConfigurationException("The first provider ("+providers[i]+") MUST have at least one workspace defined!"); m_defaultWorkspaceName = workspaces[0]; log.fine("Default workspace is set to '"+m_defaultWorkspaceName+"'"); } log.fine("Provider "+i+": "+providers[i]+" is a "+className); RepositoryProvider p = instantiateProvider( m_repository, className, props ); m_providers[i] = new ProviderInfo(); m_providers[i].provider = p; m_providers[i].workspaces = workspaces; m_providers[i].lock = new ReentrantReadWriteLock(); for( String ws : workspaces ) { if( m_workspaceAccess.containsKey(ws) ) throw new ConfigurationException("Workspace "+ws+" is defined multiple times. Very likely you have forgotten to declare a workspace property for a Provider declaration."); m_workspaceAccess.put(ws, m_providers[i]); } } } /** * [0] = /largefiles/ * [1] = / * * "/" => 1 * "/largefiles" => 0 * "/largefiles2" => 1 * "/largefiles/foo" => 0 * * @param p * @return * @throws ConfigurationException */ private final ProviderInfo getProviderInfo(WorkspaceImpl wi, Path p) throws ConfigurationException { ProviderInfo pi = m_workspaceAccess.get(wi.getName()); if( pi != null ) return pi; throw new ConfigurationException("Nonexistant workspace: "+wi.getName()); } /** * Filters the properties set when the Repository was created to find * the property set for a provider. * <p> * Essentially returns a property set where all instances of * <code>priha.provider.[providerName].property = value</code> * are replaced with <code>property = value</code>. * * @param repository The repository from which the properties are read * @param providerName The name to filter with * @return A valid set of Properties. It can also be empty, if there * were no properties defined for this providerName. * @see ProviderManager#instantiateProvider(RepositoryImpl, String, Properties) */ public static Properties filterProperties( RepositoryImpl repository, String providerName ) { Properties props = new Properties(); String prefix = PROP_PRIHA_PROVIDER_PREFIX + providerName + "."; for( Enumeration<String> e = repository.getPropertyNames(); e.hasMoreElements(); ) { String key = e.nextElement(); if( key.startsWith(prefix) ) { String val = repository.getProperty(key); key = key.substring(prefix.length()); props.setProperty(key, val); } } return props; } /** * Instantiates a RepositoryProvider using the given class name and * the properties, and calls its start() method. * * @param rep The RepositoryImpl who will own this RepositoryProvider * @param className The FQN of the class. * @param props A filtered set of Properties * @return A started RepositoryProvider. * * @throws ConfigurationException If the provider cannot be instantiated or the configuration * is faulty. * * @see ProviderManager#filterProperties(RepositoryImpl, String) */ public static RepositoryProvider instantiateProvider(RepositoryImpl rep, String className, Properties props) throws ConfigurationException { Class<?> cl; RepositoryProvider provider; try { cl = Class.forName( className ); provider = (RepositoryProvider) cl.newInstance(); provider.start( rep, props ); } catch (ClassNotFoundException e) { throw new ConfigurationException("Could not find provider class",className); } catch (InstantiationException e) { throw new ConfigurationException("Could not instantiate provider class",className); } catch (IllegalAccessException e) { throw new ConfigurationException("Could not access provider class",className); } return provider; } public void open(Credentials credentials, String workspaceName) throws NoSuchWorkspaceException, RepositoryException { ProviderInfo pi = m_workspaceAccess.get(workspaceName); if( pi == null ) throw new NoSuchWorkspaceException("No such workspace: '"+workspaceName+"'"); try { pi.lock.writeLock().lock(); pi.provider.open( m_repository, credentials, workspaceName ); } finally { pi.lock.writeLock().unlock(); } } private ValueContainer getPropertyValue(WorkspaceImpl impl, Path ptPath) throws RepositoryException { ProviderInfo pi = getProviderInfo(impl,ptPath); try { pi.lock.readLock().lock(); ValueContainer stored = pi.provider.getPropertyValue( impl, ptPath ); return stored; } finally { pi.lock.readLock().unlock(); } } /** * Returns the set of workspaces declared in the config file. * * @throws ConfigurationException */ public Collection<String> listWorkspaces() throws ConfigurationException { return m_workspaceAccess.keySet(); } public List<Path>listNodes(WorkspaceImpl impl, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( impl, path ); try { pi.lock.readLock().lock(); return pi.provider.listNodes( impl, path ); } finally { pi.lock.readLock().unlock(); } } public void close(WorkspaceImpl impl) { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.close( impl ); } finally { pi.lock.writeLock().unlock(); } } } /** * Removes the item at the end of the path. * * @param impl * @param path * @throws RepositoryException */ public void remove(StoreTransaction tx, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); try { pi.lock.writeLock().lock(); pi.provider.remove( tx, path ); } finally { pi.lock.writeLock().unlock(); } } /** * Loads the state of a node from the repository. * * @param ws TODO * @param path * @return A brand new NodeImpl. * * @throws RepositoryException */ public NodeImpl loadNode( WorkspaceImpl ws, Path path ) throws RepositoryException { NodeImpl ni = null; Path ptPath = path.resolve( JCRConstants.Q_JCR_PRIMARYTYPE ); PropertyImpl primaryType = ws.createPropertyImpl( ptPath ); ValueContainer v = getPropertyValue( ws, ptPath ); if( v == null ) throw new RepositoryException("Repository did not return a primary type for path "+path); primaryType.loadValue( v.getValue() ); QName pt = ((QNameValue.Impl)v.getValue()).getQValue().getValue(); QNodeTypeManager ntm = QNodeTypeManager.getInstance(); QNodeType type = ntm.getNodeType( pt ); QNodeDefinition nd = type.findNodeDefinition( pt ); ni = ws.getSession().createNode( path, type, nd, false ); return ni; } /** * LOad the state of a single property from the repository. * * @param ws * @param ni * @param ptPath * @param name * @return * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private PropertyImpl loadProperty(WorkspaceImpl ws, NodeImpl ni, Path ptPath, QName name) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueContainer values = getPropertyValue( ws, ptPath ); PropertyImpl p = ws.createPropertyImpl( ptPath ); // // Find the proper property definition. // QPropertyDefinition pd = ni.getPrimaryQNodeType().findPropertyDefinition(name,values.isMultiple()); if( pd == null ) { for( NodeType mixin : ni.getMixinNodeTypes() ) { pd = ((QNodeType.Impl)mixin).getQNodeType().findPropertyDefinition( name, values.isMultiple() ); if( pd != null ) break; } if( pd == null ) throw new RepositoryException("Unable to locate property definition for nodetype "+ni.getPrimaryNodeType()+", name="+name); } p.setDefinition( pd.new Impl(ws.getSession()) ); // FIXME: Inoptimal if( values.isMultiple() ) p.loadValue( values.getValues(), values.getType() ); else p.loadValue( values.getValue() ); return p; } public void addNode(StoreTransaction tx, NodeImpl ni) throws RepositoryException { Path path = ni.getInternalPath(); if( !path.isRoot() && !itemExists(tx.getWorkspace(), path.getParentPath(), ItemType.NODE) ) throw new ConstraintViolationException("Parent path is missing for path "+path); ProviderInfo pi = getProviderInfo(tx.getWorkspace(),path); try { pi.lock.writeLock().lock(); pi.provider.addNode(tx, path, ni.getQDefinition()); } finally { pi.lock.writeLock().unlock(); } } public void copy(WorkspaceImpl m_workspace, Path srcpath, Path destpath) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } public NodeImpl findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); Path path = pi.provider.findByUUID(ws, uuid); return loadNode(ws, path); } catch(ItemNotFoundException e) {} finally { pi.lock.readLock().unlock(); } } throw new ItemNotFoundException("Could not locate a node by this UUID: "+uuid); } public ItemImpl getItem(WorkspaceImpl ws, Path path) throws InvalidPathException, RepositoryException { // // TODO: Not sure yet whether this optimization really makes sense. It appears to // work slightly faster, since it does not incur the overhead of two loadNodes() // if( false ) { try { NodeImpl ni = loadNode( ws, path ); return ni; } catch( RepositoryException e ) { if( path.isRoot() ) throw e; // Otherwise we just get a relatively unclear "root has no parent" NodeImpl ni = loadNode( ws, path.getParentPath() ); return loadProperty( ws, ni, path, path.getLastComponent() ); } } else { if( itemExists( ws, path, ItemType.NODE ) ) { return loadNode( ws, path ); } if( path.isRoot() ) throw new PathNotFoundException(); NodeImpl ni = loadNode( ws, path.getParentPath() ); return loadProperty( ws, ni, path, path.getLastComponent() ); } } public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.itemExists(ws, path, type); } finally { pi.lock.readLock().unlock(); } } public void putProperty(StoreTransaction tx, Path path, ValueContainer value ) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); + // + // Minor sanity check, as this could cause problems in the providers. + // + if( value.getType() == PropertyType.UNDEFINED ) + throw new ValueFormatException("Trying to save an UNDEFINED property type: "+path.toString(tx.getWorkspace().getSession())); + ValueContainer vc = value.deepClone(tx.getWorkspace().getSession()); try { pi.lock.writeLock().lock(); pi.provider.putPropertyValue( tx, path, vc ); } finally { pi.lock.writeLock().unlock(); } } public void stop() { + log.fine("Shutting down all providers..."); for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.stop(m_repository); } finally { pi.lock.writeLock().unlock(); } } + + m_providers = null; + m_repository = null; + m_workspaceAccess.clear(); } public Collection<? extends PropertyImpl> getReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { ArrayList<PropertyImpl> result = new ArrayList<PropertyImpl>(); List<Path> paths = new ArrayList<Path>(); for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); paths.addAll(pi.provider.findReferences( ws, uuid )); } finally { pi.lock.readLock().unlock(); } } for( Path path : paths ) { NodeImpl nd = loadNode( ws, path.getParentPath() ); result.add( nd.getProperty(ws.getSession().fromQName(path.getLastComponent())) ); } return result; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.listProperties(ws, path); } finally { pi.lock.readLock().unlock(); } } public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( ws.getName() ); try { pi.lock.writeLock().lock(); return pi.provider.storeStarted( ws ); } finally { pi.lock.writeLock().unlock(); } } public void storeFinished(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeFinished( tx ); } finally { pi.lock.writeLock().unlock(); } } public void storeCancelled(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeCancelled( tx ); } finally { pi.lock.writeLock().unlock(); } } /** * Stores information about a provider. */ private class ProviderInfo { public String[] workspaces; public RepositoryProvider provider; public ReadWriteLock lock; } /** * Returns the name of the default workspace. This is usually "default", but * it may change depending on how you configure Priha. * * @return */ public String getDefaultWorkspace() { return m_defaultWorkspaceName; } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.reorderNodes( tx, internalPath, childOrder ); } finally { pi.lock.writeLock().unlock(); } } } diff --git a/src/java/org/priha/core/RepositoryImpl.java b/src/java/org/priha/core/RepositoryImpl.java index ff05f3b..e4676a4 100644 --- a/src/java/org/priha/core/RepositoryImpl.java +++ b/src/java/org/priha/core/RepositoryImpl.java @@ -1,405 +1,413 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import org.priha.Release; import org.priha.core.namespace.NamespaceRegistryImpl; +import org.priha.path.PathManager; import org.priha.util.ConfigurationException; import org.priha.util.FileUtil; /** * Provides the main Repository class for Priha. You may use this * by simply instantiating it with a suitable Properties object. * <p> * Any property may be overridden also from the command line using * a system property. */ public class RepositoryImpl implements Repository { public static final String DEFAULT_WORKSPACE = "default"; private static NamespaceRegistryImpl c_namespaceRegistry = new NamespaceRegistryImpl(); - + private static PathManager c_pathManager = new PathManager(); + private RepositoryState m_state = RepositoryState.DEAD; /** * Defines which paths are attempted to locate the default property file. */ private static final String[] DEFAULT_PROPERTIES = { "/priha_default.properties", "/WEB-INF/priha_default.properties" }; private Properties m_properties; private Logger log = Logger.getLogger( getClass().getName() ); private SessionManager m_sessionManager; private ProviderManager m_providerManager; - + /** * Create a new Repository using the given properties. Any property which is not * set will be read from the default properties (priha_default.properties). * * @param prefs Properties to use. Must not be null. * @throws ConfigurationException If the properties are wrong. */ public RepositoryImpl( Properties prefs ) throws ConfigurationException { m_state = RepositoryState.STARTING; try { Properties defaultProperties = FileUtil.findProperties(DEFAULT_PROPERTIES); if( defaultProperties.isEmpty() ) throw new ConfigurationException("Default properties not found - broken distribution!?!"); m_properties = new Properties(defaultProperties); } catch (IOException e) { throw new ConfigurationException("Loading of default properties failed"); } if( prefs.isEmpty() ) log.warning("No \"priha.properties\" found, using just the default properties"); m_properties.putAll( prefs ); Runtime.getRuntime().addShutdownHook( new ShutdownThread() ); log.info( "G'day, Matilda! Priha "+Release.VERSTR+" has been initialized." ); log.fine( "Using configuration from "+prefs.toString() ); m_state = RepositoryState.LIVE; } public String getProperty(String key) { String prop = System.getProperty(key, m_properties.getProperty(key)); return prop; } public String getProperty( String key, String defValue ) { String prop = System.getProperty( key, m_properties.getProperty(key,defValue) ); return prop; } protected ProviderManager getProviderManager() throws ConfigurationException { if( m_providerManager == null ) { log.info( "Initializing providers..." ); long start = System.currentTimeMillis(); m_providerManager = new ProviderManager(this); long end = System.currentTimeMillis(); log.info( "Repository initialization took "+(end-start)+" ms." ); } return m_providerManager; } + protected static PathManager getPathManager() + { + return c_pathManager; + } + protected SessionManager getSessionManager() { if( m_sessionManager == null ) { log.info( "Initializing SessionManager..." ); m_sessionManager = new SessionManager(); } return m_sessionManager; } /** * Set transient properties for this repository. These are not saved anywhere, but they * might be something that you can use to control the Repository behaviour with. * @param key * @param property */ public void setProperty(String key, String property) { m_properties.setProperty(key,property); } @SuppressWarnings("unchecked") public Enumeration<String> getPropertyNames() { return (Enumeration<String>)m_properties.propertyNames(); } public String getDescriptor(String key) { for( int i = 0; i < Release.DESCRIPTORS.length; i += 2 ) { if( Release.DESCRIPTORS[i].equals(key) ) { return Release.DESCRIPTORS[i+1]; } } return null; } public String[] getDescriptorKeys() { String[] keys = new String[Release.DESCRIPTORS.length/2]; for( int i = 0; i < Release.DESCRIPTORS.length; i += 2 ) { keys[i/2] = Release.DESCRIPTORS[i]; } return keys; } private String getDefaultWorkspace() throws ConfigurationException { return getProviderManager().getDefaultWorkspace(); } public synchronized SessionImpl login(Credentials credentials, String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { if( m_state != RepositoryState.LIVE ) { throw new RepositoryException("Repository is not alive. It is "+m_state); } long start = System.currentTimeMillis(); if( workspaceName == null ) workspaceName = getDefaultWorkspace(); getProviderManager().open( credentials, workspaceName ); SessionImpl session = getSessionManager().openSession( credentials, workspaceName ); session.refresh(false); long end = System.currentTimeMillis(); if( log.isLoggable(Level.FINER) ) log.finer("Login completed and new Session created; took "+(end-start)+" ms."); return session; } public SessionImpl login(Credentials credentials) throws LoginException, RepositoryException { return login( credentials, null ); } public SessionImpl login(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { return login( null, workspaceName ); } public SessionImpl login() throws LoginException, RepositoryException { return login( null, null ); } /** * Shuts down the entire repository, stops all providers and releases * resources. After this call you can restart the repository by either * calling login(), or creating a new RepositoryImpl instance. */ public void shutdown() { m_state = RepositoryState.SHUTTING; // // Close all open sessions. // visit( new SessionVisitor() { public void visit(SessionImpl session) { session.logout(); } }); // // Stop the ProviderManager and release providers. // if( m_providerManager != null ) { m_providerManager.stop(); } m_providerManager = null; m_sessionManager = null; + c_pathManager.close(); m_state = RepositoryState.DEAD; } /** * Returns a Session which has write permissions to the repository. Normally, the * user has no reason to use this method - it is used internally to sometimes modify * the repo. * <p> * This method is guaranteed to always return a Session which has all permissions * into the repository - assuming the underlying repository implementation does not * have any limitations (which it normally should not have). * * @param workspaceName The workspace to which the login is done. * @return A Priha SessionImpl object. * @throws LoginException * @throws NoSuchWorkspaceException * @throws RepositoryException */ public SessionImpl superUserLogin(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { SessionImpl s = login( null, workspaceName ); s.setSuper(true); return s; } public static NamespaceRegistryImpl getGlobalNamespaceRegistry() { return c_namespaceRegistry; } /** * Visits all current Sessions * * @param v */ protected void visit( SessionVisitor v ) { synchronized( getSessionManager().m_sessions ) { for( Iterator<WeakReference<SessionImpl>> i = getSessionManager().m_sessions.iterator(); i.hasNext(); ) { WeakReference<SessionImpl> wr = i.next(); SessionImpl si = wr.get(); if( si != null ) v.visit(si); else i.remove(); } } } protected void removeSession(SessionImpl s) { getSessionManager().closeSession(s); } /** * The SessionManager holds a list of Sessions currently owned by this Repository. This * is used to manage the proper shutdown of the Sessions. * */ // FIXME: Should probably have a ReferenceQueue for cleaning away things like locks, etc. private class SessionManager { private ArrayList<WeakReference<SessionImpl>> m_sessions = new ArrayList<WeakReference<SessionImpl>>(); public SessionImpl openSession( Credentials credentials, String workspaceName ) throws RepositoryException { synchronized(m_sessions) { SessionImpl session = new SessionImpl( RepositoryImpl.this, credentials, workspaceName ); m_sessions.add( new WeakReference<SessionImpl>(session) ); return session; } } public void closeSession( SessionImpl s ) { // // Make sure that if we're in the midst of shutdown, these get removed // automatically. // if( m_state == RepositoryImpl.RepositoryState.SHUTTING ) return; synchronized(m_sessions) { for( Iterator<WeakReference<SessionImpl>> i = m_sessions.iterator(); i.hasNext(); ) { WeakReference<SessionImpl> wr = i.next(); SessionImpl si = wr.get(); if( si == null || si == s ) { i.remove(); break; } } // FIXME: Should really check if there is a Session for this workspace // so that we can call ProviderManager.close(); } } } protected interface SessionVisitor { public void visit( SessionImpl session ); } /** * Stops the Provider which stores all the things in this Repository. This is used to * manage a sane shutdown. */ private class ShutdownThread extends Thread { @Override public void run() { log.info( "Running shutdown process (repository closed due to JVM termination)" ); shutdown(); } } private enum RepositoryState { LIVE, SHUTTING, STARTING, DEAD }; } diff --git a/src/java/org/priha/core/SessionImpl.java b/src/java/org/priha/core/SessionImpl.java index b4bf056..9955475 100644 --- a/src/java/org/priha/core/SessionImpl.java +++ b/src/java/org/priha/core/SessionImpl.java @@ -1,810 +1,812 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.AccessControlException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.QLock; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceMapper; import org.priha.core.values.ValueFactoryImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.PathManager; import org.priha.path.PathRef; import org.priha.path.Path.Component; import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.xml.*; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * The SessionImpl class implements a JCR Session. It is non thread safe, * so each Thread must have its own Session. */ public class SessionImpl implements Session, NamespaceMapper { static final String PRIHA_OLD_PATH = "priha:oldPath"; private static final String JCR_SYSTEM = "jcr:system"; /** * This is a magical property which gets added to a Node whenever * a move occurs. It's value is a Path which points from source to target * and target to source nodes which have been saved - it's point is * to make sure that the user will save both the source and the target * at the same time. This property is never saved to the Provider. */ static final String MOVE_CONSTRAINT = "priha:moveConstraint"; private RepositoryImpl m_repository; private WorkspaceImpl m_workspace; private List<String> m_lockTokens = new ArrayList<String>(); private SimpleCredentials m_credentials; private Logger log = Logger.getLogger( getClass().getName() ); private boolean m_isSuperSession = false; private ValueFactoryImpl m_valueFactory = new ValueFactoryImpl(this); private String m_sessionId = UUID.randomUUID().toString(); protected SessionProvider m_provider; public SessionImpl( RepositoryImpl rep, Credentials creds, String name ) throws RepositoryException { m_repository = rep; m_workspace = new WorkspaceImpl( this, name, rep.getProviderManager() ); m_provider = new SessionProvider( this, rep.getProviderManager() ); if( creds instanceof SimpleCredentials ) { m_credentials = (SimpleCredentials)creds; } if( !hasNode("/") ) { repopulate(); } } public String getId() { return m_sessionId; } public boolean setSuper(boolean value) { boolean oldval = m_isSuperSession; m_isSuperSession = value; return oldval; } /** * Returns true, if this Session should be considered to be a supersession, * which can do whatever it wants (that is, mostly ignore any Constraint Violations. * <p> * One should be careful, since it is possible with this method to end up in * a repository with an inconsistent state. * * @return */ public boolean isSuper() { return m_isSuperSession; } public List<Path> listNodes( Path parentpath ) throws RepositoryException { return m_provider.listNodes(parentpath); } boolean hasNode( String absPath ) throws RepositoryException { return hasNode( PathFactory.getPath(this,absPath) ); } public boolean hasNode( Path absPath ) throws RepositoryException { checkLive(); return m_provider.itemExists( absPath, ItemType.NODE ); } boolean hasProperty( Path absPath ) throws RepositoryException { checkLive(); return m_provider.itemExists( absPath, ItemType.PROPERTY ); } public void addLockToken(String lt) { m_lockTokens.add(lt); } /** * Any credentials are fine to give full access. */ public void checkPermission(String absPath, String actions) throws AccessControlException, RepositoryException { checkLive(); actions = actions.trim(); if( actions.equals( "read" ) ) return; if( m_credentials == null && !isSuper() ) throw new AccessControlException("Read-only session"); return; } /** Quick way to check for write permissions. */ protected void checkWritePermission() throws AccessControlException, RepositoryException { try { checkPermission("/","add_node"); } catch( AccessControlException e ) { throw new AccessDeniedException(e.getMessage()); } } public Object getAttribute(String name) { Object res = null; if( m_credentials != null ) { res = m_credentials.getAttribute(name); } return res; } public String[] getAttributeNames() { if( m_credentials != null ) { return m_credentials.getAttributeNames(); } return new String[0]; } public ItemImpl getItem( Path absPath ) throws PathNotFoundException, RepositoryException { checkLive(); ItemImpl ii = m_provider.getItem( absPath ); return ii; } public ItemImpl getItem(String absPath) throws PathNotFoundException, RepositoryException { return getItem( PathFactory.getPath(this,absPath) ); } public String[] getLockTokens() { return m_lockTokens.toArray( new String[m_lockTokens.size()] ); } public NodeImpl getNodeByUUID(String uuid) throws ItemNotFoundException, RepositoryException { checkLive(); return m_provider.findByUUID(uuid); } public RepositoryImpl getRepository() { return m_repository; } public NodeImpl getRootNode() throws RepositoryException { return (NodeImpl) getItem(Path.ROOT); } public String getUserID() { return "anonymous"; } public ValueFactoryImpl getValueFactory() throws UnsupportedRepositoryOperationException, RepositoryException { checkLive(); return m_valueFactory; } public WorkspaceImpl getWorkspace() { return m_workspace; } public boolean hasPendingChanges() throws RepositoryException { checkLive(); return m_provider.hasPendingChanges(); } public Session impersonate(Credentials credentials) throws LoginException, RepositoryException { checkLive(); return m_repository.login( credentials, getWorkspace().getName() ); } public final boolean isLive() { return m_workspace != null; } private final void checkLive() throws RepositoryException { if( !isLive() ) throw new RepositoryException("This Session is no longer live and cannot be used."); } public boolean itemExists(String absPath) throws RepositoryException { checkLive(); return itemExists( PathFactory.getPath(this,absPath) ); } public void logout() { if( isLive() ) { m_repository.removeSession(this); LockManager.getInstance(m_workspace).expireSessionLocks( this ); m_workspace.logout(); + m_provider.logout(); + m_workspace = null; } } /** * A convenience class to move stuff based on Paths instead of Strings. */ public void move( Path srcPath, Path destPath ) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, NamespaceException, RepositoryException { // FIXME: This should really be the main routine move( srcPath.toString( this ), destPath.toString(this) ); } public void move(String srcAbsPath, String destAbsPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { checkLive(); checkWritePermission(); internalMove(srcAbsPath,destAbsPath,true); } public void internalMove( Path srcPath, Path destPath, boolean obeyConstraints ) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, NamespaceException, RepositoryException { // FIXME: This should really be the main routine internalMove( srcPath.toString( this ), destPath.toString(this), obeyConstraints ); } /** * Moves work as follows: * <ol> * <li>We add a new Node to the destAbsPath * <li>We copy all properties from the old Node to the new Node * <li>The old Node gets tagged with a property "priha:oldPath" which contains the current path * <li>The Path of the old Node (and all other Nodes which refer to it) is changed to point at the new location * <li>The Node is marked as being MOVED instead of REMOVED. * </ol> */ public void internalMove(String srcAbsPath, String destAbsPath, boolean obeyConstraints) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); if( destAbsPath.endsWith("]") && !isSuper() ) throw new ConstraintViolationException("Destination path must not have an index as its final component."); boolean isSuper = setSuper( true ); try { Path path = PathFactory.getPath( this, destAbsPath ); if( m_workspace.isCheckedIn( (NodeImpl)getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( hasNode( path ) ) { throw new ItemExistsException("Destination node "+getWorkspace().getName()+":"+path.toString(this)+" already exists!"); } NodeImpl srcnode = getRootNode().getNode(srcAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( m_workspace ); if( lm.findLock( srcnode.getParent().getInternalPath() ) != null ) throw new LockException( "Lock on source path prevents move" ); QLock lock = lm.findLock( srcnode.getInternalPath() ); if( lock != null ) lm.moveLock( lock, PathFactory.getPath(newDestPath) ); NodeImpl destnode = getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); destnode.tag( PRIHA_OLD_PATH, srcnode.getPath() ); for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); String newPath = destAbsPath + "/" + relPath; System.out.println("Child path move "+child.getPath()+" => "+newPath ); internalMove( child.getPath(), newPath, obeyConstraints ); } for( PropertyIterator pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = (PropertyImpl)pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> "+newDestPath // ); // Primary type has already been set, so we won't move that. if( !p.getName().equals( "jcr:primaryType" ) ) { if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } p.remove(); } // Set up move constraints (that is, making sure the user can only save // a top node, and not just moved bits). if( obeyConstraints ) { srcnode.getParent().tag( MOVE_CONSTRAINT, destnode.getParent().getPath() ); destnode.getParent().tag( MOVE_CONSTRAINT, srcnode.getParent().getPath() ); } // Since this is a move op, we want to make sure that the old path // does not change. //srcnode.freezePath(); // Finally, remove the source node. //srcnode.remove(); srcnode.enterState( ItemState.MOVED ); // m_provider.remove( srcnode ); // FIXME: Make sure this is ok getPathManager().move( srcnode.getInternalPath(), destnode.getInternalPath() ); // FIXME: OK with new ChangeStore? } finally { setSuper( isSuper ); } } void refresh( boolean keepChanges, Path path ) throws RepositoryException { checkLive(); m_provider.refresh( keepChanges, path ); } public void refresh(boolean keepChanges) throws RepositoryException { refresh( keepChanges, Path.ROOT ); } /** * This method makes sure that certain default stuff is available. * @throws RepositoryException */ private void repopulate() throws RepositoryException { boolean isSuper = setSuper(true); if( !hasNode("/") ) { NodeImpl ni = null; log.info("Repository empty; setting up root node..."); QNodeType rootType = getWorkspace().getNodeTypeManager().getNodeType("nt:unstructured").getQNodeType(); QNodeDefinition nd = rootType.findNodeDefinition( QName.valueOf("*") ); ni = new NodeImpl( this, "/", rootType, nd, true ); ni.enterState( ItemState.NEW ); ni.addMixin( "mix:referenceable" ); // Make referenceable. //m_provider.addNode( ni ); ni.sanitize(); save(); } if( !hasNode("/"+JCR_SYSTEM) ) { getRootNode().addNode(JCR_SYSTEM, "nt:unstructured"); // FIXME: Should probably set up all sorts of things. save(); } setSuper(isSuper); } public void removeLockToken(String lt) { m_lockTokens.remove(lt); } public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { saveNodes( Path.ROOT ); } /** * Saves all modified nodes that start with the given path prefix. This * can be used to save a node and all its children. * * @param pathprefix * @throws RepositoryException */ protected void saveNodes( Path pathprefix ) throws RepositoryException { checkLive(); checkWritePermission(); m_provider.save( pathprefix ); } public boolean itemExists( Path absPath ) throws RepositoryException { return hasNode(absPath) || hasProperty(absPath); } public void remove(ItemImpl itemImpl) throws RepositoryException { checkLive(); checkWritePermission(); m_provider.remove( itemImpl ); } public List<PropertyImpl> getReferences(String uuid) throws RepositoryException { checkLive(); return m_provider.getReferences( uuid ); } /* ========================================================================= */ /* XML import/export */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, VersionException, InvalidSerializedDataException, LockException, RepositoryException { checkLive(); checkWritePermission(); XMLImport importer = new XMLImport( this, false, PathFactory.getPath(this,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { log.log( Level.WARNING, "Could not get SAX parser", e ); throw new RepositoryException("Could not get SAX parser, please check logs."); } catch (SAXException e) { log.log( Level.WARNING, "Importing failed", e ); if( e.getException() != null && e.getException() instanceof RepositoryException ) throw (RepositoryException) e.getException(); throw new InvalidSerializedDataException("Importing failed: "+e.getMessage()); } } public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, RepositoryException { XMLImport importer = new XMLImport( this, false, PathFactory.getPath(this,parentAbsPath), uuidBehavior ); return importer; } public void exportDocumentView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse) throws PathNotFoundException, SAXException, RepositoryException { checkLive(); XMLExport export = new XMLDocExport(this); export.export( absPath, contentHandler, skipBinary, noRecurse ); } public void exportDocumentView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse) throws IOException, PathNotFoundException, RepositoryException { checkLive(); XMLExport export = new XMLDocExport( this ); ContentHandler handler = new StreamContentHandler( out ); try { export.export( absPath, handler, skipBinary, noRecurse ); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void exportSystemView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse) throws PathNotFoundException, SAXException, RepositoryException { checkLive(); XMLExport export = new XMLSysExport( this ); export.export( absPath, contentHandler, skipBinary, noRecurse ); } public void exportSystemView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse) throws IOException, PathNotFoundException, RepositoryException { checkLive(); XMLExport export = new XMLSysExport( this ); ContentHandler handler = new StreamContentHandler( out ); try { export.export( absPath, handler, skipBinary, noRecurse ); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* ========================================================================= */ /* Namespaces */ /** Maps prefixes to URIs. Prefixes are always unique, therefore they are the keys */ private HashMap<String,String> m_nsmap = new HashMap<String,String>(); public void setNamespacePrefix(String newPrefix, String existingUri) throws NamespaceException, RepositoryException { checkLive(); // Throws an exception if the URI does not exist, so this is a cheap way to check for validity. m_workspace.getNamespaceRegistry().getPrefix(existingUri); if( newPrefix.toLowerCase().startsWith("xml") ) throw new NamespaceException("No namespace starting with 'xml' may be remapped (6.3.3)"); String currentUri = null; try { currentUri = m_workspace.getNamespaceRegistry().getURI( newPrefix ); } catch( NamespaceException e ) {} if( currentUri != null && currentUri.equals(existingUri) ) { throw new NamespaceException("Existing prefix cannot be remapped (6.3.3)"); } PathFactory.reset(); m_nsmap.put(newPrefix, existingUri ); } public String getNamespacePrefix(String uri) throws NamespaceException, RepositoryException { checkLive(); for( Map.Entry<String, String> e : m_nsmap.entrySet() ) { if( e.getValue().equals( uri ) ) return e.getKey(); } return m_workspace.getNamespaceRegistry().getPrefix(uri); } public String[] getNamespacePrefixes() throws RepositoryException { checkLive(); Set<String> prefixes = new TreeSet<String>(); Set<String> uris = new TreeSet<String>(); uris.addAll( m_nsmap.values() ); uris.addAll( Arrays.asList( m_workspace.getNamespaceRegistry().getURIs() ) ); for( String u : uris ) { prefixes.add( getNamespacePrefix( u ) ); } return prefixes.toArray( new String[prefixes.size()] ); } public String getNamespaceURI(String prefix) throws NamespaceException, RepositoryException { checkLive(); String uri = m_nsmap.get(prefix); if( uri == null ) { return m_workspace.getNamespaceRegistry().getURI(prefix); } return uri; } public String fromQName(QName c) { if( c == null ) return null; try { String uri = c.getNamespaceURI(); if( uri.length() > 0 ) { String prefix = getNamespacePrefix( uri ); return prefix+":"+c.getLocalPart(); } } catch( Exception e ) { } return c.getLocalPart(); } public QName toQName(String c) throws NamespaceException, RepositoryException { checkLive(); if( c == null ) return null; if( c.indexOf( '{' ) != -1 ) throw new RepositoryException("Already in QName format: "+c); int idx = c.indexOf(':'); if( idx != -1 ) { String prefix = c.substring(0,idx); String name = c.substring(idx+1); String uri = getNamespaceURI( prefix ); return new QName( uri, name, prefix ); } return new QName(c); } /** * This method creates a correct Node subclass based on the NodeType. It * can return Version or VersionHistory objects, as well as regular Nodes. * * @param absPath * @param assignedType * @param assignedNodeDef * @return * @throws RepositoryException */ protected NodeImpl createNode(Path absPath, QNodeType assignedType, QNodeDefinition assignedNodeDef, boolean initDefaults) throws RepositoryException { NodeImpl ni; if( assignedType.isNodeType(JCRConstants.Q_NT_VERSION) ) { ni = new VersionImpl( this, absPath, assignedType, assignedNodeDef, initDefaults ); } else if( assignedType.isNodeType(JCRConstants.Q_NT_VERSIONHISTORY) ) { ni = new VersionHistoryImpl( this, absPath, assignedType, assignedNodeDef, initDefaults ); } else { ni = new NodeImpl( this, absPath, assignedType, assignedNodeDef, initDefaults ); } return ni; } public String toString() { return "Session["+(isSuper()?"SUPER":"")+"]"; } /** * This method provides debug information about the state of the Session. Do not rely * it giving it in any particular format. The dump will be done to the System.out stream. */ public void dump() { System.out.println(this); m_provider.m_changedItems.dump(); } /** * Shortcut for getPathManager().getPath(). * @param p * @return * @throws PathNotFoundException */ public Path getPath(PathRef p) throws PathNotFoundException { return m_provider.getPath( p ); } public PathManager getPathManager() { return m_provider.getPathManager(); } public void rename(Path path1, Component newName) { System.out.println("Renaming "+path1+" to "+newName); } } diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index 8c57312..7acc767 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,916 +1,917 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.ChangeStore; import org.priha.util.QName; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private - // FIXME: Should probably be elsewhere - private static PathManager c_sessionPathManager = new PathManager(); - private static final String PROP_SESSIONCACHESIZE = "priha.session.cacheSize"; private static final String PROP_MAXITEMSIZE = "priha.session.maxCachedItemSize"; private int m_maxItemSize; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(); // // The listed defaults here just exist so that something sane would be there. The defaults // are really read from the priha_defaults.properties or user settings. // int cacheSize = Integer.parseInt(session.getRepository().getProperty( PROP_SESSIONCACHESIZE, "1000" )); m_maxItemSize = Integer.parseInt(session.getRepository().getProperty( PROP_MAXITEMSIZE, "2048") ); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(cacheSize); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(cacheSize); log.fine("Initialized SessionProvider with session cache size of "+cacheSize+" items, of max "+m_maxItemSize+" bytes"); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Puts a single Item into the internal caches. * * @param ii Item to cache * @param uuid UUID, or may be null. */ private final void cache( final ItemImpl ii, final String uuid ) { if( ii instanceof PropertyImpl ) { // // Don't cache very large objects. // if( ((PropertyImpl)ii).getValueContainer().getSize() > m_maxItemSize ) return; } m_fetchedItems.put(ii.getPathReference(), ii); if( uuid != null ) { m_uuidMap.put(uuid, (NodeImpl) ii); } } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) cache( ii, null ); return ii; } - public void close() + public void logout() { - m_source.close( m_workspace ); + m_changedItems.clear(); + m_fetchedItems.clear(); + m_uuidMap.clear(); + m_workspace = null; + m_source = null; } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { cache( ii, uuid ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { // // It's faster to use a LinkedHashSet here, then copy to an ArrayList // when exiting. // Set<Path> res = new LinkedHashSet<Path>(); for( Change c : m_changedItems.getLatestChangesForParent(parentpath) ) { ItemImpl ni = c.getItem(); if( ni.isNode() ) { Path path = ni.getInternalPath(); if( !res.contains(path) && c.getState() != ItemState.REMOVED ) { res.add( path ); } } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } ArrayList<Path> ls = new ArrayList<Path>(res.size()); ls.addAll( res ); return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean itemExists(Path path, ItemType type) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && ((type == ItemType.NODE && c.getItem().isNode()) || (type == ItemType.PROPERTY && !c.getItem().isNode()) ) ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } ItemImpl ii = m_fetchedItems.get(getPathManager().getPathRef(path)); if( ii != null && ((type == ItemType.NODE && ii.isNode()) || (type == ItemType.PROPERTY && !ii.isNode())) ) return true; return m_source.itemExists(m_workspace, path, type); } public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; ChangeStore changesDone = new ChangeStore(); try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); cache(ni,null); break; case REMOVED: if( !m_source.itemExists( m_workspace, change.getPath(), ItemType.NODE ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case REORDERED: // Reordering has been done by UPDATED, so we just fire some extra events here. Change oldChange; while( (oldChange = changesDone.getLatestChange(change.getPath())) != null ) { if( (oldChange.getState() == ItemState.NEW || oldChange.getState() == ItemState.REMOVED ) || oldChange.getState() == ItemState.MOVED ) { changesDone.remove(oldChange); } } changesDone.add( ItemState.REMOVED, ni ); changesDone.add( ItemState.NEW, ni ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); cache(pi,null); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } changesDone.add( change ); } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; m_workspace.getObservationManager().fireEvents( changesDone ); } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends Path> listProperties(Path path) throws RepositoryException { LinkedHashSet<Path> result = new LinkedHashSet<Path>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.add( path.resolve(pName) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been added. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Change c : m_changedItems.getLatestChangesForParent(path) ) { ItemImpl ii = c.getItem(); if( ii.isNode() == false && (c.getState() != ItemState.REMOVED && c.getState() != ItemState.MOVED ) ) { Path p = ii.getInternalPath(); if( p.getParentPath().equals(path) ) { result.add( p ); } } } return result; } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.itemExists( m_workspace, path, ItemType.NODE ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { super( 16, 0.75f, true ); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { this(MAX_SIZE); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { - return c_sessionPathManager.getPath( p ); + return RepositoryImpl.getPathManager().getPath( p ); } public PathManager getPathManager() { - return c_sessionPathManager; + return RepositoryImpl.getPathManager(); } /** * Get the current modified state of a Path. * * @param path * @return Null, if the state does not exist in the change log. */ public ItemState getState( Path path ) { Change c = m_changedItems.getLatestChange( path ); return c != null ? c.getState() : null; } public ItemState getState( PathRef m_path ) throws PathNotFoundException { return getState( getPathManager().getPath(m_path) ); } } diff --git a/src/java/org/priha/core/WorkspaceImpl.java b/src/java/org/priha/core/WorkspaceImpl.java index bb7299f..0a7e216 100644 --- a/src/java/org/priha/core/WorkspaceImpl.java +++ b/src/java/org/priha/core/WorkspaceImpl.java @@ -1,522 +1,524 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.UUID; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.observation.ObservationManager; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceRegistryImpl; import org.priha.core.observation.ObservationManagerImpl; import org.priha.nodetype.QNodeTypeManager; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.query.PrihaQueryManager; import org.priha.util.LazyPropertyIteratorImpl; import org.priha.xml.XMLImport; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Implements a JCR Workspace. This class mostly functions as a facade for * ProviderManager, which takes care of the actual repository management. */ public class WorkspaceImpl implements Workspace { private SessionImpl m_session; private String m_name; private ProviderManager m_providerManager; private QNodeTypeManager.Impl m_nodeTypeManager; private Logger log = Logger.getLogger(WorkspaceImpl.class.getName()); /** * Create a new Workspace instance. * * @param session The SessionImpl to which this Workspace is tied to * @param name The name of the Workspace * @param mgr The ProviderManager instance which owns the repository. * @throws RepositoryException If a NodeTypeManager cannot be instantiated. */ public WorkspaceImpl( SessionImpl session, String name, ProviderManager mgr ) throws RepositoryException { m_session = session; m_name = name; m_providerManager = mgr; m_nodeTypeManager = QNodeTypeManager.getManager(this); } /** * Creates a new property implementation without a property definition. * This is meant for providers to create an "empty" property definition, * which the WorkspaceImpl will then update later on. * * @param path * @return * @throws RepositoryException */ public PropertyImpl createPropertyImpl( Path path ) throws RepositoryException { // String name = path.getLastComponent(); //NodeImpl nd = (NodeImpl) m_session.getItem(p); //PropertyDefinition pd = ((GenericNodeType)nd.getPrimaryNodeType()).findPropertyDefinition(name); PropertyImpl pi = new PropertyImpl( m_session, path, null ); return pi; } /** * If removeExisting is true, removes Nodes with conflicting UUIDs. If it's false, * this exists with a ItemExistsException. * * Does not save the Session. * * @param srcNode * @param removeExisting * @throws RepositoryException */ private void checkUUIDs( NodeImpl srcNode, boolean removeExisting ) throws RepositoryException { try { String uuid = srcNode.getUUID(); Node n = getSession().getNodeByUUID( uuid ); if( removeExisting ) { System.out.println("Removing node due to UUID conflict "+n); n.remove(); } else { throw new ItemExistsException("There already exists a Node by UUID "+uuid+" in the destination workspace! "+n.getPath()); } } catch( UnsupportedRepositoryOperationException e ) { // Fine, this node just does not have an UUID. } catch( ItemNotFoundException e ) { // Fine, expected as well. } for( NodeIterator ni = srcNode.getNodes(); ni.hasNext(); ) { checkUUIDs( (NodeImpl)ni.nextNode(), removeExisting ); } } /** * {@inheritDoc} */ public void clone(String srcWorkspace, String srcAbsPath, String destAbsPath, boolean removeExisting) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { checkLock(destAbsPath); getSession().checkWritePermission(); SessionImpl srcSession = getSession().getRepository().login(srcWorkspace); boolean isSuper = m_session.setSuper( true ); try { // // Do the check here, since once we're in super mode, addNode() will happily // allow adding to an indexed path. // if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot clone to a path which ends with an index."); if( removeExisting && getSession().itemExists( destAbsPath ) ) { // getSession().getItem( destAbsPath ).remove(); //getSession().save(); } checkUUIDs( (NodeImpl)srcSession.getItem( srcAbsPath ), removeExisting ); //getSession().save(); copy( srcSession, srcAbsPath, destAbsPath, true ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * {@inheritDoc} */ public void copy(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { copy( getName(), srcAbsPath, destAbsPath ); } /** * Throws a LockException if the given absolute path or any of its child nodes * is locked. */ private void checkLock( String abspath ) throws LockException, RepositoryException { LockManager lm = LockManager.getInstance( this ); if( lm.findLock( PathFactory.getPath( m_session, abspath ) ) != null ) throw new LockException("Destination path "+abspath+" is locked and cannot be modified."); } /** * {@inheritDoc} */ public void copy(String srcWorkspace, String srcAbsPath, String destAbsPath) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Destination path must not end with an index."); SessionImpl srcSession = getSession().getRepository().login( srcWorkspace ); // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); boolean isSuper = m_session.setSuper( true ); try { copy( srcSession, srcAbsPath, destAbsPath, false ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * Checks if the node or any of its parents are checked in. * * @param n * @return * @throws RepositoryException */ protected boolean isCheckedIn( NodeImpl n ) throws RepositoryException { if( !n.isCheckedOut() ) return true; if( n.getInternalPath().isRoot() ) return false; return isCheckedIn( n.getParent() ); } /** * Performs the actual copy, but does not save. * * @param srcSession * @param srcAbsPath * @param destAbsPath * @throws NoSuchWorkspaceException * @throws ConstraintViolationException * @throws VersionException * @throws AccessDeniedException * @throws PathNotFoundException * @throws ItemExistsException * @throws LockException * @throws RepositoryException */ protected void copy(SessionImpl srcSession, String srcAbsPath, String destAbsPath, boolean preserveUUIDs ) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { Path path = PathFactory.getPath( getSession(), destAbsPath ); if( isCheckedIn( (NodeImpl)m_session.getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( m_session.hasNode( destAbsPath ) ) { NodeImpl nx = getSession().getRootNode().getNode(destAbsPath); if( !nx.getDefinition().allowsSameNameSiblings() ) throw new ItemExistsException("Destination node "+destAbsPath+" already exists, and does not allow same name siblings!"); } NodeImpl srcnode = srcSession.getRootNode().getNode(srcAbsPath); // System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( srcSession.getWorkspace() ); if( lm.hasChildLock( srcnode.getInternalPath() ) ) throw new LockException( "Lock on source path prevents copy" ); NodeImpl destnode = m_session.getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); if( isCheckedIn( destnode ) ) { throw new VersionException("Destination node "+destnode.getPath()+" (or one of its parent nodes) is checked in, and therefore unmodifiable."); } for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); copy( srcSession, child.getPath(), destAbsPath + "/" + relPath, preserveUUIDs ); } for( LazyPropertyIteratorImpl pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> // "+newDestPath // ); // // The primary type is already set above upon the creation of the Node. // if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE )) continue; // // Section 7.1.7; the new node must get a new UUID when copying; // but we allow UUIDs to be preserved for e.g. clone. // if( p.getQName().equals( JCRConstants.Q_JCR_UUID) && !preserveUUIDs ) { destnode.setProperty( p.getName(), UUID.randomUUID().toString() ); } else { // // Copy the property // if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } } } /** * {@inheritDoc} */ public String[] getAccessibleWorkspaceNames() throws RepositoryException { Collection<String> list = m_providerManager.listWorkspaces(); return list.toArray(new String[0]); } /** * {@inheritDoc} */ // FIXME: SuperUserSession leaks. public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession,true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); return importer; } /** * {@inheritDoc} */ public String getName() { return m_name; } /** * {@inheritDoc} */ public NamespaceRegistryImpl getNamespaceRegistry() throws RepositoryException { return RepositoryImpl.getGlobalNamespaceRegistry(); } /** * {@inheritDoc} */ public QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_nodeTypeManager; } /** * Unsupported at the moment. */ public ObservationManagerImpl.Impl getObservationManager() throws UnsupportedRepositoryOperationException, RepositoryException { return ObservationManagerImpl.getInstance(this); } /** * {@inheritDoc} */ public PrihaQueryManager getQueryManager() throws RepositoryException { return new PrihaQueryManager(getSession()); } /** * {@inheritDoc} */ public SessionImpl getSession() { return m_session; } /** * {@inheritDoc} */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, InvalidSerializedDataException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession, true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { throw new RepositoryException("Could not get SAX parser!",e); } catch (SAXException e) { if( e.getException() != null && (e.getException() instanceof RepositoryException) ) { throw (RepositoryException) e.getException(); } throw new InvalidSerializedDataException("Importing failed",e); } finally { suSession.logout(); } } /** * Implemented simply by starting a new Session, which then performs the copy, * and then calling save() on it. */ public void move(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot move to a path with an index in the name"); SessionImpl s = m_session.getRepository().superUserLogin( getName() ); try { s.move( srcAbsPath, destAbsPath ); s.save(); } finally { s.logout(); } } /** * Unsupported at the moment. */ public void restore(Version[] versions, boolean removeExisting) throws ItemExistsException, UnsupportedRepositoryOperationException, VersionException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Workspace.restore()"); } /** * Performs a logout; to be called by SessionImpl only. */ public void logout() { m_providerManager.close(this); + LockManager lm = LockManager.getInstance( this ); + lm.logout(); } /** * Checks directly from the repository if an item exists. * * @param path * @return * @throws InvalidPathException */ public boolean nodeExists(Path path) throws RepositoryException { return m_providerManager.itemExists(this, path, ItemType.NODE); } } diff --git a/src/java/org/priha/core/locks/LockManager.java b/src/java/org/priha/core/locks/LockManager.java index a66412a..715e0a1 100644 --- a/src/java/org/priha/core/locks/LockManager.java +++ b/src/java/org/priha/core/locks/LockManager.java @@ -1,190 +1,195 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.locks; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Logger; import javax.jcr.Workspace; import org.priha.core.SessionImpl; import org.priha.core.WorkspaceImpl; import org.priha.path.InvalidPathException; import org.priha.path.Path; /** * A LockManager exists per static workspace. This means that it * manages *all* the locks for a given workspace, regardless of the * Session which accesses it. */ // FIXME: This class should avoid synchronization as much as possible. public class LockManager { private static HashMap<String,LockManager> m_lockManagers = new HashMap<String,LockManager>(); private HashMap<Path,QLock> m_locks = new HashMap<Path,QLock>(); //private String m_workspace; private Logger log = Logger.getLogger( LockManager.class.getName() ); private SessionImpl m_session; private LockManager(WorkspaceImpl ws) { m_session = ws.getSession(); } public synchronized void addLock( QLock lock ) { m_locks.put( lock.getPath(), lock ); } /** * Checks if the object at this path holds a lock. * * @param path * @return */ public synchronized QLock getLock( Path path ) { QLock lock = m_locks.get(path); return lock; } /** * Checks if the object at this path or any object above it * holds a lock. * * @param path * @return */ public synchronized QLock findLock( Path path ) { boolean deepRequired = false; while( !path.isRoot() ) { QLock li = m_locks.get( path ); if( li != null ) { if( deepRequired && li.isDeep() ) return li; // new QLock(li,m_session); else if( !deepRequired ) return li; // new QLock(li,m_session); } try { path = path.getParentPath(); deepRequired = true; } catch (InvalidPathException e) { log.warning("Internal error: "+e.getMessage()); } } return null; } /** * This method must be used to access a LockManager. * * @param ws * @return */ public static synchronized LockManager getInstance(WorkspaceImpl ws) { LockManager lm = m_lockManagers.get(ws.getName()); if( lm == null ) { lm = new LockManager( ws ); m_lockManagers.put( ws.getName(), lm ); } return lm; } + public void logout() + { + m_session = null; + } + public synchronized void expireSessionLocks( SessionImpl session ) { for( Iterator<Map.Entry<Path,QLock>> i = m_locks.entrySet().iterator(); i.hasNext(); ) { Map.Entry<Path,QLock> e = i.next(); QLock li = e.getValue(); if( li.expire(session) ) { // i.remove(); } } } /** * Updates a lock with a new path. * * @param lock Lock to change. * @param destPath New path. */ public synchronized void moveLock(QLock lock, Path destPath) { System.out.println("Moving lock from "+lock.getPath()+" to "+destPath); removeLock(lock); lock.move(destPath); addLock(lock); } /** * Removes the lock, if it exists. * * @param lock Lock to remove. */ public synchronized void removeLock(QLock lock) { m_locks.remove(lock.getPath()); } /** * Checks if any of the children of this Node hold a lock * to which the session does not hold a key to. * * @param internalPath * @return */ public synchronized boolean hasChildLock(Path internalPath) { for( Path p : m_locks.keySet() ) { //TODO Slightly unoptimal if( internalPath.isParentOf(p) ) { /* QLock li = m_locks.get(p); if( li.getLockToken() == null && li.isSessionScoped() ) return true; */ return true; } } return false; } } diff --git a/src/java/org/priha/path/PathManager.java b/src/java/org/priha/path/PathManager.java index f4cc160..a3a61ab 100644 --- a/src/java/org/priha/path/PathManager.java +++ b/src/java/org/priha/path/PathManager.java @@ -1,135 +1,141 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.path; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.WeakHashMap; import javax.jcr.PathNotFoundException; /** * PathManager stores all the Paths within a Session. */ public class PathManager { private WeakHashMap<PathRef,Path> m_pathMap = new WeakHashMap<PathRef,Path>(128); private HashMap<Path,WeakPathRef> m_reversePathMap = new HashMap<Path,WeakPathRef>(128); private ReferenceQueue<PathRef> m_queue = new ReferenceQueue<PathRef>(); public PathManager() { } public synchronized Path getPath(PathRef p) throws PathNotFoundException { emptyStaleEntries(); Path path = m_pathMap.get( p ); if( path == null ) { throw new PathNotFoundException("Path not found for reference "+p); } return path; } public synchronized PathRef getPathRef( Path path ) { emptyStaleEntries(); PathRef ref; WeakReference<PathRef> w = m_reversePathMap.get( path ); if( w != null ) { ref = w.get(); if( ref != null ) return ref; } ref = makeReference(path); m_reversePathMap.put( path, new WeakPathRef(ref,path,m_queue) ); m_pathMap.put( ref, path ); return ref; } public synchronized void move( Path oldPath, Path newPath ) { PathRef pr = getPathRef( oldPath ); if( pr != null ) { m_pathMap.put( pr, newPath ); m_reversePathMap.put( newPath, new WeakPathRef(pr,newPath,m_queue) ); m_reversePathMap.remove( oldPath ); } else { throw new RuntimeException("Oldpath does not exist!?! "+oldPath); } } private void emptyStaleEntries() { /* System.out.println("-------------"); System.out.println("pathMap.size() "+m_pathMap.size()); System.out.println("reversePathMap.size() "+m_reversePathMap.size()); */ WeakPathRef r; while( (r = (WeakPathRef)m_queue.poll()) != null ) { Path p = r.getPath(); m_reversePathMap.remove( p ); // System.out.println(" Expunged "+p); } /* System.out.println("pathMap.size() "+m_pathMap.size()); System.out.println("reversePathMap.size() "+m_reversePathMap.size()); */ } // FIXME: I don't quite know what happens when this overflows... private static int c_counter = Integer.MIN_VALUE; private PathRef makeReference(Path path) { return new PathRef(c_counter++); } private static class WeakPathRef extends WeakReference<PathRef> { private Path m_path; public WeakPathRef( PathRef referent,Path path, ReferenceQueue<PathRef> queue ) { super( referent, queue ); m_path = path; } public final Path getPath() { return m_path; } } + + public void close() + { + m_pathMap.clear(); + m_reversePathMap.clear(); + } } diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index 53ba823..0255724 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -279,1025 +279,1025 @@ public class FileProvider implements RepositoryProvider, PerformanceReporter return list; } private boolean deleteContents( File dir ) { // System.out.println("Deleting "+dir.getAbsolutePath()); for( File f : dir.listFiles() ) { if( f.isDirectory() ) { deleteContents( f ); } if( !f.delete() ) return false; } return true; } public void start(RepositoryImpl rep, Properties props) throws ConfigurationException { m_hitCount[Count.Start.ordinal()]++; try { m_systemPath = PathFactory.getPath( RepositoryImpl.getGlobalNamespaceRegistry(), "/jcr:system" ); } catch( RepositoryException e ) { throw new ConfigurationException("Unable to create a /jcr:system instance: "+e.getMessage()); } String wsList = props.getProperty("workspaces", "default"); m_root = props.getProperty("directory"); // // Make sure that root exists. // File root = new File(m_root); root.mkdirs(); // // Make sure this instance is the only one using that root. // File lockFile = new File(m_root, LOCKFILE); if( lockFile.exists() ) { String msg = "Cannot use the Priha FileProvider repository while another instance of Priha is using it. "+ "If you are sure there are no other instances using this same repository, please "+ "remove the '"+lockFile.getAbsolutePath()+"' file and restart."; log.severe( msg ); throw new ConfigurationException(msg); } // // Create the lock file; and make sure it gets cleaned up properly in // most cases. // try { lockFile.createNewFile(); lockFile.deleteOnExit(); } catch( IOException e ) { throw new ConfigurationException("Cannot start Priha ",e); } // // Initializing the workspaces. // log.fine("Initializing FileProvider with root "+m_root); String[] workspaces = wsList.split("\\s"); for( String wsname : workspaces ) { File wsroot = new File(getWorkspaceDir(wsname)); if( !wsroot.exists() ) { wsroot.mkdirs(); log.finer("Created workspace directory "+wsroot); } // // Reset the workspaces. // m_references.put( wsname, new UUIDObjectStore<Path[]>(mangleName(wsname)+"-references.ser") ); m_uuids.put( wsname, new UUIDObjectStore<Path>(mangleName(wsname)+"-uuid.ser") ); } } public void stop(RepositoryImpl rep) { m_hitCount[Count.Stop.ordinal()]++; log.fine("Shutting down FileProvider..."); for( UUIDObjectStore<Path[]> s : m_references.values() ) { s.shutdown(); } for( UUIDObjectStore<Path> s : m_uuids.values() ) { s.shutdown(); } m_references.clear(); m_uuids.clear(); // // Clean up the lockfile, in case we're e.g. switching repos mid-flight. // File lockFile = new File(m_root, LOCKFILE); lockFile.delete(); log.finer("Manglename cache hits = "+m_cacheHits+", misses = "+m_cacheMisses); } public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Copy.ordinal()]++; throw new UnsupportedRepositoryOperationException("copy()"); } public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws NamespaceException, RepositoryException { m_hitCount[Count.ListNodes.ordinal()]++; ArrayList<Path> list = new ArrayList<Path>(); File startPath = getNodeDir( ws, parentpath ); if( !startPath.exists() ) throw new PathNotFoundException("No such path found: "+parentpath); //acquirePaths( parentpath, startPath, list, false ); List<String> orderArray = getOrder( ws, parentpath ); for( String s : orderArray ) { Path childPath = parentpath.resolve( Path.Component.valueOf( s ) ); list.add( childPath ); } // // The .order -file will probably not contain the system path for anyone else // except the workspace which was created first. // if( parentpath.isRoot() && !list.contains( m_systemPath )) { list.add( 0, m_systemPath ); } return list; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.ListProperties.ordinal()]++; File nodeDir = getNodeDir( ws, path ); List<QName> proplist = new ArrayList<QName>(); try { File[] files = nodeDir.listFiles( new PropertyTypeFilter() ); if( files != null ) { for( File propertyFile : files ) { Properties props; FileInputStream in = null; try { in = new FileInputStream(propertyFile); props = FastPropertyStore.load(in); String qname = props.getProperty(PROP_PATH); proplist.add( PathFactory.getPath( qname ).getLastComponent() ); } finally { if( in != null ) in.close(); } } } } catch( IOException e ) { throw new RepositoryException("Thingy said booboo", e); } return proplist; } public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Move.ordinal()]++; throw new UnsupportedRepositoryOperationException("move()"); } /** * A Node exists only if it has a primaryType.info in the directory. */ public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) { m_hitCount[Count.ItemExists.ordinal()]++; File nodeDir; try { File propFile; if( type == ItemType.NODE ) { nodeDir = getNodeDir( ws, path ); propFile = new File( nodeDir, mangleName("jcr:primaryType.info") ); } else if( type == ItemType.PROPERTY ) { nodeDir = getNodeDir( ws, path.getParentPath() ); propFile = new File( nodeDir, makeFilename( path.getLastComponent(), ".info" ) ); } else { throw new IllegalArgumentException("Type "+type.name()+" not supported"); } return propFile.exists(); } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_hitCount[Count.Open.ordinal()]++; List<String> wsnames = listWorkspaces(); if( wsnames.indexOf(workspaceName) == -1 ) throw new NoSuchWorkspaceException(workspaceName); log.finer("Workspace "+workspaceName+" has been opened."); } public void close(WorkspaceImpl ws) { log.finer( "Workspace "+ws.getName()+" closing..." ); m_hitCount[Count.Close.ordinal()]++; /* try { m_uuids.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } catch( NullPointerException e ) { log.warning( "A non-configured workspace '"+ws.getName()+"' detected. If you are using a multiprovider configuration, please check this workspace actually exists." ); return; } try { m_references.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } */ } private void writeValue( File f, ValueImpl v ) throws IOException, IllegalStateException, RepositoryException { OutputStream out = null; InputStream in = null; try { if( v instanceof QValue.QValueInner ) { byte[] ba = ((QValue.QValueInner)v).getQValue().getString().getBytes("UTF-8"); in = new ByteArrayInputStream(ba); } else { in = v.getStream(); } out = new FileOutputStream( f ); FileUtil.copyContents( in, out ); } finally { // // ...and close all the streams. // if( out != null ) { try { out.close(); } finally { if( in != null ) in.close(); } } } } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc) throws RepositoryException { m_hitCount[Count.PutPropertyValue.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path.getParentPath() ); saveUuidShortcut(ws,path,vc); QName qname = path.getLastComponent(); File inf = new File( nodeDir, makeFilename( qname, ".info" ) ); Properties props = new Properties(); props.setProperty( PROP_PATH, path.toString() ); props.setProperty( PROP_TYPE, PropertyType.nameFromValue( vc.getType() ) ); props.setProperty( PROP_MULTIPLE, vc.isMultiple() ? "true" : "false" ); OutputStream out = null; try { if( vc.isMultiple() ) { props.setProperty( PROP_NUM_PROPERTIES, Integer.toString(vc.getValues().length) ); Value[] values = vc.getValues(); // // Let's clear previous references, if this is an attempt to save // a null value. // if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl[] oldval = getPropertyValue( ws, path ).getValues(); for( ValueImpl vi : oldval ) { String uuid = vi.getString(); cleanRefMapping( ws, path, uuid ); } } catch( PathNotFoundException e ){} // This is okay } for( int i = 0; i < values.length; i++ ) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); saveRefShortcut( ws, path, (ValueImpl)values[i] ); writeValue( df, (ValueImpl)values[i] ); } // Remove the rest of old values int i = values.length; while(true) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); if( df.exists() ) df.delete(); else break; } } else { if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl oldval = getPropertyValue( ws, path ).getValue(); cleanRefMapping( ws, path, oldval.getString() ); } catch(PathNotFoundException e) {} // OK saveRefShortcut( ws, path, vc.getValue() ); } File df = new File( nodeDir, makeFilename( qname, ".data" ) ); writeValue( df, vc.getValue() ); } out = new FileOutputStream(inf); FastPropertyStore.store( out, props ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * Saves a shortcut to an UUID. The contents of the file are the path of the Node. * */ private void saveUuidShortcut(WorkspaceImpl ws, Path path, ValueContainer vc) throws RepositoryException { if( path.getLastComponent().equals(Q_JCR_UUID) ) { UUIDObjectStore<Path> uuids = m_uuids.get( ws.getName() ); uuids.setObject( vc.getValue().valueAsString(), path.getParentPath() ); } } private ValueImpl prepareValue( WorkspaceImpl ws, File propFile, String propType ) throws IOException, RepositoryException { ValueFactoryImpl vf = ws.getSession().getValueFactory(); ValueImpl value; if( propType.equals(PropertyType.TYPENAME_STRING) ) { value = vf.createValue( readContentsAsString(propFile) ); } else if( propType.equals(PropertyType.TYPENAME_BOOLEAN) ) { value = vf.createValue( "true".equals(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DOUBLE) ) { value = vf.createValue( Double.parseDouble(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_LONG) ) { value = vf.createValue( Long.parseLong(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DATE) ) { value = vf.createValue( readContentsAsString( propFile ), PropertyType.DATE ); } else if( propType.equals(PropertyType.TYPENAME_NAME) ) { String qnameStr = readContentsAsString(propFile); QName qn = QName.valueOf( qnameStr ); value = vf.createValue( qn, PropertyType.NAME ); } else if( propType.equals(PropertyType.TYPENAME_PATH )) { String val = readContentsAsString(propFile); value = vf.createValue( val, PropertyType.PATH ); } else if( propType.equals(PropertyType.TYPENAME_REFERENCE ) ) { value = vf.createValue( readContentsAsString(propFile), PropertyType.REFERENCE ); } else if( propType.equals(PropertyType.TYPENAME_BINARY) ) { value = vf.createValue( new FileBinarySource(propFile) ); } else - throw new RepositoryException("Cannot deserialize property type "+propType); + throw new RepositoryException("Cannot deserialize property type "+propType+" for file "+propFile.getAbsolutePath()); return value; } /** * Returns the contents of the .info -file. * * @param nodeDir * @return * @throws PathNotFoundException * @throws IOException */ private Properties getPropertyInfo( File nodeDir, QName name ) throws PathNotFoundException, IOException { File inf = new File( nodeDir, makeFilename( name, ".info" ) ); if( !inf.exists() ) { throw new PathNotFoundException("The property metadata file was not found: "+inf.getAbsolutePath()); } Properties props; FileInputStream in = null; try { in = new FileInputStream( inf ); props = FastPropertyStore.load(in); } finally { if( in != null ) in.close(); } return props; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.GetPropertyValue.ordinal()]++; File nodeDir = getNodeDir( ws, path.getParentPath() ); try { Properties props = getPropertyInfo( nodeDir, path.getLastComponent() ); String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); ValueImpl[] result = new ValueImpl[items]; for( int i = 0; i < items; i++ ) { File df = new File( nodeDir, makeFilename(path.getLastComponent(),"."+i+".data") ); ValueImpl v = prepareValue( ws, df, propType ); result[i] = v; } return new ValueContainer(result, PropertyType.valueFromName( propType ) ); } File df = new File( nodeDir, makeFilename( path.getLastComponent(), ".data" ) ); ValueImpl v = prepareValue(ws, df, propType); return new ValueContainer(v); } catch( IOException e ) { throw new RepositoryException("Unable to read property file",e); } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: Protect against windows special names (CON) etc. protected String mangleName( String name ) { // diff --git a/tests/tck/org/apache/jackrabbit/test/api/AbstractWorkspaceVersionableTest.java b/tests/tck/org/apache/jackrabbit/test/api/AbstractWorkspaceVersionableTest.java index 46701d3..3326dbd 100644 --- a/tests/tck/org/apache/jackrabbit/test/api/AbstractWorkspaceVersionableTest.java +++ b/tests/tck/org/apache/jackrabbit/test/api/AbstractWorkspaceVersionableTest.java @@ -1,64 +1,65 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.test.api; import javax.jcr.Node; +import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import org.apache.jackrabbit.test.NotExecutableException; /** * <code>AbstractWorkspaceReferenceableTest</code> is the abstract base class * for all copying/moving/cloning related test classes with versionable nodes in * workspace. */ abstract class AbstractWorkspaceVersionableTest extends AbstractWorkspaceCopyBetweenTest { protected void setUp() throws Exception { super.setUp(); // we assume versioning is supported by repository NodeTypeManager ntMgr = superuser.getWorkspace().getNodeTypeManager(); // assert that this repository supports versioning try { NodeType versionableNt = ntMgr.getNodeType(mixVersionable); - if (versionableNt == null) { + if (versionableNt == null||superuser.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false")) { throw new NotExecutableException("Repository does not support versioning: mixin nodetype '" + mixVersionable + "' is missing."); } } catch (NoSuchNodeTypeException e) { throw new NotExecutableException("Repository does not support versioning: mixin nodetype '" + mixVersionable + "' is missing."); } } /** * add the mix:versionable mixin type to a node. */ protected Node addMixinVersionableToNode(Node parent, Node node) throws RepositoryException { NodeType nodetype = node.getPrimaryNodeType(); if (!nodetype.isNodeType(mixVersionable)) { node.addMixin(mixVersionable); } parent.save(); return node; } } \ No newline at end of file
jalkanen/Priha
34cb09a34a61c0c8babaf26428b83e758d1fffb0
Oopsydaisy, forgot to init a field, therefore getSize() always returned zero.
diff --git a/src/java/org/priha/providers/ValueContainer.java b/src/java/org/priha/providers/ValueContainer.java index a83b6aa..ed59351 100644 --- a/src/java/org/priha/providers/ValueContainer.java +++ b/src/java/org/priha/providers/ValueContainer.java @@ -1,204 +1,204 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import javax.jcr.*; import org.priha.core.SessionImpl; import org.priha.core.values.QValue; import org.priha.core.values.ValueImpl; /** * Stores a Value with its type. This is what a PropertyImpl stores internally, * and this is what gets passed down to a RepositoryProvider. Most noticeably * the difference is that the Value that a ValueContainer contains is NOT cloned * when you do a getValue(). Therefore, if you getValue() and read its contents * with getStream(), you cannot read it again until you clone the ValueContainer. * Ditto, if you read it with getString() or one of the other scalar values, you * cannot use getStream() anymore. * <p> * To work around this problem, use the sessionInstance() and deepClone() methods, * which will return you a new ValueContainer - or use ValueFactory.cloneValues(). */ public class ValueContainer { public static final ValueContainer UNDEFINED_CONTAINER = new ValueContainer(); private Object m_value; private int m_type = PropertyType.UNDEFINED; private boolean m_multiple; /** * Empty private constructor; use UNDEFINED_CONTAINER if you need something. */ private ValueContainer() {} public ValueContainer(ValueImpl v) { m_value = v; m_multiple = false; m_type = v.getType(); } public ValueContainer(ValueImpl[] v, int type) { m_value = v; m_multiple = true; m_type = type; } public ValueContainer(Value[] values, int propertyType) { m_multiple = true; m_type = propertyType; m_value = new ValueImpl[values.length]; System.arraycopy(values, 0, m_value, 0, values.length); } public int getType() { return m_type; } public ValueImpl getValue() throws ValueFormatException { if( m_multiple == true ) throw new ValueFormatException("Attempt to get a multivalue"); return (ValueImpl)m_value; } public ValueImpl[] getValues() throws ValueFormatException { if( m_multiple == false ) throw new ValueFormatException("Attempt to get a single value"); return (ValueImpl[])m_value; } public boolean isMultiple() { return m_multiple; } public String toString() { try { return isMultiple() ? (PropertyType.nameFromValue( m_type )+"["+getValues().length+"]") : m_value.toString(); } catch( ValueFormatException e ) {} return "Error?"; } /** * Returns a new ValueContainer which has mappings to the given Session. * * @param session * @return * @throws ValueFormatException */ public ValueContainer sessionInstance( SessionImpl session ) throws ValueFormatException { if( m_multiple ) { ValueImpl[] newValues = new ValueImpl[getValues().length]; for( int i = 0; i < getValues().length; i++ ) { ValueImpl vi = getValues()[i]; if( vi instanceof QValue.QValueInner ) { vi = ((QValue.QValueInner)vi).getQValue().getValue( session ); } newValues[i] = vi; } return new ValueContainer( newValues, m_type ); } if( getValue() instanceof QValue.QValueInner ) { return new ValueContainer( ((QValue.QValueInner)getValue()).getQValue().getValue( session ) ); } return this; } /** * Cloning of a ValueContainer is a deep operation, i.e. you will get all new Value instances. * This is because the Values might be consumed already, esp. if they are streams. * * @throws RepositoryException * @throws UnsupportedRepositoryOperationException * @throws IllegalStateException * @throws ValueFormatException */ public ValueContainer deepClone( SessionImpl session ) throws ValueFormatException, IllegalStateException, UnsupportedRepositoryOperationException, RepositoryException { if( m_multiple ) { Value[] newValues = session.getValueFactory().cloneValues( getValues() ); return new ValueContainer(newValues, getType()); } else { ValueImpl newValue = session.getValueFactory().cloneValue( getValue() ); return new ValueContainer( newValue ); } } public boolean isEmpty() { return m_value == null; } - private long m_cachedSize; + private long m_cachedSize = -1; /** * Calculates the rough size of this object in bytes. * * @return */ public long getSize() { if( m_cachedSize != -1 ) return m_cachedSize; if( m_value != null ) { if( m_multiple ) { long size = 0; for( ValueImpl v : (ValueImpl[]) m_value ) { long sz = v.getSize(); if( sz < 0 ) { size = -1; break; } size += sz; } m_cachedSize = size; } else { m_cachedSize = ((ValueImpl)m_value).getSize(); } } return m_cachedSize; } }
jalkanen/Priha
d7f0099c2b10f170e8f2c0c92c912ee70b3f1ac8
Added 0.7.4 results.
diff --git a/doc/Performance.txt b/doc/Performance.txt index 5217c42..15a93b8 100644 --- a/doc/Performance.txt +++ b/doc/Performance.txt @@ -1,151 +1,177 @@ PRIHA PERFORMANCE COOKBOOK ========================== Priha is not the fastest JCR implementation around, but it can hold its own. It's very good at small repository sizes, but some operations scale better than others. To keep your implementation fast, there are some basic rules which are good to follow. 1) Steer clear of same name siblings. Renaming, moving, removing them will cause plenty of repository accesses, since Priha uses Paths as the immutable object and unique item identifier. Calling Node.orderBefore() whenever you have same name siblings will probably be very slow. 2) Very large changesets in Session. Some of the algorithms in SessionProvider are O(N) or worse, so they will become slower as your unsaved changes grow. Especially if you use references heavily. 3) Queries. Unfortunately the default SimpleQueryProvider is very slow. Looking for ways to make it faster... 4) References in general are not that good an idea, since they mean that Priha needs to be checking for referential integrity all day. It's strongly recommended that you read and internalize David's Model, a guide to JCR content model design at http://wiki.apache.org/jackrabbit/DavidsModel. ---------------------------------------------------------------------------------------------- The rest of the file contains some sample test runs. CPU: 8x E5310 @ 1.60GHz Ubuntu 8.04 Java HotSpot(TM) Server VM (build 14.0-b16, mixed mode) LARGE REPOSITORY ================ Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 27,554.529 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.1.32 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.86 42226 28 1726 34339 43752 9 1187 21681 29960 4135 4075699 1052318 552493 FileProvider, no cache 2410 5433 85 380 12897 4777 33 273 1584 3291 476 5762550 1160431 1062556 FileProvider, with Ehcache 3674 4202 79 508 11598 2491 32 292 1219 1378 463 6610291 1171581 993581 JdbcProvider, no cache 40 6940 57 155 18311 11610 71 143 7952 535 223 5865707 1169224 904838 JdbcProvider, with Ehcache 274 4682 52 155 30321 3355 62 152 2399 350 219 6608281 1182648 761772 Jackrabbit 0.26 12836 200 268 0.43 23954 706 356 6038 38407 472 510608 1833296 555645 ------------- ---------------- --------------- Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 24,264.237 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.1.35 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.86 34041 21 1351 32458 36329 7 1022 15320 23344 3554 4147210 551582 813431 FileProvider, no cache 62 5300 47 366 5161 4633 22 250 1436 3302 368 4945679 1054289 736046 FileProvider, with Ehcache 3269 3757 39 463 11544 2538 21 304 1794 1388 518 4111099 575475 860618 JdbcProvider, no cache 36 5925 35 139 17728 10815 49 132 5352 518 204 5845684 1055036 956811 JdbcProvider, with Ehcache 274 4215 33 132 29858 3215 45 135 2646 355 211 4990868 1052285 937860 Jackrabbit 0.08 12458 205 274 0.54 24620 739 361 5990 47369 477 472575 1820003 527168 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 4,879.679 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.1.40 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.86 46771 24 1262 31864 50780 8 1041 16476 36392 3348 6116963 946805 828446 FileProvider, no cache 2002 4831 53 391 3478 4799 24 299 1605 3317 522 3087284 1007580 932581 FileProvider, with Ehcache 3129 4480 47 439 3266 5697 21 265 2425 4212 737 5227694 1019065 621266 JdbcProvider, no cache 35 7722 34 143 16346 10801 49 140 5883 6961 207 5145101 1011047 936684 JdbcProvider, with Ehcache 170 6834 35 137 4071 9462 49 142 5815 5758 211 5151465 998437 633336 Jackrabbit 0.25 9219 197 279 2865 25218 667 368 5100 38029 508 363755 2108694 776265 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 4,955.61 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.4.0 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.83 27763 18290029 1241 32585 35017 4761637 1030 206761088 33237 3965 3103776 737497 100399 FileProvider, no cache 93 5434 42 211 12487 4484 22 169 1463 3376 474 3732332 803352 600288 FileProvider, with Ehcache 14 4804 43 221 3302 5660 23 185 2147 4089 437 3389755 509009 745610 JdbcProvider, no cache 1 4453 33 111 14830 5447 11 112 3142 3870 183 3290572 786117 747306 JdbcProvider, with Ehcache 571 4421 35 107 4183 5619 11 109 3509 3921 195 3313538 786630 546656 Jackrabbit 0.26 3780 186 269 3584 22193 737 355 4958 40819 501 607558 2275791 849284 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 2,356.826 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.7.0-svn Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save MemoryProvider, no cache 2 31866 48289350 1516 27958 30019 36065278 1273 FileProvider, no cache 82 4974 230 199 10017 4552 193 208 FileProvider, with Ehcache 9 5422 274 220 3349 5534 200 217 JdbcProvider, no cache 0.20 4739 39 111 15101 5246 36 110 JdbcProvider, with Ehcache 434 4441 40 117 4262 5400 37 117 Jackrabbit 0.25 7078 194 274 3673 19114 719 346 SeqRead UUID Update exists getItem getProperty propUUID MemoryProvider, no cache 209248797 29384 6227 818628 2848365 761666 389615 FileProvider, no cache 1764 3154 579 32819 2653480 764525 736396 FileProvider, with Ehcache 2426 4046 610 31990 2671378 754926 742737 JdbcProvider, no cache 3104 4030 1272 17466 2597055 755972 731350 JdbcProvider, with Ehcache 3396 4051 1548 16157 2660070 765454 737974 Jackrabbit 4495 39499 487 42460 412058 2206883 773435 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 2,652.136 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.7.3-svn Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save MemoryProvider, no cache 2 70637 24132381 1515 14979 62579 14564839 1334 FileProvider, no cache 7 5371 244 231 9527 5267 181 193 FileProvider, with Ehcache 11 5852 241 227 2970 5836 191 204 JdbcProvider, no cache 0.18 4283 33 110 11634 5935 30 103 JdbcProvider, with Ehcache 335 3973 36 110 3861 6594 32 112 Jackrabbit 0.21 5341 174 191 3013 15167 639 239 SeqRead UUID Update exists getItem getProperty propUUID MemoryProvider, no cache 145966223 48554 11412 693085 3066164 712545 604631 FileProvider, no cache 2327 3583 1056 33754 3109530 653987 702360 FileProvider, with Ehcache 3087 4110 1374 31125 3064541 714271 703580 JdbcProvider, no cache 463 3838 307 14888 2952266 736530 567148 JdbcProvider, with Ehcache 468 4305 346 14300 2764363 762076 568895 Jackrabbit 4386 33998 332 34246 579779 1930375 530741 + + +Testsuite: org.priha.core.PerformanceTest +Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 2,438.397 sec +------------- Standard Output --------------- +Test results. The number is operations/seconds - larger means faster. +Blob size 10 kB +Repository size 10000 nodes +Priha version 0.7.4-svn +Jackrabbit version 1.6.0 + FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save +MemoryProvider, no cache 2 60495 20336984 1658 12823 129625 11566002 1260 +FileProvider, no cache 30 27795 230 214 7965 37024 154 182 +FileProvider, with Ehcache 10 22919 237 219 2950 34314 173 188 +JdbcProvider, no cache 0.04 21848 33 120 11051 37722 30 119 +JdbcProvider, with Ehcache 342 18046 36 118 3794 35667 35 123 +Jackrabbit 0.20 6710 167 185 2933 20612 572 253 + + + SeqRead UUID Update exists getItem getProperty propUUID +MemoryProvider, no cache 97700139 101065 13434 455003 2888165 704576 405119 +FileProvider, no cache 2279 19398 1042 31940 2644728 724237 650177 +FileProvider, with Ehcache 1630 20096 1345 28945 2767973 718113 597347 +JdbcProvider, no cache 469 20058 405 12854 2756507 750959 639016 +JdbcProvider, with Ehcache 490 20384 420 15052 2618564 689566 613951 +Jackrabbit 4468 31918 315 41138 538651 488527 904535
jalkanen/Priha
5514853a9b0f02091f185fef134b82727afbb3e6
Adding Session Item Cache configuration; fixed itemExists() to check for local items as well. Added System properties override.
diff --git a/ChangeLog b/ChangeLog index 3d22154..08844ad 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,525 @@ +2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.7.4 + + * The "I think I optimized something but I've got a flu" -release. + + * Session Item cache is now configurable (and slightly bigger by default) + + * SessionProvider.itemExists() is now slightly smarter when checking + for cached items. + + * Allowed overriding priha.properties from system properties. + 2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.3 * Optimization of ProviderManager.loadNode() and Item.enterState(). Especially the latter helps reading quite a lot. * EhCacheProvider.exists() was confusing Nodes with Properties sometimes. * ObservationManager now correctly sends events for Node reordering. 2010-01-04 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.2 * Implemented Observation. It does not *quite* work yet, but it's only nine errors until TCK pass. 2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> * Fixed XML import tests for versioning by properly checking for checked-in Nodes in XMLImport. You may test Versioning, but the TCK tests are disabled. You can turn them on by editing Release.DESCRIPTORS and setting Repository.OPTION_VERSIONING_SUPPORTED to STR_TRUE. * 0.7.1 * FileProvider speedup - added internal cache for mangleName(). 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation diff --git a/doc/Performance.txt b/doc/Performance.txt index 9755892..5217c42 100644 --- a/doc/Performance.txt +++ b/doc/Performance.txt @@ -1,125 +1,151 @@ PRIHA PERFORMANCE COOKBOOK ========================== Priha is not the fastest JCR implementation around, but it can hold its own. It's very good at small repository sizes, but some operations scale better than others. To keep your implementation fast, there are some basic rules which are good to follow. 1) Steer clear of same name siblings. Renaming, moving, removing them will cause plenty of repository accesses, since Priha uses Paths as the immutable object and unique item identifier. Calling Node.orderBefore() whenever you have same name siblings will probably be very slow. 2) Very large changesets in Session. Some of the algorithms in SessionProvider are O(N) or worse, so they will become slower as your unsaved changes grow. Especially if you use references heavily. 3) Queries. Unfortunately the default SimpleQueryProvider is very slow. Looking for ways to make it faster... 4) References in general are not that good an idea, since they mean that Priha needs to be checking for referential integrity all day. It's strongly recommended that you read and internalize David's Model, a guide to JCR content model design at http://wiki.apache.org/jackrabbit/DavidsModel. ---------------------------------------------------------------------------------------------- The rest of the file contains some sample test runs. CPU: 8x E5310 @ 1.60GHz Ubuntu 8.04 Java HotSpot(TM) Server VM (build 14.0-b16, mixed mode) LARGE REPOSITORY ================ Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 27,554.529 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.1.32 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.86 42226 28 1726 34339 43752 9 1187 21681 29960 4135 4075699 1052318 552493 FileProvider, no cache 2410 5433 85 380 12897 4777 33 273 1584 3291 476 5762550 1160431 1062556 FileProvider, with Ehcache 3674 4202 79 508 11598 2491 32 292 1219 1378 463 6610291 1171581 993581 JdbcProvider, no cache 40 6940 57 155 18311 11610 71 143 7952 535 223 5865707 1169224 904838 JdbcProvider, with Ehcache 274 4682 52 155 30321 3355 62 152 2399 350 219 6608281 1182648 761772 Jackrabbit 0.26 12836 200 268 0.43 23954 706 356 6038 38407 472 510608 1833296 555645 ------------- ---------------- --------------- Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 24,264.237 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.1.35 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.86 34041 21 1351 32458 36329 7 1022 15320 23344 3554 4147210 551582 813431 FileProvider, no cache 62 5300 47 366 5161 4633 22 250 1436 3302 368 4945679 1054289 736046 FileProvider, with Ehcache 3269 3757 39 463 11544 2538 21 304 1794 1388 518 4111099 575475 860618 JdbcProvider, no cache 36 5925 35 139 17728 10815 49 132 5352 518 204 5845684 1055036 956811 JdbcProvider, with Ehcache 274 4215 33 132 29858 3215 45 135 2646 355 211 4990868 1052285 937860 Jackrabbit 0.08 12458 205 274 0.54 24620 739 361 5990 47369 477 472575 1820003 527168 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 4,879.679 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.1.40 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.86 46771 24 1262 31864 50780 8 1041 16476 36392 3348 6116963 946805 828446 FileProvider, no cache 2002 4831 53 391 3478 4799 24 299 1605 3317 522 3087284 1007580 932581 FileProvider, with Ehcache 3129 4480 47 439 3266 5697 21 265 2425 4212 737 5227694 1019065 621266 JdbcProvider, no cache 35 7722 34 143 16346 10801 49 140 5883 6961 207 5145101 1011047 936684 JdbcProvider, with Ehcache 170 6834 35 137 4071 9462 49 142 5815 5758 211 5151465 998437 633336 Jackrabbit 0.25 9219 197 279 2865 25218 667 368 5100 38029 508 363755 2108694 776265 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 4,955.61 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.4.0 Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save SeqRead UUID Update getItem getProperty propUUID MemoryProvider, no cache 0.83 27763 18290029 1241 32585 35017 4761637 1030 206761088 33237 3965 3103776 737497 100399 FileProvider, no cache 93 5434 42 211 12487 4484 22 169 1463 3376 474 3732332 803352 600288 FileProvider, with Ehcache 14 4804 43 221 3302 5660 23 185 2147 4089 437 3389755 509009 745610 JdbcProvider, no cache 1 4453 33 111 14830 5447 11 112 3142 3870 183 3290572 786117 747306 JdbcProvider, with Ehcache 571 4421 35 107 4183 5619 11 109 3509 3921 195 3313538 786630 546656 Jackrabbit 0.26 3780 186 269 3584 22193 737 355 4958 40819 501 607558 2275791 849284 Testsuite: org.priha.core.PerformanceTest Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 2,356.826 sec ------------- Standard Output --------------- Test results. The number is operations/seconds - larger means faster. Blob size 10 kB Repository size 10000 nodes Priha version 0.7.0-svn Jackrabbit version 1.6.0 FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save MemoryProvider, no cache 2 31866 48289350 1516 27958 30019 36065278 1273 FileProvider, no cache 82 4974 230 199 10017 4552 193 208 FileProvider, with Ehcache 9 5422 274 220 3349 5534 200 217 JdbcProvider, no cache 0.20 4739 39 111 15101 5246 36 110 JdbcProvider, with Ehcache 434 4441 40 117 4262 5400 37 117 Jackrabbit 0.25 7078 194 274 3673 19114 719 346 SeqRead UUID Update exists getItem getProperty propUUID MemoryProvider, no cache 209248797 29384 6227 818628 2848365 761666 389615 FileProvider, no cache 1764 3154 579 32819 2653480 764525 736396 FileProvider, with Ehcache 2426 4046 610 31990 2671378 754926 742737 JdbcProvider, no cache 3104 4030 1272 17466 2597055 755972 731350 JdbcProvider, with Ehcache 3396 4051 1548 16157 2660070 765454 737974 Jackrabbit 4495 39499 487 42460 412058 2206883 773435 + + +Testsuite: org.priha.core.PerformanceTest +Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 2,652.136 sec +------------- Standard Output --------------- +Test results. The number is operations/seconds - larger means faster. +Blob size 10 kB +Repository size 10000 nodes +Priha version 0.7.3-svn +Jackrabbit version 1.6.0 + FirstSess LargeRead LargeRemove LargeSave NewSession RandRead Remove Save +MemoryProvider, no cache 2 70637 24132381 1515 14979 62579 14564839 1334 +FileProvider, no cache 7 5371 244 231 9527 5267 181 193 +FileProvider, with Ehcache 11 5852 241 227 2970 5836 191 204 +JdbcProvider, no cache 0.18 4283 33 110 11634 5935 30 103 +JdbcProvider, with Ehcache 335 3973 36 110 3861 6594 32 112 +Jackrabbit 0.21 5341 174 191 3013 15167 639 239 + + + SeqRead UUID Update exists getItem getProperty propUUID +MemoryProvider, no cache 145966223 48554 11412 693085 3066164 712545 604631 +FileProvider, no cache 2327 3583 1056 33754 3109530 653987 702360 +FileProvider, with Ehcache 3087 4110 1374 31125 3064541 714271 703580 +JdbcProvider, no cache 463 3838 307 14888 2952266 736530 567148 +JdbcProvider, with Ehcache 468 4305 346 14300 2764363 762076 568895 +Jackrabbit 4386 33998 332 34246 579779 1930375 530741 diff --git a/etc/priha_default.properties b/etc/priha_default.properties index d96e870..c132b49 100644 --- a/etc/priha_default.properties +++ b/etc/priha_default.properties @@ -1,14 +1,19 @@ # # The default property file. Usually you should have no need to # modify this, as it goes into the JAR file. But it might be useful # to read this to see what kind of things Priha defaults to. # # # Repository storage # priha.providers=defaultProvider priha.provider.defaultProvider.class=org.priha.providers.FileProvider priha.provider.defaultProvider.directory=/tmp/priha/fileprovider/ priha.provider.defaultProvider.workspaces=default +# +# Internal variables +# +priha.session.cacheSize = 10000 +priha.session.maxCachedItemSize = 2048 diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 9ec483a..d24dc6e 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ - public static final int MINORREVISION = 3; + public static final int MINORREVISION = 4; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_TRUE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/RepositoryImpl.java b/src/java/org/priha/core/RepositoryImpl.java index 8c66aca..ff05f3b 100644 --- a/src/java/org/priha/core/RepositoryImpl.java +++ b/src/java/org/priha/core/RepositoryImpl.java @@ -1,398 +1,405 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import org.priha.Release; import org.priha.core.namespace.NamespaceRegistryImpl; import org.priha.util.ConfigurationException; import org.priha.util.FileUtil; /** * Provides the main Repository class for Priha. You may use this * by simply instantiating it with a suitable Properties object. + * <p> + * Any property may be overridden also from the command line using + * a system property. */ public class RepositoryImpl implements Repository { public static final String DEFAULT_WORKSPACE = "default"; private static NamespaceRegistryImpl c_namespaceRegistry = new NamespaceRegistryImpl(); private RepositoryState m_state = RepositoryState.DEAD; /** * Defines which paths are attempted to locate the default property file. */ private static final String[] DEFAULT_PROPERTIES = { "/priha_default.properties", "/WEB-INF/priha_default.properties" }; private Properties m_properties; private Logger log = Logger.getLogger( getClass().getName() ); private SessionManager m_sessionManager; private ProviderManager m_providerManager; /** * Create a new Repository using the given properties. Any property which is not * set will be read from the default properties (priha_default.properties). * * @param prefs Properties to use. Must not be null. * @throws ConfigurationException If the properties are wrong. */ public RepositoryImpl( Properties prefs ) throws ConfigurationException { m_state = RepositoryState.STARTING; try { Properties defaultProperties = FileUtil.findProperties(DEFAULT_PROPERTIES); if( defaultProperties.isEmpty() ) throw new ConfigurationException("Default properties not found - broken distribution!?!"); m_properties = new Properties(defaultProperties); } catch (IOException e) { throw new ConfigurationException("Loading of default properties failed"); } if( prefs.isEmpty() ) log.warning("No \"priha.properties\" found, using just the default properties"); m_properties.putAll( prefs ); Runtime.getRuntime().addShutdownHook( new ShutdownThread() ); log.info( "G'day, Matilda! Priha "+Release.VERSTR+" has been initialized." ); log.fine( "Using configuration from "+prefs.toString() ); m_state = RepositoryState.LIVE; } public String getProperty(String key) { - return m_properties.getProperty(key); + String prop = System.getProperty(key, m_properties.getProperty(key)); + + return prop; } public String getProperty( String key, String defValue ) { - return m_properties.getProperty(key,defValue); + String prop = System.getProperty( key, m_properties.getProperty(key,defValue) ); + + return prop; } protected ProviderManager getProviderManager() throws ConfigurationException { if( m_providerManager == null ) { log.info( "Initializing providers..." ); long start = System.currentTimeMillis(); m_providerManager = new ProviderManager(this); long end = System.currentTimeMillis(); log.info( "Repository initialization took "+(end-start)+" ms." ); } return m_providerManager; } protected SessionManager getSessionManager() { if( m_sessionManager == null ) { log.info( "Initializing SessionManager..." ); m_sessionManager = new SessionManager(); } return m_sessionManager; } /** * Set transient properties for this repository. These are not saved anywhere, but they * might be something that you can use to control the Repository behaviour with. * @param key * @param property */ public void setProperty(String key, String property) { m_properties.setProperty(key,property); } @SuppressWarnings("unchecked") public Enumeration<String> getPropertyNames() { return (Enumeration<String>)m_properties.propertyNames(); } public String getDescriptor(String key) { for( int i = 0; i < Release.DESCRIPTORS.length; i += 2 ) { if( Release.DESCRIPTORS[i].equals(key) ) { return Release.DESCRIPTORS[i+1]; } } return null; } public String[] getDescriptorKeys() { String[] keys = new String[Release.DESCRIPTORS.length/2]; for( int i = 0; i < Release.DESCRIPTORS.length; i += 2 ) { keys[i/2] = Release.DESCRIPTORS[i]; } return keys; } private String getDefaultWorkspace() throws ConfigurationException { return getProviderManager().getDefaultWorkspace(); } public synchronized SessionImpl login(Credentials credentials, String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { if( m_state != RepositoryState.LIVE ) { throw new RepositoryException("Repository is not alive. It is "+m_state); } long start = System.currentTimeMillis(); if( workspaceName == null ) workspaceName = getDefaultWorkspace(); getProviderManager().open( credentials, workspaceName ); SessionImpl session = getSessionManager().openSession( credentials, workspaceName ); session.refresh(false); long end = System.currentTimeMillis(); if( log.isLoggable(Level.FINER) ) log.finer("Login completed and new Session created; took "+(end-start)+" ms."); return session; } public SessionImpl login(Credentials credentials) throws LoginException, RepositoryException { return login( credentials, null ); } public SessionImpl login(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { return login( null, workspaceName ); } public SessionImpl login() throws LoginException, RepositoryException { return login( null, null ); } /** * Shuts down the entire repository, stops all providers and releases * resources. After this call you can restart the repository by either * calling login(), or creating a new RepositoryImpl instance. */ public void shutdown() { m_state = RepositoryState.SHUTTING; // // Close all open sessions. // visit( new SessionVisitor() { public void visit(SessionImpl session) { session.logout(); } }); // // Stop the ProviderManager and release providers. // if( m_providerManager != null ) { m_providerManager.stop(); } m_providerManager = null; m_sessionManager = null; m_state = RepositoryState.DEAD; } /** * Returns a Session which has write permissions to the repository. Normally, the * user has no reason to use this method - it is used internally to sometimes modify * the repo. * <p> * This method is guaranteed to always return a Session which has all permissions * into the repository - assuming the underlying repository implementation does not * have any limitations (which it normally should not have). * * @param workspaceName The workspace to which the login is done. * @return A Priha SessionImpl object. * @throws LoginException * @throws NoSuchWorkspaceException * @throws RepositoryException */ public SessionImpl superUserLogin(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { SessionImpl s = login( null, workspaceName ); s.setSuper(true); return s; } public static NamespaceRegistryImpl getGlobalNamespaceRegistry() { return c_namespaceRegistry; } /** * Visits all current Sessions * * @param v */ protected void visit( SessionVisitor v ) { synchronized( getSessionManager().m_sessions ) { for( Iterator<WeakReference<SessionImpl>> i = getSessionManager().m_sessions.iterator(); i.hasNext(); ) { WeakReference<SessionImpl> wr = i.next(); SessionImpl si = wr.get(); if( si != null ) v.visit(si); else i.remove(); } } } protected void removeSession(SessionImpl s) { getSessionManager().closeSession(s); } /** * The SessionManager holds a list of Sessions currently owned by this Repository. This * is used to manage the proper shutdown of the Sessions. * */ // FIXME: Should probably have a ReferenceQueue for cleaning away things like locks, etc. private class SessionManager { private ArrayList<WeakReference<SessionImpl>> m_sessions = new ArrayList<WeakReference<SessionImpl>>(); public SessionImpl openSession( Credentials credentials, String workspaceName ) throws RepositoryException { synchronized(m_sessions) { SessionImpl session = new SessionImpl( RepositoryImpl.this, credentials, workspaceName ); m_sessions.add( new WeakReference<SessionImpl>(session) ); return session; } } public void closeSession( SessionImpl s ) { // // Make sure that if we're in the midst of shutdown, these get removed // automatically. // if( m_state == RepositoryImpl.RepositoryState.SHUTTING ) return; synchronized(m_sessions) { for( Iterator<WeakReference<SessionImpl>> i = m_sessions.iterator(); i.hasNext(); ) { WeakReference<SessionImpl> wr = i.next(); SessionImpl si = wr.get(); if( si == null || si == s ) { i.remove(); break; } } // FIXME: Should really check if there is a Session for this workspace // so that we can call ProviderManager.close(); } } } protected interface SessionVisitor { public void visit( SessionImpl session ); } /** * Stops the Provider which stores all the things in this Repository. This is used to * manage a sane shutdown. */ private class ShutdownThread extends Thread { @Override public void run() { log.info( "Running shutdown process (repository closed due to JVM termination)" ); shutdown(); } } private enum RepositoryState { LIVE, SHUTTING, STARTING, DEAD }; } diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index ffa5962..8c57312 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,882 +1,916 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.ChangeStore; import org.priha.util.QName; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); - - private static final int DEFAULT_CACHESIZE = 1000; + + private static final String PROP_SESSIONCACHESIZE = "priha.session.cacheSize"; + private static final String PROP_MAXITEMSIZE = "priha.session.maxCachedItemSize"; + + private int m_maxItemSize; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(); + + // + // The listed defaults here just exist so that something sane would be there. The defaults + // are really read from the priha_defaults.properties or user settings. + // + int cacheSize = Integer.parseInt(session.getRepository().getProperty( PROP_SESSIONCACHESIZE, "1000" )); + m_maxItemSize = Integer.parseInt(session.getRepository().getProperty( PROP_MAXITEMSIZE, "2048") ); + + m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(cacheSize); + m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(cacheSize); - m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); - m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); + log.fine("Initialized SessionProvider with session cache size of "+cacheSize+" items, of max "+m_maxItemSize+" bytes"); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } + /** + * Puts a single Item into the internal caches. + * + * @param ii Item to cache + * @param uuid UUID, or may be null. + */ + private final void cache( final ItemImpl ii, final String uuid ) + { + if( ii instanceof PropertyImpl ) + { + // + // Don't cache very large objects. + // + if( ((PropertyImpl)ii).getValueContainer().getSize() > m_maxItemSize ) + return; + } + + m_fetchedItems.put(ii.getPathReference(), ii); + + if( uuid != null ) + { + m_uuidMap.put(uuid, (NodeImpl) ii); + } + } + /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); - if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); + if( ii != null ) cache( ii, null ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { - m_fetchedItems.put( ii.getPathReference(), ii ); - m_uuidMap.put( uuid, ii ); + cache( ii, uuid ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { // // It's faster to use a LinkedHashSet here, then copy to an ArrayList // when exiting. // Set<Path> res = new LinkedHashSet<Path>(); for( Change c : m_changedItems.getLatestChangesForParent(parentpath) ) { ItemImpl ni = c.getItem(); if( ni.isNode() ) { Path path = ni.getInternalPath(); if( !res.contains(path) && c.getState() != ItemState.REMOVED ) { res.add( path ); } } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } ArrayList<Path> ls = new ArrayList<Path>(res.size()); ls.addAll( res ); return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean itemExists(Path path, ItemType type) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && ((type == ItemType.NODE && c.getItem().isNode()) || (type == ItemType.PROPERTY && !c.getItem().isNode()) ) ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } + ItemImpl ii = m_fetchedItems.get(getPathManager().getPathRef(path)); + + if( ii != null && ((type == ItemType.NODE && ii.isNode()) || (type == ItemType.PROPERTY && !ii.isNode())) ) + return true; + return m_source.itemExists(m_workspace, path, type); } -/* - public void open( Credentials credentials, String workspaceName) - throws RepositoryException, - NoSuchWorkspaceException - { - m_source.open(credentials, workspaceName); - } -*/ + public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; ChangeStore changesDone = new ChangeStore(); try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); - m_fetchedItems.put( ni.getPathReference(), ni ); + cache(ni,null); break; case REMOVED: if( !m_source.itemExists( m_workspace, change.getPath(), ItemType.NODE ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case REORDERED: // Reordering has been done by UPDATED, so we just fire some extra events here. Change oldChange; while( (oldChange = changesDone.getLatestChange(change.getPath())) != null ) { if( (oldChange.getState() == ItemState.NEW || oldChange.getState() == ItemState.REMOVED ) || oldChange.getState() == ItemState.MOVED ) { changesDone.remove(oldChange); } } changesDone.add( ItemState.REMOVED, ni ); changesDone.add( ItemState.NEW, ni ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); - m_fetchedItems.put( pi.getPathReference(), pi ); + cache(pi,null); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } changesDone.add( change ); } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; m_workspace.getObservationManager().fireEvents( changesDone ); } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends Path> listProperties(Path path) throws RepositoryException { LinkedHashSet<Path> result = new LinkedHashSet<Path>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.add( path.resolve(pName) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been added. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Change c : m_changedItems.getLatestChangesForParent(path) ) { ItemImpl ii = c.getItem(); if( ii.isNode() == false && (c.getState() != ItemState.REMOVED && c.getState() != ItemState.MOVED ) ) { Path p = ii.getInternalPath(); if( p.getParentPath().equals(path) ) { result.add( p ); } } } return result; } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.itemExists( m_workspace, path, ItemType.NODE ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { - super(); + super( 16, 0.75f, true ); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { - super(); + this(MAX_SIZE); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { return c_sessionPathManager.getPath( p ); } public PathManager getPathManager() { return c_sessionPathManager; } /** * Get the current modified state of a Path. * * @param path * @return Null, if the state does not exist in the change log. */ public ItemState getState( Path path ) { Change c = m_changedItems.getLatestChange( path ); return c != null ? c.getState() : null; } public ItemState getState( PathRef m_path ) throws PathNotFoundException { return getState( getPathManager().getPath(m_path) ); } }
jalkanen/Priha
09c645305aecf99be424123c5eacc67e0a6cf6d2
Adding size calculation.
diff --git a/src/java/org/priha/providers/ValueContainer.java b/src/java/org/priha/providers/ValueContainer.java index 83a573e..a83b6aa 100644 --- a/src/java/org/priha/providers/ValueContainer.java +++ b/src/java/org/priha/providers/ValueContainer.java @@ -1,170 +1,204 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import javax.jcr.*; import org.priha.core.SessionImpl; import org.priha.core.values.QValue; import org.priha.core.values.ValueImpl; /** * Stores a Value with its type. This is what a PropertyImpl stores internally, * and this is what gets passed down to a RepositoryProvider. Most noticeably * the difference is that the Value that a ValueContainer contains is NOT cloned * when you do a getValue(). Therefore, if you getValue() and read its contents * with getStream(), you cannot read it again until you clone the ValueContainer. * Ditto, if you read it with getString() or one of the other scalar values, you * cannot use getStream() anymore. * <p> * To work around this problem, use the sessionInstance() and deepClone() methods, * which will return you a new ValueContainer - or use ValueFactory.cloneValues(). */ public class ValueContainer { public static final ValueContainer UNDEFINED_CONTAINER = new ValueContainer(); private Object m_value; private int m_type = PropertyType.UNDEFINED; private boolean m_multiple; /** * Empty private constructor; use UNDEFINED_CONTAINER if you need something. */ private ValueContainer() {} public ValueContainer(ValueImpl v) { m_value = v; m_multiple = false; m_type = v.getType(); } public ValueContainer(ValueImpl[] v, int type) { m_value = v; m_multiple = true; m_type = type; } public ValueContainer(Value[] values, int propertyType) { m_multiple = true; m_type = propertyType; m_value = new ValueImpl[values.length]; System.arraycopy(values, 0, m_value, 0, values.length); } public int getType() { return m_type; } public ValueImpl getValue() throws ValueFormatException { if( m_multiple == true ) throw new ValueFormatException("Attempt to get a multivalue"); return (ValueImpl)m_value; } public ValueImpl[] getValues() throws ValueFormatException { if( m_multiple == false ) throw new ValueFormatException("Attempt to get a single value"); return (ValueImpl[])m_value; } public boolean isMultiple() { return m_multiple; } public String toString() { try { return isMultiple() ? (PropertyType.nameFromValue( m_type )+"["+getValues().length+"]") : m_value.toString(); } catch( ValueFormatException e ) {} return "Error?"; } /** * Returns a new ValueContainer which has mappings to the given Session. * * @param session * @return * @throws ValueFormatException */ public ValueContainer sessionInstance( SessionImpl session ) throws ValueFormatException { if( m_multiple ) { ValueImpl[] newValues = new ValueImpl[getValues().length]; for( int i = 0; i < getValues().length; i++ ) { ValueImpl vi = getValues()[i]; if( vi instanceof QValue.QValueInner ) { vi = ((QValue.QValueInner)vi).getQValue().getValue( session ); } newValues[i] = vi; } return new ValueContainer( newValues, m_type ); } if( getValue() instanceof QValue.QValueInner ) { return new ValueContainer( ((QValue.QValueInner)getValue()).getQValue().getValue( session ) ); } return this; } /** * Cloning of a ValueContainer is a deep operation, i.e. you will get all new Value instances. * This is because the Values might be consumed already, esp. if they are streams. * * @throws RepositoryException * @throws UnsupportedRepositoryOperationException * @throws IllegalStateException * @throws ValueFormatException */ public ValueContainer deepClone( SessionImpl session ) throws ValueFormatException, IllegalStateException, UnsupportedRepositoryOperationException, RepositoryException { if( m_multiple ) { Value[] newValues = session.getValueFactory().cloneValues( getValues() ); return new ValueContainer(newValues, getType()); } else { ValueImpl newValue = session.getValueFactory().cloneValue( getValue() ); return new ValueContainer( newValue ); } } public boolean isEmpty() { return m_value == null; } + + private long m_cachedSize; + + /** + * Calculates the rough size of this object in bytes. + * + * @return + */ + public long getSize() + { + if( m_cachedSize != -1 ) return m_cachedSize; + + if( m_value != null ) + { + if( m_multiple ) + { + long size = 0; + for( ValueImpl v : (ValueImpl[]) m_value ) + { + long sz = v.getSize(); + if( sz < 0 ) { size = -1; break; } + size += sz; + } + + m_cachedSize = size; + } + else + { + m_cachedSize = ((ValueImpl)m_value).getSize(); + } + } + + return m_cachedSize; + } }
jalkanen/Priha
c45918fd1632cfd0f5059fac54bbd3bac4840837
Added getSize()
diff --git a/src/java/org/priha/core/values/BooleanValueImpl.java b/src/java/org/priha/core/values/BooleanValueImpl.java index 7f9ae66..7705aef 100644 --- a/src/java/org/priha/core/values/BooleanValueImpl.java +++ b/src/java/org/priha/core/values/BooleanValueImpl.java @@ -1,91 +1,97 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; public class BooleanValueImpl extends ValueImpl implements Value, Serializable { private static final long serialVersionUID = 1L; Boolean m_value; public BooleanValueImpl(boolean value) { m_value = value; } public BooleanValueImpl(String value) { m_value = Boolean.valueOf(value); } public BooleanValueImpl(BooleanValueImpl value) { m_value = value.m_value; } public int getType() { return PropertyType.BOOLEAN; } @Override public boolean getBoolean() { checkValue(); return m_value; } @Override public InputStream getStream() throws RepositoryException { checkStream(); try { return new ByteArrayInputStream( m_value.toString().getBytes("UTF-8") ); } catch (UnsupportedEncodingException e) { throw new RepositoryException("Yeah right, you don't have UTF-8. Your platform is b0rked."); } } @Override public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return m_value.toString(); } @Override public String toString() { return m_value.toString(); } + + @Override + public long getSize() + { + return 1; + } } diff --git a/src/java/org/priha/core/values/CalendarValueImpl.java b/src/java/org/priha/core/values/CalendarValueImpl.java index be8c637..97b07cf 100644 --- a/src/java/org/priha/core/values/CalendarValueImpl.java +++ b/src/java/org/priha/core/values/CalendarValueImpl.java @@ -1,147 +1,153 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; public class CalendarValueImpl extends ValueImpl implements Value, Serializable { private static final long serialVersionUID = -8918655334999478605L; private Calendar m_value = Calendar.getInstance(); private static ThreadLocal<SimpleDateFormat> c_isoFormat = new ThreadLocal<SimpleDateFormat>() { protected synchronized SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); } }; public CalendarValueImpl( Calendar c ) { m_value = c; } public CalendarValueImpl( Double value ) throws ValueFormatException { this( value.longValue() ); } public CalendarValueImpl( Long value ) throws ValueFormatException { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis( value ); m_value = cal; } public CalendarValueImpl(String value) throws ValueFormatException { Calendar cal = Calendar.getInstance(); cal.setTime( parse(value) ); m_value = cal; } public CalendarValueImpl(CalendarValueImpl value) { m_value = value.m_value; } public int getType() { return PropertyType.DATE; } /** * Formats a date in the ISO 8601 format required by JCR. * * @param date * @return */ public static String format( Date date ) { return c_isoFormat.get().format(date); } public static Date parse( String date ) throws ValueFormatException { try { Date d = c_isoFormat.get().parse(date); if( d == null ) throw new ValueFormatException("Cannot be parsed as date: "+date); return d; } catch( Exception e ) { throw new ValueFormatException("Cannot be parsed as date: "+date); } } @Override public Calendar getDate() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return m_value; } @Override public double getDouble() { checkValue(); return m_value.getTimeInMillis(); } @Override public long getLong() { checkValue(); return m_value.getTimeInMillis(); } @Override public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return c_isoFormat.get().format(m_value.getTime()); } @Override public InputStream getStream() { checkStream(); String val = c_isoFormat.get().format( m_value.getTime() ); return new ByteArrayInputStream(val.getBytes()); } public String toString() { if( m_value != null ) return c_isoFormat.get().format( m_value.getTime() ); return "Null value"; } + + @Override + public long getSize() + { + return 112; // Roughly, is missing Timezone info + } } diff --git a/src/java/org/priha/core/values/DoubleValueImpl.java b/src/java/org/priha/core/values/DoubleValueImpl.java index 95cf4b7..481e05b 100644 --- a/src/java/org/priha/core/values/DoubleValueImpl.java +++ b/src/java/org/priha/core/values/DoubleValueImpl.java @@ -1,117 +1,123 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.Serializable; import java.util.Calendar; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; public class DoubleValueImpl extends ValueImpl implements Value, Serializable { private static final long serialVersionUID = -3927800064326452318L; private Double m_value; public DoubleValueImpl( double value ) { m_value = value; } public DoubleValueImpl(String value) throws ValueFormatException { try { m_value = Double.parseDouble(value); } catch( Exception e ) { throw new ValueFormatException( e.getMessage() ); } } public DoubleValueImpl(DoubleValueImpl value) { m_value = value.m_value; } public int getType() { return PropertyType.DOUBLE; } @Override public Calendar getDate() { checkValue(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis( m_value.longValue() ); return cal; } @Override public long getLong() { return m_value.longValue(); } @Override public double getDouble() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return m_value; } @Override public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return Double.toString( m_value ); } @Override public int compareTo( ValueImpl value ) { try { if( value.getType() == PropertyType.DOUBLE || value.getType() == PropertyType.LONG ) return m_value.compareTo(value.getDouble()); return super.compareTo( value ); } catch( RepositoryException e ) {} return 0; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } @Override public String toString() { return m_value.toString(); } + + @Override + public long getSize() + { + return 8; + } } diff --git a/src/java/org/priha/core/values/LongValueImpl.java b/src/java/org/priha/core/values/LongValueImpl.java index 9501114..128f1fa 100644 --- a/src/java/org/priha/core/values/LongValueImpl.java +++ b/src/java/org/priha/core/values/LongValueImpl.java @@ -1,110 +1,123 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.Serializable; import java.util.Calendar; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; public class LongValueImpl extends ValueImpl implements Value, Serializable { private static final long serialVersionUID = -6722775187710834343L; private Long m_value; public LongValueImpl( long value ) { m_value = value; } public LongValueImpl(String value) throws ValueFormatException { try { m_value = Long.parseLong(value); } catch( Exception e ) { throw new ValueFormatException("Cannot be parsed as long: "+value); } } public LongValueImpl(LongValueImpl value) { m_value = value.m_value; } public int getType() { return PropertyType.LONG; } @Override public long getLong() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return m_value; } @Override public Calendar getDate() { checkValue(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis( m_value ); return cal; } @Override public double getDouble() { return m_value; } @Override public int compareTo( ValueImpl value ) { try { if( value.getType() == PropertyType.DOUBLE || value.getType() == PropertyType.LONG ) return m_value.compareTo(value.getLong()); return super.compareTo( value ); } catch( RepositoryException e ) {} return 0; } @Override public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return Long.toString( m_value ); } @Override public String toString() { return m_value.toString(); } + + @Override + public long getSize() + { + return 8; + } + + @Override + protected Object clone() throws CloneNotSupportedException + { + // TODO Auto-generated method stub + return super.clone(); + } } diff --git a/src/java/org/priha/core/values/NodeValueImpl.java b/src/java/org/priha/core/values/NodeValueImpl.java index 0211289..4ed4385 100644 --- a/src/java/org/priha/core/values/NodeValueImpl.java +++ b/src/java/org/priha/core/values/NodeValueImpl.java @@ -1,81 +1,87 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.Value; import org.priha.core.NodeImpl; /** * Superclass of all classes which reference a Node * */ public abstract class NodeValueImpl extends ValueImpl implements Value, Serializable { protected int m_type; protected String m_value; protected NodeValueImpl( NodeImpl value, int type ) throws UnsupportedRepositoryOperationException, RepositoryException { m_value = value.getUUID(); m_type = type; } protected NodeValueImpl(String value, int type) { m_value = value; m_type = type; } @Override public String getString() { return m_value.toString(); } @Override public InputStream getStream() { return new ByteArrayInputStream( m_value.toString().getBytes() ); } public int getType() { return m_type; } @Override public String valueAsString() { return m_value; } @Override public String toString() { return m_value.toString(); } + + @Override + public long getSize() + { + return m_value.length() * 2; + } } diff --git a/src/java/org/priha/core/values/QNameValue.java b/src/java/org/priha/core/values/QNameValue.java index 3aef700..32de16e 100644 --- a/src/java/org/priha/core/values/QNameValue.java +++ b/src/java/org/priha/core/values/QNameValue.java @@ -1,108 +1,122 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.Serializable; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; import org.priha.core.namespace.NamespaceMapper; import org.priha.util.QName; public class QNameValue extends QValue implements Serializable { private static final long serialVersionUID = -5040292769406453341L; private QName m_value; public QNameValue(QName value) { m_value = value; } public QNameValue(NamespaceMapper na, String value) throws RepositoryException { m_value = na.toQName( value ); } @Override public ValueImpl getValue(NamespaceMapper nsm) { return new Impl(nsm); } public QName getValue() { return m_value; } public class Impl extends ValueImpl implements Value, Serializable, QValue.QValueInner { private static final long serialVersionUID = 1L; public NamespaceMapper m_mapper; public Impl(NamespaceMapper nsm) { m_mapper = nsm; } public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { return m_mapper.fromQName( m_value ); } public int getType() { return PropertyType.NAME; } public QNameValue getQValue() { return QNameValue.this; } public String toString() { try { return getString(); } catch( Exception e ) { return "Conversion failed for "+m_value; } } + + @Override + public long getSize() + { + long lp = 0, nm = 0, pr = 0; + + if( m_value.getLocalPart() != null ) lp = m_value.getLocalPart().length(); + if( m_value.getNamespaceURI() != null ) lp = m_value.getNamespaceURI().length(); + if( m_value.getPrefix() != null ) lp = m_value.getPrefix().length(); + + return (lp+nm+pr) * 2; + } } @Override public String getString() { return m_value.toString(); } @Override public String toString() { return m_value.toString(); } + + } diff --git a/src/java/org/priha/core/values/StreamValueImpl.java b/src/java/org/priha/core/values/StreamValueImpl.java index a0cab67..f188af7 100644 --- a/src/java/org/priha/core/values/StreamValueImpl.java +++ b/src/java/org/priha/core/values/StreamValueImpl.java @@ -1,171 +1,184 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; import org.priha.core.binary.BinarySource; import org.priha.core.binary.MemoryBinarySource; import org.priha.util.FileUtil; // FIXME: This class does not yet implement Serializable - it needs to serialize // itself as a proper bytearraystream or use the serialization from the BinarySource public class StreamValueImpl extends ValueImpl implements Value { private BinarySource m_value; public StreamValueImpl(ValueImpl val) throws IllegalStateException, RepositoryException { if( val instanceof StreamValueImpl ) { m_value = ((StreamValueImpl)val).m_value.clone(); } else { try { m_value = new MemoryBinarySource( val.getStream() ); } catch (IOException e) { throw new ValueFormatException("Cannot construct a binary source: "+e.getMessage()); } } } public StreamValueImpl(InputStream in) throws ValueFormatException { try { m_value = new MemoryBinarySource( in ); } catch (IOException e) { throw new ValueFormatException("Cannot construct a binary source: "+e.getMessage()); } } public StreamValueImpl(BinarySource source) { m_value = source; } public StreamValueImpl(String value) throws IOException { byte[] v = value.getBytes("UTF-8"); m_value = new MemoryBinarySource(v); } public int getType() { return PropertyType.BINARY; } public long getLength() throws IOException { return m_value.getLength(); } @Override public InputStream getStream() throws IllegalStateException, RepositoryException { checkStream(); try { return m_value.getStream(); } catch (IOException e) { throw new IllegalStateException("Stream read error:"+e.getMessage()); } } @Override public String getString() throws ValueFormatException { checkStream(); String res; try { res = FileUtil.readContents( m_value.getStream(), "UTF-8" ); } catch (IOException e) { throw new ValueFormatException("Stream cannot be interpreted in UTF-8"); } return res; } @Override public Calendar getDate() throws ValueFormatException { checkStream(); Calendar cal = Calendar.getInstance(); cal.setTime( CalendarValueImpl.parse( getString() ) ); return cal; } @Override public double getDouble() throws ValueFormatException { checkStream(); try { return Double.parseDouble( getString() ); } catch( NumberFormatException e ) { throw new ValueFormatException("Conversion from Stream to Double failed: "+e.getMessage()); } } @Override public long getLong() throws ValueFormatException { checkStream(); try { return Long.parseLong( getString() ); } catch( NumberFormatException e ) { throw new ValueFormatException("Conversion from Stream to Long failed: "+e.getMessage()); } } @Override public boolean getBoolean() throws ValueFormatException { checkStream(); return Boolean.parseBoolean( getString() ); } + + @Override + public long getSize() + { + try + { + return m_value.getLength(); + } + catch (IOException e) + { + return -1; + } + } } diff --git a/src/java/org/priha/core/values/StringValueImpl.java b/src/java/org/priha/core/values/StringValueImpl.java index f476233..a85fb13 100644 --- a/src/java/org/priha/core/values/StringValueImpl.java +++ b/src/java/org/priha/core/values/StringValueImpl.java @@ -1,134 +1,140 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.util.Calendar; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; public class StringValueImpl extends ValueImpl implements Value, Serializable { private static final long serialVersionUID = 6874691155431565288L; String m_value; public StringValueImpl( String value ) { m_value = value; } public int getType() { return PropertyType.STRING; } @Override public boolean getBoolean() { checkValue(); return Boolean.parseBoolean( m_value ); } @Override public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { checkValue(); return m_value; } @Override public Calendar getDate() throws ValueFormatException { checkValue(); Calendar cal = Calendar.getInstance(); cal.setTime( CalendarValueImpl.parse(m_value) ); return cal; } @Override public double getDouble() throws ValueFormatException { checkValue(); try { return Double.parseDouble( m_value ); } catch( NumberFormatException e ) { throw new ValueFormatException("Conversion from String to Double failed: "+e.getMessage()); } } @Override public long getLong() throws ValueFormatException { checkValue(); try { return Long.parseLong( m_value ); } catch( NumberFormatException e ) { throw new ValueFormatException("Conversion from String to Long failed: "+e.getMessage()); } } public InputStream getStream() throws IllegalStateException, RepositoryException { checkStream(); try { return new ByteArrayInputStream( m_value != null ? m_value.getBytes("UTF-8") : new byte[0] ); } catch (UnsupportedEncodingException e) { // Shall never happen throw new RepositoryException(e); } } @Override public String toString() { return m_value; } @Override public String valueAsString() { return m_value; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } + + @Override + public long getSize() + { + return m_value.length() * 2; + } } diff --git a/src/java/org/priha/core/values/ValueImpl.java b/src/java/org/priha/core/values/ValueImpl.java index 9ae39ee..1e4ae8f 100644 --- a/src/java/org/priha/core/values/ValueImpl.java +++ b/src/java/org/priha/core/values/ValueImpl.java @@ -1,164 +1,175 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.values; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Calendar; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; /** * Implements the Value interface and provides a number of default accessors * for easy development. All accessors by default throw a ValueFormatException, * so you will want to implement those which you can convert to. * */ public abstract class ValueImpl implements Value, Cloneable, Comparable<ValueImpl> { protected VALUE_STATE m_state = VALUE_STATE.UNDEFINED; private enum VALUE_STATE { UNDEFINED, VALUE, STREAM } protected ValueImpl() {} /** * This method makes sure that the Value value is a stream, not a value. * * @throws IllegalStateException If this is a value Value. */ protected final void checkStream() throws IllegalStateException { if( m_state == VALUE_STATE.VALUE ) throw new IllegalStateException("This is a scalar value"); if( m_state == VALUE_STATE.STREAM ) throw new IllegalStateException("Stream already consumed"); m_state = VALUE_STATE.STREAM; } /** * This method makes sure that the Value value is a value, not a stream. * * @throws IllegalStateException If this is a stream value. */ protected final void checkValue() throws IllegalStateException { if( m_state == VALUE_STATE.STREAM ) throw new IllegalStateException(); m_state = VALUE_STATE.VALUE; } public boolean getBoolean() throws ValueFormatException, IllegalStateException, RepositoryException { throw new ValueFormatException("This is not a boolean type: "+getClass().getName()); } public Calendar getDate() throws ValueFormatException, IllegalStateException, RepositoryException { throw new ValueFormatException("This is not a date type: "+getClass().getName()); } public double getDouble() throws ValueFormatException, IllegalStateException, RepositoryException { throw new ValueFormatException("This is not a double type: "+getClass().getName()); } public long getLong() throws ValueFormatException, IllegalStateException, RepositoryException { throw new ValueFormatException("This is not a long type: "+getClass().getName()); } /** * By default, returns the inputstream of the String representation. */ public InputStream getStream() throws IllegalStateException, RepositoryException { try { return new ByteArrayInputStream( getString().getBytes("UTF-8") ); } catch (UnsupportedEncodingException e) { throw new RepositoryException("Yeah right, you don't have UTF-8. Your platform is b0rked."); } } public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { throw new ValueFormatException("Cannot convert to String!"); } public boolean equals( Object o ) { if( o instanceof Value ) { Value v = (Value) o; try { return v.getType() == getType() && v.getString().equals(getString()); } catch( Exception e ) { } } return false; } @Override public String toString() { return getClass().getName()+":"+m_state; } /** * Allows getting the Value as a String without regard to the current Stream/Value format * setting. This means that this method can be called at any time. * * @return The value as a String. However, may return null in case the conversion * cannot be made. Default implementation returns null and subclasses are expected * to override this. * */ public String valueAsString() { return null; } + /** + * Returns the approximate size of this object in bytes. If not determinable, + * returns -1; + * + * @return + */ + public long getSize() + { + return -1; + } + /** * By default, does String comparison, which means it may fail. Subclasses are expected * to override. */ public int compareTo( ValueImpl value ) { try { String s1 = getString(); String s2 = value.getString(); return s1.compareTo( s2 ); } catch(Exception e) { // FIXME: Probably not correct. return 0; } } }
jalkanen/Priha
7be6a69c5ab535efec0af92d5a205d007a736e45
Oops, was leaking file handles.
diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index 974fbce..53ba823 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -864,777 +864,785 @@ public class FileProvider implements RepositoryProvider, PerformanceReporter } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: Protect against windows special names (CON) etc. protected String mangleName( String name ) { // // Check the internal cache first. // String cached = m_mangledNames.get(name); if( cached != null ) { m_cacheHits++; return cached; } m_cacheMisses++; StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } else if( ch == ':' ) { // Colon is not allowed on NTFS or OSX. sb.append( ';' ); } else if( ch >= 'A' && ch <= 'Z' ) { // JSR-170 is case sensitive, so we have to make // sure our storage is too. sb.append( ch ); sb.append( '^' ); } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } String result = sb.toString(); m_mangledNames.put(name, result); return result; } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } private String readContentsAsString( File file ) throws IOException { - return FileUtil.readContents(new FileInputStream(file), "UTF-8"); + FileInputStream fis = new FileInputStream(file); + try + { + return FileUtil.readContents(fis, "UTF-8"); + } + finally + { + if( fis != null ) fis.close(); + } } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; private long m_lastWrite = System.currentTimeMillis(); /* After this many writes the store is compacted. */ private static final int COMPACT_LIMIT = 100; /* But compacting is not done more often than this limit (in ms) */ private static final long COMPACT_TIME_LIMIT = 30*1000L; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); long now = System.currentTimeMillis(); if( ++m_writeCount > COMPACT_LIMIT && (now-m_lastWrite) > COMPACT_TIME_LIMIT ) { //System.out.println( now-m_lastWrite ); serialize(); m_writeCount = 0; m_lastWrite = now; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { // System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } }
jalkanen/Priha
9458ce88de756775b7cb6275f0276f850e5eb50c
Added Node reordering events support.
diff --git a/ChangeLog b/ChangeLog index 1fc45bc..3d22154 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,524 @@ +2010-01-07 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.7.3 + + * Optimization of ProviderManager.loadNode() and Item.enterState(). + Especially the latter helps reading quite a lot. + + * EhCacheProvider.exists() was confusing Nodes with Properties + sometimes. + + * ObservationManager now correctly sends events for Node reordering. + 2010-01-04 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.2 * Implemented Observation. It does not *quite* work yet, but it's only nine errors until TCK pass. 2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> * Fixed XML import tests for versioning by properly checking for checked-in Nodes in XMLImport. You may test Versioning, but the TCK tests are disabled. You can turn them on by editing Release.DESCRIPTORS and setting Repository.OPTION_VERSIONING_SUPPORTED to STR_TRUE. * 0.7.1 * FileProvider speedup - added internal cache for mangleName(). 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index e4756ef..9ec483a 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ - public static final int MINORREVISION = 2; + public static final int MINORREVISION = 3; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_TRUE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/ItemState.java b/src/java/org/priha/core/ItemState.java index fbf1fce..f623024 100644 --- a/src/java/org/priha/core/ItemState.java +++ b/src/java/org/priha/core/ItemState.java @@ -1,37 +1,38 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; /** * The ItemState enumeration tracks the state of a Node. * <ul> * <li>NEW = The Item is new, and has never been saved. * <li>EXISTS = Item was loaded from the repository and has not been changed. * <li>REMOVED = Item has been removed and cannot be addressed any more. * <li>MOVED = Item was moved * </ul> */ public enum ItemState { NEW, EXISTS, REMOVED, MOVED, UPDATED, - UNDEFINED + UNDEFINED, + REORDERED } diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 0a6b595..8c45965 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,1448 +1,1452 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; import org.priha.core.locks.LockManager; import org.priha.core.locks.QLock; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; /** * Implements a Node. This is one of the most heavy classes in Priha, with a lot * of stuff happening. The NodeImpl class does some basic caching for some state * objects, so keeping references can be faster in some cases. */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { + private static final String PRIHA_TMPMOVE = "priha:tmpmove"; + public static final QName Q_PRIHA_TMPMOVE = QName.valueOf("{"+RepositoryManager.NS_PRIHA+"}tmpmove"); + private static final String JCR_FROZENUUID = "jcr:frozenUuid"; private static final String JCR_FROZENNODE = "jcr:frozenNode"; private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; /** * A compile-time flag for allowing/disallowing Same Name Sibling support. * addNode() will throw an exception if you disallow these. This is sometimes * useful for debugging. */ private static final boolean ALLOW_SNS = true; private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; private static final String NO_UUID = ""; // If there is no UUID for this Node. static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { enterState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.enterState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.enterState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public LazyPropertyIteratorImpl getProperties() throws RepositoryException { List<Path> ls = new ArrayList<Path>(); ls.addAll(m_session.m_provider.listProperties(getInternalPath())); return new LazyPropertyIteratorImpl( getSession(), ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); m_cachedUUID = uuid.toString(); pi.loadValue( vfi.createValue( m_cachedUUID ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.enterState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } /** * Returns the UUID for this node. Utilizes an internal cache for the UUID, * so is fast after the first call. */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { if( NO_UUID.equals(m_cachedUUID) && !hasProperty(JCR_UUID) ) throw new UnsupportedRepositoryOperationException(); if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { // OK, so let's fallthrough to the exception throwing part. } } m_cachedUUID = NO_UUID; throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } /** * Returns true, if this Node has a child with the given QName. * * @param name A QName. * @return True, if there is a child by this name. * @throws RepositoryException */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { m_lockManager.removeLock( lock ); } - // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { if( srcChildRelPath.indexOf('[') != -1 || hasNode(srcChildRelPath+"[2]" ) ) { // Yes, we are moving a SNS so this needs reordering. - Path tmpPath = getInternalPath().resolve( m_session, "priha:tmpmove" ); + Path tmpPath = getInternalPath().resolve( m_session, PRIHA_TMPMOVE ); // First, store the old version m_session.internalMove( srcPath, tmpPath, false ); String childName = srcChildRelPath.replaceAll( "\\[\\d+\\]", "" ); // FIXME: Hackish trick. boolean last = false; if( dstPath == null ) { NodeIterator ni = getNodes(childName); dstPath = getInternalPath().resolve( m_session, childName+"["+ni.getSize()+"]" ); last = true; } int dir; int startIdx; int endIdx; if( srcPath.getLastComponent().getIndex() < dstPath.getLastComponent().getIndex() ) { // When moving forward, the dstPath is not actually the correct index; // we want to place it _before_ the given index. if( !last ) { int idx = dstPath.getLastComponent().getIndex() - 1; // Real last one dstPath = dstPath.getParentPath().resolve( new Path.Component(dstPath.getLastComponent().getQName(),idx) ); } // Moving stuff forwards dir = -1; startIdx = srcPath.getLastComponent().getIndex()+1; endIdx = dstPath.getLastComponent().getIndex()+1; } else { dir = 1; startIdx = srcPath.getLastComponent().getIndex()-1; endIdx = dstPath.getLastComponent().getIndex()-1; } for( int i = startIdx; i != endIdx; i -= dir ) { String oldName = childName + "[" + i + "]"; String newName = childName + "[" + (i + dir) + "]"; System.out.println("Reordering SNS : "+oldName+" to "+newName); Path path1 = getInternalPath().resolve(m_session,oldName); Path newPath = getInternalPath().resolve(m_session,newName); m_session.internalMove( path1, newPath, false ); } m_session.internalMove( tmpPath, dstPath, false ); } else { // // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. // Path p = newOrder.remove(srcIndex); if( dstIndex != -1 ) newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); else newOrder.add(p); } } finally { m_session.setSuper(isSuper); } // // Lock back up // if( lock != null ) { m_lockManager.moveLock( lock, dstPath ); } // // Finish. // enterState( ItemState.UPDATED ); m_childOrder = newOrder; + // TODO: Also for thingies. + m_session.m_provider.m_changedItems.add( ItemState.REORDERED, getNode(srcChildRelPath) ); } protected PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ protected PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } if( value == null ) { removeProperty(prop); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); } // FIXME: No rollback support public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { if( getState() == ItemState.NEW ) diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index f731f86..ffa5962 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,849 +1,882 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; -import org.priha.util.*; +import org.priha.util.ChangeStore; +import org.priha.util.QName; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); private static final int DEFAULT_CACHESIZE = 1000; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { // // It's faster to use a LinkedHashSet here, then copy to an ArrayList // when exiting. // Set<Path> res = new LinkedHashSet<Path>(); for( Change c : m_changedItems.getLatestChangesForParent(parentpath) ) { ItemImpl ni = c.getItem(); if( ni.isNode() ) { Path path = ni.getInternalPath(); if( !res.contains(path) && c.getState() != ItemState.REMOVED ) { res.add( path ); } } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } ArrayList<Path> ls = new ArrayList<Path>(res.size()); ls.addAll( res ); return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean itemExists(Path path, ItemType type) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && ((type == ItemType.NODE && c.getItem().isNode()) || (type == ItemType.PROPERTY && !c.getItem().isNode()) ) ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.itemExists(m_workspace, path, type); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; - List<Change> changesDone = new ArrayList<Change>(); + ChangeStore changesDone = new ChangeStore(); + try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. + + } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.itemExists( m_workspace, change.getPath(), ItemType.NODE ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; + case REORDERED: + // Reordering has been done by UPDATED, so we just fire some extra events here. + + Change oldChange; + + while( (oldChange = changesDone.getLatestChange(change.getPath())) != null ) + { + if( (oldChange.getState() == ItemState.NEW || oldChange.getState() == ItemState.REMOVED ) || oldChange.getState() == ItemState.MOVED ) + { + changesDone.remove(oldChange); + } + } + + changesDone.add( ItemState.REMOVED, ni ); + changesDone.add( ItemState.NEW, ni ); + + break; + case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } changesDone.add( change ); } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; - m_workspace.getObservationManager().fireEvent( changesDone ); + m_workspace.getObservationManager().fireEvents( changesDone ); } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends Path> listProperties(Path path) throws RepositoryException { LinkedHashSet<Path> result = new LinkedHashSet<Path>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.add( path.resolve(pName) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been added. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Change c : m_changedItems.getLatestChangesForParent(path) ) { ItemImpl ii = c.getItem(); if( ii.isNode() == false && (c.getState() != ItemState.REMOVED && c.getState() != ItemState.MOVED ) ) { Path p = ii.getInternalPath(); if( p.getParentPath().equals(path) ) { result.add( p ); } } } return result; } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.itemExists( m_workspace, path, ItemType.NODE ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { super(); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { super(); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { return c_sessionPathManager.getPath( p ); } public PathManager getPathManager() { return c_sessionPathManager; } - public ItemState getState( PathRef m_path ) throws PathNotFoundException + /** + * Get the current modified state of a Path. + * + * @param path + * @return Null, if the state does not exist in the change log. + */ + public ItemState getState( Path path ) { - Change c = m_changedItems.getLatestChange( getPath(m_path) ); + Change c = m_changedItems.getLatestChange( path ); - return c != null ? c.getState() : null; + return c != null ? c.getState() : null; + } + + public ItemState getState( PathRef m_path ) throws PathNotFoundException + { + return getState( getPathManager().getPath(m_path) ); } } diff --git a/src/java/org/priha/core/observation/EventImpl.java b/src/java/org/priha/core/observation/EventImpl.java new file mode 100644 index 0000000..ef76478 --- /dev/null +++ b/src/java/org/priha/core/observation/EventImpl.java @@ -0,0 +1,68 @@ +/** + * + */ +package org.priha.core.observation; + +import javax.jcr.RepositoryException; +import javax.jcr.observation.Event; + +import org.priha.core.SessionImpl; +import org.priha.path.Path; + +class EventImpl implements Event +{ + SessionImpl m_session; + int m_eventType; + Path m_path; + + public EventImpl(SessionImpl s, int eventType, Path path) + { + m_session = s; + m_eventType = eventType; + m_path = path; + } + + public String getPath() throws RepositoryException + { + return m_path.toString(m_session); + } + + public int getType() + { + return m_eventType; + } + + public String getUserID() + { + return m_session.getUserID(); + } + + public String toString() + { + return getEventString(m_eventType) + " " + m_path.toString(); + } + + private String getEventString(int type) + { + switch( type ) + { + case NODE_ADDED: + return "NODE_ADDED"; + + case NODE_REMOVED: + return "NODE_REMOVED"; + + case PROPERTY_ADDED: + return "PROPERTY_ADDED"; + + case PROPERTY_CHANGED: + return "PROPERTY_CHANGED"; + + case PROPERTY_REMOVED: + return "PROPERTY_REMOVED"; + + default: + return "UNKNOWN"; + } + } +} \ No newline at end of file diff --git a/src/java/org/priha/core/observation/ObservationManagerImpl.java b/src/java/org/priha/core/observation/ObservationManagerImpl.java index 1fcadec..89f1858 100644 --- a/src/java/org/priha/core/observation/ObservationManagerImpl.java +++ b/src/java/org/priha/core/observation/ObservationManagerImpl.java @@ -1,408 +1,413 @@ package org.priha.core.observation; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; +import java.util.*; import java.util.logging.Logger; import javax.jcr.AccessDeniedException; import javax.jcr.ItemNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.observation.*; +import javax.jcr.observation.EventListener; -import org.priha.core.NodeImpl; -import org.priha.core.SessionImpl; -import org.priha.core.WorkspaceImpl; +import org.priha.core.*; import org.priha.path.Path; import org.priha.path.PathFactory; +import org.priha.util.ChangeStore; import org.priha.util.GenericIterator; import org.priha.util.ChangeStore.Change; /** * Implements an ObservationManager. Again, the actual implementation is a per-Session class instantiated * at request. * */ // FIXME: This class is not particularly optimized. public class ObservationManagerImpl { private static ObservationManagerImpl c_manager = new ObservationManagerImpl(); - private ArrayList<EventListenerWrapper> m_listeners = new ArrayList<EventListenerWrapper>(); + private Map<String,List<EventListenerWrapper>> m_listeners = new HashMap<String,List<EventListenerWrapper>>(); private Logger log = Logger.getLogger(ObservationManagerImpl.class.getName()); + /** + * Adds an event listener for a particular Session. + * + * @param session + * @param listener + * @param eventTypes + * @param absPath + * @param isDeep + * @param uuid + * @param nodeTypeName + * @param noLocal + * @throws RepositoryException + */ public void addEventListener(SessionImpl session, EventListener listener, int eventTypes, Path absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal) throws RepositoryException { EventListenerWrapper elw = new EventListenerWrapper(session,listener,eventTypes,absPath,isDeep,uuid,nodeTypeName,noLocal); - m_listeners.add(elw); + List<EventListenerWrapper> list = m_listeners.get(session.getWorkspace().getName()); + + if( list == null ) + list = new ArrayList<EventListenerWrapper>(); + + list.add( elw ); + + m_listeners.put(session.getWorkspace().getName(), list); } + /** + * Lists EventListeners for a given Session. + * + * @param session + * @return + * @throws RepositoryException + */ public EventListenerIterator getRegisteredEventListeners(SessionImpl session) throws RepositoryException { List<EventListener> list = new ArrayList<EventListener>(); - for( Iterator<EventListenerWrapper> i = m_listeners.iterator() ; i.hasNext(); ) + List<EventListenerWrapper> l = m_listeners.get(session.getWorkspace().getName()); + + if( l != null ) { - EventListenerWrapper elw = i.next(); - if( elw.getSessionId().equals(session.getId()) ) + for( Iterator<EventListenerWrapper> i = l.iterator() ; i.hasNext(); ) { - list.add( elw.getListener() ); + EventListenerWrapper elw = i.next(); + if( elw.getSessionId().equals(session.getId()) ) + { + list.add( elw.getListener() ); + } } } - return new Iter(list); } + /** + * Removes an Event listener (for any session) + * @param listener + * @throws RepositoryException + */ public void removeEventListener(EventListener listener) throws RepositoryException { - for( Iterator<EventListenerWrapper> i = m_listeners.iterator() ; i.hasNext(); ) + for( List<EventListenerWrapper> le : m_listeners.values() ) { - if( i.next().getListener() == listener ) + for( Iterator<EventListenerWrapper> i = le.iterator() ; i.hasNext(); ) { - i.remove(); - return; + if( i.next().getListener() == listener ) + { + i.remove(); + return; + } } } } - public void fireEvent( SessionImpl srcSession, List<Change> changes ) + public void fireEvent( SessionImpl srcSession, ChangeStore changes ) { - for( Iterator<EventListenerWrapper> i = m_listeners.iterator() ; i.hasNext(); ) + List<EventListenerWrapper> l = m_listeners.get(srcSession.getWorkspace().getName()); + + if( l != null ) { - EventListenerWrapper elw = i.next(); + for( Iterator<EventListenerWrapper> i = l.iterator() ; i.hasNext(); ) + { + EventListenerWrapper elw = i.next(); - // Fire the event + // Fire the event - try - { - elw.getListener().onEvent( new EventIteratorImpl(filterEvents(srcSession,elw,changes)) ); - } - catch( Exception e ) - { - log.warning("Unable to fire event "+ e.getMessage()); - } - } + try + { + elw.getListener().onEvent( new EventIteratorImpl(filterEvents(srcSession,elw,changes)) ); + } + catch( Exception e ) + { + log.warning("Unable to fire event "+ e.getMessage()); + } + } + } } - private List<Event> filterEvents( SessionImpl session, EventListenerWrapper elw, List<Change> changes ) throws ItemNotFoundException, AccessDeniedException, RepositoryException + private List<Event> filterEvents( SessionImpl session, EventListenerWrapper elw, ChangeStore changes ) throws ItemNotFoundException, AccessDeniedException, RepositoryException { ArrayList<Event> list = new ArrayList<Event>(); for( Change c : changes ) { System.out.println(c); + // Session filtering if( elw.isNoLocal() && session.getId().equals(elw.getSessionId()) ) { continue; } + + // Tags filtering + + if( !c.getItem().isNode() ) + { + if( ((PropertyImpl)c.getItem()).isTransient() ) continue; + } + + // Internal tags filtering + + if( c.getPath().getLastComponent().equals(NodeImpl.Q_PRIHA_TMPMOVE) ) + continue; // Path filtering if( elw.getAbsPath() != null ) { Path itemPath = c.getPath(); Path ePath = elw.getAbsPath(); // // This fairly complicated sentence fulfils the contract on page 272 of JCR-1.0 spec. // if( !(( (!itemPath.isRoot() && ePath.equals(itemPath.getParentPath())) && !elw.isDeep()) || (ePath.isParentOf(itemPath) && elw.isDeep() )) ) { continue; } } // UUID filtering if( elw.getUuids() != null ) { NodeImpl parent = c.getItem().getParent(); try { String parentUUID = parent.getUUID(); if( Arrays.binarySearch( elw.getUuids(), parentUUID ) < 0 ) continue; } catch( UnsupportedRepositoryOperationException e ) {} } // Nodetype filtering if( elw.getNodeTypeNames() != null ) { NodeImpl parent = c.getItem().getParent(); boolean success = false; for( String s : elw.getNodeTypeNames() ) { if( parent.isNodeType(s) ) { success = true; break; } } if( !success ) continue; } + // Transient changes filtering. Priha will actually list all the events, both additions and removals + // so we need to filter out the ones which result in no change in the repository. + + if( c.getState() != ItemState.REMOVED ) + { + if( changes.getLatestChange(c.getPath()).getState() == ItemState.REMOVED ) + continue; + } + // EventType filtering int eventType = -1; switch( c.getState() ) { case NEW: case MOVED: if( c.getItem().isNode() ) eventType = Event.NODE_ADDED; else eventType = Event.PROPERTY_ADDED; break; case UPDATED: if( !c.getItem().isNode() ) eventType = Event.PROPERTY_CHANGED; break; case REMOVED: if( c.getItem().isNode() ) eventType = Event.NODE_REMOVED; else eventType = Event.PROPERTY_REMOVED; break; } if( (elw.getEventTypes() & eventType) == 0 ) { continue; } // Add to the event list if( eventType != -1 ) { Event e = new EventImpl(session, eventType, c.getPath()); list.add( e ); System.out.println("Firing "+e); } } return list; } private static class EventIteratorImpl extends GenericIterator implements EventIterator { public EventIteratorImpl(List<Event> list) { super(list); } public Event nextEvent() { return (Event) super.next(); } } - private static class EventImpl implements Event - { - SessionImpl m_session; - int m_eventType; - Path m_path; - - public EventImpl(SessionImpl s, int eventType, Path path) - { - m_session = s; - m_eventType = eventType; - m_path = path; - } - - public String getPath() throws RepositoryException - { - return m_path.toString(m_session); - } - - public int getType() - { - return m_eventType; - } - - public String getUserID() - { - return m_session.getUserID(); - } - - public String toString() - { - return getEventString(m_eventType) + " " + m_path.toString(); - } - - private String getEventString(int type) - { - switch( type ) - { - case NODE_ADDED: - return "NODE_ADDED"; - - case NODE_REMOVED: - return "NODE_REMOVED"; - - case PROPERTY_ADDED: - return "PROPERTY_ADDED"; - - case PROPERTY_CHANGED: - return "PROPERTY_CHANGED"; - - case PROPERTY_REMOVED: - return "PROPERTY_REMOVED"; - - default: - return "UNKNOWN"; - } - } - } - /** * Provides iteration through EventListeners. * */ private static class Iter extends GenericIterator implements EventListenerIterator { public Iter(List<EventListener> list) { super( list ); } public EventListener nextEventListener() { return (EventListener)super.next(); } public Object next() { return nextEventListener(); } } /** * Wraps everything interesting for an EventListener. */ private static class EventListenerWrapper { private String m_sessionId; private EventListener m_listener; private int m_eventTypes; private Path m_absPath; private boolean m_isDeep; private String[] m_uuids; private String[] m_nodeTypeNames; private boolean m_noLocal; public EventListenerWrapper( SessionImpl session, EventListener listener, int eventTypes, Path absPath, boolean isDeep, String[] uuids, String[] nodeTypeNames, boolean noLocal ) { m_sessionId = session.getId(); m_listener = listener; m_eventTypes = eventTypes; m_absPath = absPath; m_isDeep = isDeep; m_uuids = uuids; m_nodeTypeNames = nodeTypeNames; m_noLocal = noLocal; if( m_uuids != null ) Arrays.sort(m_uuids); } public String getSessionId() { return m_sessionId; } public EventListener getListener() { return m_listener; } public int getEventTypes() { return m_eventTypes; } public Path getAbsPath() { return m_absPath; } public boolean isDeep() { return m_isDeep; } public String[] getUuids() { return m_uuids; } public String[] getNodeTypeNames() { return m_nodeTypeNames; } public boolean isNoLocal() { return m_noLocal; } } /** * Session-local ObservationManager. */ public class Impl implements ObservationManager { SessionImpl m_session; public Impl(SessionImpl session) { m_session = session; } public void addEventListener(EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal) throws RepositoryException { ObservationManagerImpl.this.addEventListener(m_session, listener, eventTypes, PathFactory.getPath(m_session, absPath), isDeep, uuid, nodeTypeName, noLocal); } public EventListenerIterator getRegisteredEventListeners() throws RepositoryException { return ObservationManagerImpl.this.getRegisteredEventListeners(m_session); } public void removeEventListener(EventListener listener) throws RepositoryException { ObservationManagerImpl.this.removeEventListener(listener); } - public void fireEvent( List<Change> change ) + public void fireEvents( ChangeStore changes ) { - ObservationManagerImpl.this.fireEvent( m_session, change ); + ObservationManagerImpl.this.fireEvent( m_session, changes ); } } /** * Get an instance for a Workspace. */ public static ObservationManagerImpl.Impl getInstance(WorkspaceImpl workspaceImpl) { return c_manager.new Impl(workspaceImpl.getSession()); } } diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index 3138597..974fbce 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -88,1597 +88,1553 @@ public class FileProvider implements RepositoryProvider, PerformanceReporter { if( m_workspaceRoot == null ) { m_workspaceRoot = m_root + "/workspaces"; } return m_workspaceRoot; } /** * Figures out what the filename for a Workspace is. * @param ws * @return */ // FIXME: Should escape the filename properly. private String getWorkspaceFilename( Workspace ws ) { return ws.getName(); } /** * Figures out the what the filename for a given path is. * @param path * @return * @throws RepositoryException * @throws NamespaceException */ // FIXME: Should escape the path properly private String getPathFilename( Path path ) throws NamespaceException, RepositoryException { String p = path.toString( RepositoryImpl.getGlobalNamespaceRegistry() ); return mangleName(p); } /** * Create a valid filename based on the QName and a suffix. * * @param name * @param suffix * @return */ private String makeFilename( QName name, String suffix ) { String filename; try { filename = RepositoryImpl.getGlobalNamespaceRegistry().fromQName(name); } catch( NamespaceException e ) { filename = name.getLocalPart(); } if( suffix != null ) filename = filename + suffix; return mangleName(filename); } /** * Returns the directory for a particular Workspace. * * @param wsname * @return */ private String getWorkspaceDir( String wsname ) { String wsDir = getWorkspaceRoot() + "/" + wsname; return wsDir; } /** * Returns the directory in which a particular Node in a particular workspace resides * * @param ws * @param path * @return * @throws RepositoryException * @throws NamespaceException */ private File getNodeDir( Workspace ws, Path path ) throws NamespaceException, RepositoryException { if( m_systemPath.isParentOf( path ) || m_systemPath.equals( path ) ) { return new File( m_root, getPathFilename(path) ); } String wsDir = getWorkspaceDir( getWorkspaceFilename(ws) ); File nodeDir = new File( wsDir, getPathFilename(path) ); return nodeDir; } public void addNode(StoreTransaction tx, Path path, QNodeDefinition def) throws RepositoryException { m_hitCount[Count.AddNode.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path ); nodeDir.mkdirs(); if( !path.isRoot() ) { List<String> order = getOrder(ws,path.getParentPath()); if( !order.contains( path.getLastComponent().toString() ) ) { order.add( path.getLastComponent().toString() ); saveOrder( ws, path.getParentPath(), order ); } } } private void acquirePaths( Path startPath, File dir, List<Path> list, boolean recurse ) { File[] files = dir.listFiles(); if( files == null || files.length == 0 ) return; for( File f : files ) { if( f.isDirectory() ) { try { Properties props = getPropertyInfo( f, Q_JCR_PRIMARYTYPE ); Path p = PathFactory.getPath( props.getProperty( PROP_PATH ) ); list.add( p.getParentPath() ); if( recurse ) { acquirePaths( p.getParentPath(), f, list, recurse ); } } catch( PathNotFoundException e ) { // Skip, don't include. } catch( IOException e ) { // Skip, don't include. } catch (NamespaceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidPathException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch( NullPointerException e ) { e.printStackTrace(); } } } } public List<String> listWorkspaces() { m_hitCount[Count.ListWorkspaces.ordinal()]++; ArrayList<String> list = new ArrayList<String>(); File[] dirs = new File(getWorkspaceRoot()).listFiles(); if( dirs != null ) { for( File f : dirs ) { if( f.isDirectory() ) { list.add( f.getName() ); } } } return list; } private boolean deleteContents( File dir ) { // System.out.println("Deleting "+dir.getAbsolutePath()); for( File f : dir.listFiles() ) { if( f.isDirectory() ) { deleteContents( f ); } if( !f.delete() ) return false; } return true; } public void start(RepositoryImpl rep, Properties props) throws ConfigurationException { m_hitCount[Count.Start.ordinal()]++; try { m_systemPath = PathFactory.getPath( RepositoryImpl.getGlobalNamespaceRegistry(), "/jcr:system" ); } catch( RepositoryException e ) { throw new ConfigurationException("Unable to create a /jcr:system instance: "+e.getMessage()); } String wsList = props.getProperty("workspaces", "default"); m_root = props.getProperty("directory"); // // Make sure that root exists. // File root = new File(m_root); root.mkdirs(); // // Make sure this instance is the only one using that root. // File lockFile = new File(m_root, LOCKFILE); if( lockFile.exists() ) { String msg = "Cannot use the Priha FileProvider repository while another instance of Priha is using it. "+ "If you are sure there are no other instances using this same repository, please "+ "remove the '"+lockFile.getAbsolutePath()+"' file and restart."; log.severe( msg ); throw new ConfigurationException(msg); } // // Create the lock file; and make sure it gets cleaned up properly in // most cases. // try { lockFile.createNewFile(); lockFile.deleteOnExit(); } catch( IOException e ) { throw new ConfigurationException("Cannot start Priha ",e); } // // Initializing the workspaces. // log.fine("Initializing FileProvider with root "+m_root); String[] workspaces = wsList.split("\\s"); for( String wsname : workspaces ) { File wsroot = new File(getWorkspaceDir(wsname)); if( !wsroot.exists() ) { wsroot.mkdirs(); log.finer("Created workspace directory "+wsroot); } // // Reset the workspaces. // m_references.put( wsname, new UUIDObjectStore<Path[]>(mangleName(wsname)+"-references.ser") ); m_uuids.put( wsname, new UUIDObjectStore<Path>(mangleName(wsname)+"-uuid.ser") ); } } public void stop(RepositoryImpl rep) { m_hitCount[Count.Stop.ordinal()]++; log.fine("Shutting down FileProvider..."); for( UUIDObjectStore<Path[]> s : m_references.values() ) { s.shutdown(); } for( UUIDObjectStore<Path> s : m_uuids.values() ) { s.shutdown(); } m_references.clear(); m_uuids.clear(); // // Clean up the lockfile, in case we're e.g. switching repos mid-flight. // File lockFile = new File(m_root, LOCKFILE); lockFile.delete(); log.finer("Manglename cache hits = "+m_cacheHits+", misses = "+m_cacheMisses); } public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Copy.ordinal()]++; throw new UnsupportedRepositoryOperationException("copy()"); } public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws NamespaceException, RepositoryException { m_hitCount[Count.ListNodes.ordinal()]++; ArrayList<Path> list = new ArrayList<Path>(); File startPath = getNodeDir( ws, parentpath ); if( !startPath.exists() ) throw new PathNotFoundException("No such path found: "+parentpath); //acquirePaths( parentpath, startPath, list, false ); List<String> orderArray = getOrder( ws, parentpath ); for( String s : orderArray ) { Path childPath = parentpath.resolve( Path.Component.valueOf( s ) ); list.add( childPath ); } // // The .order -file will probably not contain the system path for anyone else // except the workspace which was created first. // if( parentpath.isRoot() && !list.contains( m_systemPath )) { list.add( 0, m_systemPath ); } return list; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.ListProperties.ordinal()]++; File nodeDir = getNodeDir( ws, path ); List<QName> proplist = new ArrayList<QName>(); try { File[] files = nodeDir.listFiles( new PropertyTypeFilter() ); if( files != null ) { for( File propertyFile : files ) { Properties props; FileInputStream in = null; try { in = new FileInputStream(propertyFile); props = FastPropertyStore.load(in); String qname = props.getProperty(PROP_PATH); proplist.add( PathFactory.getPath( qname ).getLastComponent() ); } finally { if( in != null ) in.close(); } } } } catch( IOException e ) { throw new RepositoryException("Thingy said booboo", e); } return proplist; } public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Move.ordinal()]++; throw new UnsupportedRepositoryOperationException("move()"); } /** * A Node exists only if it has a primaryType.info in the directory. */ public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) { m_hitCount[Count.ItemExists.ordinal()]++; File nodeDir; try { File propFile; if( type == ItemType.NODE ) { nodeDir = getNodeDir( ws, path ); propFile = new File( nodeDir, mangleName("jcr:primaryType.info") ); } else if( type == ItemType.PROPERTY ) { nodeDir = getNodeDir( ws, path.getParentPath() ); propFile = new File( nodeDir, makeFilename( path.getLastComponent(), ".info" ) ); } else { throw new IllegalArgumentException("Type "+type.name()+" not supported"); } return propFile.exists(); } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_hitCount[Count.Open.ordinal()]++; List<String> wsnames = listWorkspaces(); if( wsnames.indexOf(workspaceName) == -1 ) throw new NoSuchWorkspaceException(workspaceName); log.finer("Workspace "+workspaceName+" has been opened."); } public void close(WorkspaceImpl ws) { log.finer( "Workspace "+ws.getName()+" closing..." ); m_hitCount[Count.Close.ordinal()]++; /* try { m_uuids.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } catch( NullPointerException e ) { log.warning( "A non-configured workspace '"+ws.getName()+"' detected. If you are using a multiprovider configuration, please check this workspace actually exists." ); return; } try { m_references.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } */ } private void writeValue( File f, ValueImpl v ) throws IOException, IllegalStateException, RepositoryException { OutputStream out = null; InputStream in = null; try { if( v instanceof QValue.QValueInner ) { byte[] ba = ((QValue.QValueInner)v).getQValue().getString().getBytes("UTF-8"); in = new ByteArrayInputStream(ba); } else { in = v.getStream(); } out = new FileOutputStream( f ); - copyContents( in, out ); + FileUtil.copyContents( in, out ); } finally { // // ...and close all the streams. // if( out != null ) { try { out.close(); } finally { if( in != null ) in.close(); } } } } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc) throws RepositoryException { m_hitCount[Count.PutPropertyValue.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path.getParentPath() ); saveUuidShortcut(ws,path,vc); QName qname = path.getLastComponent(); File inf = new File( nodeDir, makeFilename( qname, ".info" ) ); Properties props = new Properties(); props.setProperty( PROP_PATH, path.toString() ); props.setProperty( PROP_TYPE, PropertyType.nameFromValue( vc.getType() ) ); props.setProperty( PROP_MULTIPLE, vc.isMultiple() ? "true" : "false" ); OutputStream out = null; try { if( vc.isMultiple() ) { props.setProperty( PROP_NUM_PROPERTIES, Integer.toString(vc.getValues().length) ); Value[] values = vc.getValues(); // // Let's clear previous references, if this is an attempt to save // a null value. // if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl[] oldval = getPropertyValue( ws, path ).getValues(); for( ValueImpl vi : oldval ) { String uuid = vi.getString(); cleanRefMapping( ws, path, uuid ); } } catch( PathNotFoundException e ){} // This is okay } for( int i = 0; i < values.length; i++ ) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); saveRefShortcut( ws, path, (ValueImpl)values[i] ); writeValue( df, (ValueImpl)values[i] ); } // Remove the rest of old values int i = values.length; while(true) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); if( df.exists() ) df.delete(); else break; } } else { if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl oldval = getPropertyValue( ws, path ).getValue(); cleanRefMapping( ws, path, oldval.getString() ); } catch(PathNotFoundException e) {} // OK saveRefShortcut( ws, path, vc.getValue() ); } File df = new File( nodeDir, makeFilename( qname, ".data" ) ); writeValue( df, vc.getValue() ); } out = new FileOutputStream(inf); FastPropertyStore.store( out, props ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * Saves a shortcut to an UUID. The contents of the file are the path of the Node. * */ private void saveUuidShortcut(WorkspaceImpl ws, Path path, ValueContainer vc) throws RepositoryException { if( path.getLastComponent().equals(Q_JCR_UUID) ) { UUIDObjectStore<Path> uuids = m_uuids.get( ws.getName() ); uuids.setObject( vc.getValue().valueAsString(), path.getParentPath() ); } } private ValueImpl prepareValue( WorkspaceImpl ws, File propFile, String propType ) throws IOException, RepositoryException { ValueFactoryImpl vf = ws.getSession().getValueFactory(); ValueImpl value; if( propType.equals(PropertyType.TYPENAME_STRING) ) { value = vf.createValue( readContentsAsString(propFile) ); } else if( propType.equals(PropertyType.TYPENAME_BOOLEAN) ) { value = vf.createValue( "true".equals(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DOUBLE) ) { value = vf.createValue( Double.parseDouble(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_LONG) ) { value = vf.createValue( Long.parseLong(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DATE) ) { value = vf.createValue( readContentsAsString( propFile ), PropertyType.DATE ); } else if( propType.equals(PropertyType.TYPENAME_NAME) ) { String qnameStr = readContentsAsString(propFile); QName qn = QName.valueOf( qnameStr ); value = vf.createValue( qn, PropertyType.NAME ); } else if( propType.equals(PropertyType.TYPENAME_PATH )) { String val = readContentsAsString(propFile); value = vf.createValue( val, PropertyType.PATH ); } else if( propType.equals(PropertyType.TYPENAME_REFERENCE ) ) { value = vf.createValue( readContentsAsString(propFile), PropertyType.REFERENCE ); } else if( propType.equals(PropertyType.TYPENAME_BINARY) ) { value = vf.createValue( new FileBinarySource(propFile) ); } else throw new RepositoryException("Cannot deserialize property type "+propType); return value; } /** * Returns the contents of the .info -file. * * @param nodeDir * @return * @throws PathNotFoundException * @throws IOException */ private Properties getPropertyInfo( File nodeDir, QName name ) throws PathNotFoundException, IOException { File inf = new File( nodeDir, makeFilename( name, ".info" ) ); if( !inf.exists() ) { throw new PathNotFoundException("The property metadata file was not found: "+inf.getAbsolutePath()); } Properties props; FileInputStream in = null; try { in = new FileInputStream( inf ); props = FastPropertyStore.load(in); } finally { if( in != null ) in.close(); } return props; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.GetPropertyValue.ordinal()]++; File nodeDir = getNodeDir( ws, path.getParentPath() ); try { Properties props = getPropertyInfo( nodeDir, path.getLastComponent() ); String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); ValueImpl[] result = new ValueImpl[items]; for( int i = 0; i < items; i++ ) { File df = new File( nodeDir, makeFilename(path.getLastComponent(),"."+i+".data") ); ValueImpl v = prepareValue( ws, df, propType ); result[i] = v; } return new ValueContainer(result, PropertyType.valueFromName( propType ) ); } File df = new File( nodeDir, makeFilename( path.getLastComponent(), ".data" ) ); ValueImpl v = prepareValue(ws, df, propType); return new ValueContainer(v); } catch( IOException e ) { throw new RepositoryException("Unable to read property file",e); } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: Protect against windows special names (CON) etc. protected String mangleName( String name ) { // // Check the internal cache first. // String cached = m_mangledNames.get(name); if( cached != null ) { m_cacheHits++; return cached; } m_cacheMisses++; StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } else if( ch == ':' ) { // Colon is not allowed on NTFS or OSX. sb.append( ';' ); } else if( ch >= 'A' && ch <= 'Z' ) { // JSR-170 is case sensitive, so we have to make // sure our storage is too. sb.append( ch ); sb.append( '^' ); } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } String result = sb.toString(); m_mangledNames.put(name, result); return result; } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } - - /** - * Just copies all characters from <i>in</i> to <i>out</i>. - */ - private static void copyContents( InputStream in, OutputStream out ) - throws IOException - { - byte[] buf = new byte[BUFFER_SIZE]; - int bytesRead = 0; - - while ((bytesRead = in.read(buf)) > 0) - { - out.write(buf, 0, bytesRead); - } - - out.flush(); - } - - private static void copyContents(Reader in, Writer out) - throws IOException - { - char[] buf = new char[BUFFER_SIZE]; - int bytesRead = 0; - - while ((bytesRead = in.read(buf)) > 0) - { - out.write(buf, 0, bytesRead); - } - - out.flush(); - } - private String readContentsAsString( File file ) throws IOException { - Reader in = new InputStreamReader( new FileInputStream(file), "UTF-8" ); - - try - { - StringWriter out = new StringWriter(); - copyContents( in, out ); - - return out.toString(); - } - finally - { - in.close(); - } + return FileUtil.readContents(new FileInputStream(file), "UTF-8"); } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; private long m_lastWrite = System.currentTimeMillis(); /* After this many writes the store is compacted. */ private static final int COMPACT_LIMIT = 100; /* But compacting is not done more often than this limit (in ms) */ private static final long COMPACT_TIME_LIMIT = 30*1000L; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); long now = System.currentTimeMillis(); if( ++m_writeCount > COMPACT_LIMIT && (now-m_lastWrite) > COMPACT_TIME_LIMIT ) { //System.out.println( now-m_lastWrite ); serialize(); m_writeCount = 0; m_lastWrite = now; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { // System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } } diff --git a/src/java/org/priha/util/ChangeStore.java b/src/java/org/priha/util/ChangeStore.java index 61b3920..5c481c9 100644 --- a/src/java/org/priha/util/ChangeStore.java +++ b/src/java/org/priha/util/ChangeStore.java @@ -1,442 +1,466 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.util.*; import org.priha.core.ItemImpl; import org.priha.core.ItemState; import org.priha.core.PropertyImpl; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.ValueContainer; /** * Provides a list of changes, which can be both played back * one by one, as well as searched rapidly. * <p> * Internally, this class stores both a List of Change objects, * as well as a HashMap pointing at the latest change. It can be * iterated both forwards (using peek() and remove() and iterator()) as well * as backwards (using values()). * <p> * In addition, it stores a separate reference to all the changes relating * to a particular parent path (making it fairly fast to filter based on a path). */ public class ChangeStore implements Iterable<ChangeStore.Change> { private ArrayList<Change> m_changes = new ArrayList<Change>(); private HashMap<Path,Change> m_latest = new HashMap<Path,Change>(); private HashMap<Path,List<Change>> m_childChanges = new HashMap<Path,List<Change>>(); /** * Create a ChangeStore without the HashMap. */ public ChangeStore() {} /** * Returns the newest ItemImpl that corresponds to the Path given. * * @param path Path to search for * @return Newest Item or null, if no such thing is found. */ public ItemImpl getLatestItem( Path path ) { Change c = getLatestChange( path ); if( c != null ) return c.getItem(); return null; } /** * Finds the latest change. * * @param path Path to search for * @return The Change or null, if no such thing found. */ public Change getLatestChange( Path path ) { Change c = m_latest.get( path ); return c; } /** * Get all the latest changes, ignoring any duplicate changes. * * @return A list of latest changes. */ public List<Change> getLatestChanges() { ArrayList<Change> changes = new ArrayList<Change>(); changes.addAll( m_latest.values() ); return changes; } /** * Returns a list of Changes filtered by a parent path. * * @param parent The path to filter against * @return A list of Changes. */ public List<Change> getLatestChangesForParent( Path parent ) { ArrayList<Change> changes = new ArrayList<Change>(); List<Change> c = m_childChanges.get(parent); if( c != null ) changes.addAll( c ); return changes; } /** * Adds a new Item with given ItemState to the end of the Change List. * * @param newState New state * @param ii The Item */ public void add( ItemState newState, ItemImpl ii ) { Change c = new Change( newState, ii ); add( c ); } /** * Adds a whole Change object at the end of the Change List. * * @param c The Change to add * @return True, at the moment. */ public boolean add( Change c ) { if( c.getState() == ItemState.UNDEFINED ) { dump(); throw new IllegalStateException("You cannot add an UNDEFINED Item "+c.getItem().getInternalPath()); } m_changes.add(c); m_latest.put( c.getPath(), c ); if( !c.getPath().isRoot() ) { try { List<Change> pc = m_childChanges.get( c.getPath().getParentPath() ); if( pc == null ) { pc = new ArrayList<Change>(); m_childChanges.put( c.getPath().getParentPath(), pc ); } pc.add( c ); } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot add path "+c.getPath()); } } return true; } /** * Gets the first change from the change list. Returns null, if there are no more * changes. * * @return The first change from the list, or null, if the list was empty. */ public Change peek() { if( m_changes.size() > 0 ) return m_changes.get(0); return null; } + public boolean remove( Change c ) + { + if( m_changes.remove(c) ) + { + internalRemove(c); + + return true; + } + + return false; + } + + private void internalRemove(Change c) + { + m_latest.remove(c.getPath()); + + if( !c.getPath().isRoot() ) + { + try + { + Path parent = c.getPath().getParentPath(); + + List<Change> pc = m_childChanges.get( parent ); + + pc.remove( c ); // FIXME: repeated with remove(). + + if( pc.isEmpty() ) + { + m_childChanges.remove( parent ); + } + } + catch( InvalidPathException e ) + { + throw new IllegalStateException("Cannot remove "+c.getPath()); + } + } + } + /** * Removes the first change from the change list. * * @return The first change from the list, or null, if the list was empty. */ public Change remove() { Change c = null; if( m_changes.size() > 0 ) { c = m_changes.remove(0); - m_latest.remove( c.getPath() ); - - if( !c.getPath().isRoot() ) - { - try - { - Path parent = c.getPath().getParentPath(); - - List<Change> pc = m_childChanges.get( parent ); - - pc.remove( c ); // FIXME: SLow. - - if( pc.isEmpty() ) - { - m_childChanges.remove( parent ); - } - } - catch( InvalidPathException e ) - { - throw new IllegalStateException("Cannot remove "+c.getPath()); - } - } - + internalRemove(c); } return c; } /** * Clears the changes. * * @return The number of changes removed from the queue. */ public int clear() { int numChanges = m_changes.size(); m_changes.clear(); m_latest.clear(); m_childChanges.clear(); return numChanges; } /** * Returns a forward iterator for the Changes. * * @return A forward iterator for the Changes. */ public Iterator<Change> iterator() { return new ForwardIterator(); } /** * Returns a <b>backward</b> iterator for the Items in the change list. The first * value you get is the newest value on the stack. This means * that the iteration order for iterator() and values() is reversed. * * @return A reverse iterator for the values. */ public Iterator<ItemImpl> values() { return new ItemIterator(); } /** * Returns true, if there are no changes. * * @return True, if there are no changes. */ public final boolean isEmpty() { return m_changes.isEmpty(); } + public void addAll( ChangeStore store ) + { + for( Change c : store ) + { + add( c ); + } + } + /** * Implements a backwards iterator through the Items in the list. */ private class ItemIterator implements Iterator<ItemImpl> { int m_position; protected ItemIterator() { m_position = m_changes.size()-1; } public final boolean hasNext() { return m_position > 0; } public final ItemImpl next() { return m_changes.get(m_position--).getItem(); } public void remove() { throw new UnsupportedOperationException(); } } private class ForwardIterator implements Iterator<Change> { int m_position; protected ForwardIterator() { m_position = 0; } public final boolean hasNext() { return m_position < m_changes.size(); } public final Change next() { return m_changes.get(m_position++); } public void remove() { if( m_position == 0 ) throw new IllegalStateException(); Change c = m_changes.remove( --m_position ); m_latest.remove( c.getPath() ); if( !c.getPath().isRoot() ) { try { Path parent = c.getPath().getParentPath(); List<Change> pc = m_childChanges.get( parent ); pc.remove( c ); // FIXME: SLow. if( pc.isEmpty() ) { m_childChanges.remove( parent ); } } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot remove "+c.getPath()); } } } } /** * Dumps the store contents for debugging to System.out. */ public void dump() { System.out.println("DUMP OF CHANGESTORE @"+Integer.toHexString(this.hashCode())); System.out.println(this); } /** * Outputs a human-readable description of the contents of the ChangeStore. * * @return Somethign human-readable. */ public String toString() { StringBuilder sb = new StringBuilder(); for( Change c : this ) { sb.append( c.getState().toString() + ": " + c.getPath() + ": " + c.getItem() + "\n" ); } return sb.toString(); } /** * Stores a single change. */ public static final class Change { private ItemState m_state; private ItemImpl m_item; private Path m_path; private ValueContainer m_valueContainer; /** * Create a new Change for the given ItemState and item. If the * Item is a property, also the Value is copied internally. * * @param newState The new state * @param item The item */ public Change( ItemState newState, ItemImpl item ) { m_state = newState; m_item = item; m_path = item.getInternalPath(); if( !item.isNode() ) { m_valueContainer = ((PropertyImpl)item).getValueContainer(); if( m_valueContainer.isEmpty() && newState != ItemState.REMOVED ) throw new IllegalArgumentException("Null value in valuecontainer for "+m_path); } } /** * Returns the Item for this Change. * * @return The Item. */ public final ItemImpl getItem() { return m_item; } /** * Returns the ItemState for this Change. * * @return The ItemState. */ public final ItemState getState() { return m_state; } /** * Returns the Path for this Change. * * @return The Path. */ public final Path getPath() { return m_path; } /** * Return the ValueContainer for the Change. * * @return The ValueContainer, or null, if the Change concerned a Node. */ public final ValueContainer getValue() { return m_valueContainer; } public String toString() { return m_state.toString()+" "+m_item.getInternalPath(); } } } diff --git a/src/java/org/priha/util/FastPropertyStore.java b/src/java/org/priha/util/FastPropertyStore.java index 47107c7..41da3b4 100644 --- a/src/java/org/priha/util/FastPropertyStore.java +++ b/src/java/org/priha/util/FastPropertyStore.java @@ -1,138 +1,133 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Map; import java.util.Properties; /** * Provides a very fast way of saving and loading Property files. The format * is almost the same as with regular ones, with few key differences: * <ul> * <li>The file encoding is UTF-8 * <li>Unicode entities (\\u) are not recognized * <li>Line continuations are not supported (line ends with a backslash) * <li>Always uses \\n for ending the line, on all architectures. * </ul> */ public class FastPropertyStore { public static void store(OutputStream out, Properties props) throws IOException { BufferedWriter o = new BufferedWriter(new OutputStreamWriter(out,"UTF-8") ); for( Map.Entry<Object,Object> e : props.entrySet() ) { String key = (String)e.getKey(); String value = (String)e.getValue(); o.write( key ); o.write( "=" ); o.write( value ); o.write( "\n" ); } o.flush(); } public static Properties load(FileInputStream in) throws IOException { Properties props = new Properties(); - +/* FileChannel fc = in.getChannel(); - //MappedByteBuffer bb = fc.map(MapMode.READ_ONLY, 0, fc.size() ); - - ByteBuffer ba = ByteBuffer.allocate( (int) fc.size() ); + ByteBuffer ba = ByteBuffer.allocate( Math.max( (int)fc.size(), 8*1024 ) ); // at least 8kB fc.read( ba ); String c = new String( ba.array(), "UTF-8" ); + */ - /* - BufferedReader i = new BufferedReader(new InputStreamReader( in,"UTF-8" )); - */ - /* ByteArrayOutputStream ba = new ByteArrayOutputStream(); FileUtil.copyContents( in, ba ); String c = new String( ba.toByteArray(), "UTF-8" ); - */ + BufferedStringReader i = new BufferedStringReader(c); String line; while( (line = i.readLine()) != null ) { line = line.trim(); if( line.length() == 0 || line.charAt( 0 ) == '#' ) continue; int eqSign = line.indexOf( '=' ); if( eqSign == -1 ) throw new IOException("Illegal format in property file"); String key = line.substring( 0, eqSign ); String val = line.substring( eqSign+1 ); props.put( key, val ); } return props; } /** * This is a very fast String reader which implements the readLine() * method by returning substrings of the given string. EOL is * determined by the \\n character. */ private static class BufferedStringReader { String m_string; int m_pos; public BufferedStringReader( String s ) { m_string = s; } public String readLine() { if( m_pos >= m_string.length() ) return null; String result; int newline = m_string.indexOf( '\n', m_pos ); if( newline >= 0 ) { result = m_string.substring( m_pos, newline ); m_pos = newline+1; } else { result = m_string.substring( m_pos ); m_pos = m_string.length()+1; } return result; } } } diff --git a/src/java/org/priha/util/FileUtil.java b/src/java/org/priha/util/FileUtil.java index a696803..e110fb4 100644 --- a/src/java/org/priha/util/FileUtil.java +++ b/src/java/org/priha/util/FileUtil.java @@ -1,145 +1,149 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; +import java.nio.channels.FileChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.util.Properties; import java.util.logging.Logger; import org.priha.core.RepositoryImpl; public class FileUtil { private static final int BUFFER_SIZE = 4096; private static Logger log = Logger.getLogger(FileUtil.class.getName()); /** * Just copies all characters from <I>in</I> to <I>out</I>. The copying * is performed using a buffer of bytes. * * @since 1.5.8 * @param in The reader to copy from * @param out The reader to copy to * @throws IOException If reading or writing failed. */ public static void copyContents( Reader in, Writer out ) throws IOException { char[] buf = new char[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } /** * Just copies all bytes from <I>in</I> to <I>out</I>. The copying is * performed using a buffer of bytes. * * @since 1.9.31 * @param in The inputstream to copy from * @param out The outputstream to copy to * @throws IOException In case reading or writing fails. */ public static void copyContents( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } /** - * Reads in file contents. + * Reads in file contents and assumes it's a String. This method is fastest + * up until 4-8 kB in size. * * @param input The InputStream to read from. * @param encoding The encoding to assume at first. * @return A String, interpreted in the "encoding", or, if it fails, in Latin1. * @throws IOException If the stream cannot be read or the stream cannot be * decoded. */ public static String readContents( InputStream input, String encoding ) throws IOException { + ByteBuffer bbuf; + ByteArrayOutputStream out = new ByteArrayOutputStream(); FileUtil.copyContents( input, out ); - ByteBuffer bbuf = ByteBuffer.wrap( out.toByteArray() ); - + bbuf = ByteBuffer.wrap( out.toByteArray() ); + Charset cset = Charset.forName( encoding ); CharsetDecoder csetdecoder = cset.newDecoder(); csetdecoder.onMalformedInput( CodingErrorAction.REPLACE ); csetdecoder.onUnmappableCharacter( CodingErrorAction.REPLACE ); try { CharBuffer cbuf = csetdecoder.decode( bbuf ); return cbuf.toString(); } catch( CharacterCodingException e ) { log.fine( "Failed to map a character to UTF-8" ); } return null; } /** * Takes a list of paths and attempts to locate a property file from * the list. The first one which can be loaded is parsed and returned. * * @param propertyPaths * @return * @throws IOException If the reading failed. */ public static Properties findProperties(String[] propertyPaths) throws IOException { Properties props = new Properties(); for( int i = 0; i < propertyPaths.length; i++ ) { InputStream in = RepositoryImpl.class.getResourceAsStream(propertyPaths[i]); if( in != null ) { props.load(in); log.fine("Loaded properties from "+propertyPaths[i]); break; } } return props; } } diff --git a/tests/java/org/priha/util/FileUtilTest.java b/tests/java/org/priha/util/FileUtilTest.java new file mode 100644 index 0000000..ad1a1d0 --- /dev/null +++ b/tests/java/org/priha/util/FileUtilTest.java @@ -0,0 +1,196 @@ +package org.priha.util; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.util.Random; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.priha.core.PerformanceTest.Perf; + +public class FileUtilTest extends TestCase +{ + public static String readContentsIO( FileInputStream input, String encoding, boolean decodeNIO ) + throws IOException + { + ByteBuffer bbuf; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + FileUtil.copyContents(input, out); + + bbuf = ByteBuffer.wrap(out.toByteArray()); + + return decodeNIO ? decodeNIO(encoding, bbuf) : decodeIO(encoding, bbuf); + } + + public static String readContentsNIO( FileInputStream input, String encoding, boolean decodeNIO ) + throws IOException + { + ByteBuffer bbuf; + + FileChannel fc = input.getChannel(); + bbuf = ByteBuffer.allocate( (int)fc.size() ); + + fc.read(bbuf); + bbuf.flip(); + + return decodeNIO ? decodeNIO(encoding, bbuf) : decodeIO(encoding, bbuf); + } + + private static String decodeIO(String encoding, ByteBuffer bbuf) throws UnsupportedEncodingException + { + if( bbuf.hasArray() ) + return new String( bbuf.array(), encoding ); + + throw new IllegalArgumentException(); + } + + private static String decodeNIO(String encoding, ByteBuffer bbuf) + { + Charset cset = Charset.forName(encoding); + CharsetDecoder csetdecoder = cset.newDecoder(); + + csetdecoder.onMalformedInput(CodingErrorAction.REPLACE); + csetdecoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + + try + { + CharBuffer cbuf = csetdecoder.decode(bbuf); + + return cbuf.toString(); + } + catch (CharacterCodingException e) + { + e.printStackTrace(); + } + return null; + } + + private static File createTempFile( int txtlen ) throws IOException + { + Random r = new Random(); + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < txtlen; i++ ) + { + int c = 'A' + r.nextInt(25); + sb.append( (char)c ); + } + + String s = sb.toString(); + + assertEquals( txtlen, s.length() ); + File f = File.createTempFile("tmp", "txt"); + + FileOutputStream fout = new FileOutputStream(f); + + fout.write( s.getBytes("UTF-8") ); + + fout.close(); + + return f; + } + + /** + * Test what is the fastest way to read a file. + * + * @throws Exception + */ + public void testReadContent() throws Exception + { + runSingleTest(16); + runSingleTest(32); + runSingleTest(64); + runSingleTest(128); + runSingleTest(256); + runSingleTest(512); + runSingleTest(1024); + runSingleTest(2048); + runSingleTest(4096); + runSingleTest(16384); + runSingleTest(65536); + runSingleTest(65536*16); + + System.out.println(); + Perf.print(); + } + + private void runSingleTest(int size) throws IOException, FileNotFoundException + { + int numIters = 1000; + File f = createTempFile( size ); + + System.out.print("."); System.out.flush(); + + Perf.setTestable("Length: "+size); + Perf.start("IO+IO"); + + for( int i = 0; i < numIters; i++ ) + { + FileInputStream fis = new FileInputStream(f); + String s = readContentsIO(fis, "UTF-8",false); + fis.close(); + assertEquals( size, s.length()); + } + + Perf.stop(numIters); + + Perf.start("NIO+IO"); + + for( int i = 0; i < numIters; i++ ) + { + try + { + FileInputStream fis = new FileInputStream(f); + String s = readContentsNIO(fis, "UTF-8",false); + fis.close(); + assertEquals( size, s.length()); + } + catch( IllegalArgumentException e ) { break; } + } + + Perf.stop(numIters); + + Perf.start("IO+NIO"); + + for( int i = 0; i < numIters; i++ ) + { + try + { + FileInputStream fis = new FileInputStream(f); + String s = readContentsIO(fis, "UTF-8",true); + fis.close(); + assertEquals( size, s.length()); + } + catch( IllegalArgumentException e ) { break; } + } + + Perf.stop(numIters); + Perf.start("NIO+NIO"); + + for( int i = 0; i < numIters; i++ ) + { + try + { + FileInputStream fis = new FileInputStream(f); + String s = readContentsNIO(fis, "UTF-8",true); + fis.close(); + assertEquals( size, s.length()); + } + catch( IllegalArgumentException e ) { break; } + } + + Perf.stop(numIters); + } + + public static TestSuite suite() + { + return new TestSuite(FileUtilTest.class); + } +}
jalkanen/Priha
7873cc46f51537dbd3fbcd67c0808cd2bbc27790
Removed obsolete code, itemExists() didn't heed item type.
diff --git a/src/java/org/priha/providers/EhCachingProvider.java b/src/java/org/priha/providers/EhCachingProvider.java index 7c94f1d..c9e8b78 100644 --- a/src/java/org/priha/providers/EhCachingProvider.java +++ b/src/java/org/priha/providers/EhCachingProvider.java @@ -1,475 +1,458 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import javax.jcr.*; import javax.management.MBeanServer; import net.sf.ehcache.*; import net.sf.ehcache.constructs.blocking.LockTimeoutException; import net.sf.ehcache.management.ManagementService; import org.priha.core.ItemType; import org.priha.core.ProviderManager; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.core.values.StreamValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.Path; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * Uses EHCache for an intermediate level cache. It lies on top of a real provider, * like FileProvider, and provides caching for most of the items that can be fetched * from the cache. Configurable properties are: * <ul> * <li><b>realProvider</b> - The nickname of the underlying provider to use.</li> * <li><b>cacheName</b> - A name for the cache under which it gets registered to * the EHCache CacheManager. If a cache by this name already * exists (e.g. from the ehcache configuration XML file), * it will be used. If it does not exist, we create one.</li> * <li><b>size</b> - The size of the cache (in items; default is 5000)</li> * <li><b>maxSize</b> - The maximum size of the objects which are cached. Default is 10 kB. * </ul> * Priha creates a memory only cache. */ public class EhCachingProvider implements RepositoryProvider { private static final int DEFAULT_CACHESIZE = 5000; private static final String DEFAULT_CACHENAME = "priha.ehCache"; private static final long DEFAULT_MINCACHEABLESIZE = 10*1024; public static final String PROP_MAXCACHEABLESIZE = "maxSize"; public static final String PROP_SIZE = "size"; public static final String PROP_CACHENAME = "cacheName"; public static final String PROP_REALPROVIDER = "realProvider"; private Logger log = Logger.getLogger(EhCachingProvider.class.getName()); private CacheManager m_cacheManager; private Ehcache m_valueCache; private RepositoryProvider m_realProvider; private long m_maxCacheableSize = DEFAULT_MINCACHEABLESIZE; public EhCachingProvider() { } public void start(RepositoryImpl repository, Properties properties) throws ConfigurationException { m_cacheManager = CacheManager.getInstance(); String realProviderNick = properties.getProperty(PROP_REALPROVIDER); Properties props = ProviderManager.filterProperties(repository, realProviderNick); String className = props.getProperty("class"); String workspaceList = properties.getProperty("workspaces"); if( workspaceList != null ) props.setProperty("workspaces", workspaceList); m_realProvider = ProviderManager.instantiateProvider(repository, className, props); String cacheName = props.getProperty(PROP_CACHENAME, DEFAULT_CACHENAME); int size = Integer.parseInt( props.getProperty(PROP_SIZE, Integer.toString(DEFAULT_CACHESIZE) ) ); // Since we store multiple objects per a single cache item (UUIDs/etc), we double the size // of the cache here. size = size * 2; m_maxCacheableSize = Long.parseLong( props.getProperty(PROP_MAXCACHEABLESIZE, Long.toString( DEFAULT_MINCACHEABLESIZE ) ) ); Ehcache myCache = m_cacheManager.getEhcache( cacheName ); if( myCache == null ) { - myCache = new Cache(cacheName, size, false, true, 30, 20); + myCache = new Cache(cacheName, size, false, true, 3000, 2000); // // For some completely unfathomable reason, the BlockingCache blocks // on the same thread every 5-10 calls to getPropertyValue() on OSX 10.4, // both Java5 and Java6. So until I figure out what is going on, // we can't use it :-( // // myCache = new BlockingCache(myCache)); // // ((BlockingCache)myCache).setTimeoutMillis( 10*1000 ); m_cacheManager.addCache(myCache); } m_valueCache = m_cacheManager.getEhcache( cacheName ); // // Register to MBeanServer // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); try { ManagementService.registerMBeans(m_cacheManager, mBeanServer, false, false, false, true); } catch( CacheException e ) { // Failure is not fatal. } log.fine("Started EHCache with real provider class "+m_realProvider.getClass().getName()); } public void stop(RepositoryImpl rep) { m_realProvider.stop(rep); m_cacheManager.shutdown(); log.fine("Stopped EHCache"); } /** * Gives an unique ID with which to use as the cache key for Values. * * @param ws * @param path * @return */ private final String getVid(WorkspaceImpl ws, Path path) { return ws.getName()+";"+path.toString()+";V"; } /** For the Property name lists */ private final String getPid(WorkspaceImpl ws, Path path) { return ws.getName()+";"+path.toString()+";P"; } /** For the Node child lists */ private final String getNid(WorkspaceImpl ws, Path path) { return ws.getName()+";"+path.toString()+";N"; } /** For UUIDs */ private final String getUid(WorkspaceImpl ws, String uuid) { return ws.getName()+";"+uuid; // UUIDs are unique enough } /** For Reverse UUIDs */ private final String getRUid(WorkspaceImpl ws, Path path ) { return ws.getName()+";"+path.toString()+";U"; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_realProvider.open(rep, credentials, workspaceName); } public void close(WorkspaceImpl ws) { if( m_valueCache.getStatus() == Status.STATUS_ALIVE ) { Statistics s = m_valueCache.getStatistics(); log.fine("EHCache statistics right before close(): "+s.toString()); m_valueCache.removeAll(); } m_realProvider.close(ws); } public void addNode(StoreTransaction tx, Path path, QNodeDefinition def) throws RepositoryException { if( !path.isRoot() ) m_valueCache.remove( getNid(tx.getWorkspace(),path.getParentPath()) ); m_realProvider.addNode(tx, path,def); } -/* - public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException - { - m_realProvider.copy(ws, srcpath, destpath); - } -*/ + /* * UUIDs are fairly safe because even if the Node was deleted, SessionImpl will * attempt to fetch the Node itself based on the Path, so that will fail then. * So we can just cache all the values happily. * * Also, the mappings don't really change, except in a move() operation. * * (non-Javadoc) * @see org.priha.providers.RepositoryProvider#findByUUID(org.priha.core.WorkspaceImpl, java.lang.String) */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { try { Element e = m_valueCache.get( getUid( ws, uuid ) ); if( e != null ) { return (Path)e.getObjectValue(); } Path p = m_realProvider.findByUUID(ws, uuid); m_valueCache.put( new Element( getUid( ws, uuid ), p ) ); m_valueCache.put( new Element( getRUid( ws, p ), uuid ) ); return p; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout getting propery value"); } catch( RuntimeException e ) { // Release lock m_valueCache.put( new Element( getUid( ws, uuid ), null ) ); throw new RepositoryException("Error getting property value"); } } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { return m_realProvider.findReferences(ws, uuid); } // // Binary objects are not cached, unless they are smaller than the max cacheable size. // private boolean isCacheable(ValueContainer o) throws ValueFormatException { if( o.getType() == PropertyType.BINARY ) { if( !o.isMultiple() && o.getValue() instanceof StreamValueImpl ) { StreamValueImpl svi = (StreamValueImpl)o.getValue(); try { return svi.getLength() <= m_maxCacheableSize; } catch( IOException e ) {} // Fine, can be ignored. } return false; } return true; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { String key = getVid(ws,path); try { Element e = m_valueCache.get( key ); if( e != null ) { ValueContainer o = (ValueContainer)e.getObjectValue(); // // If this is a mapped instance, then we'll actually return // a new copy of it for this particular Session. // // FIXME: Optimize by checking the Session, if this comes from the same one, no need to clone. // return o.sessionInstance( ws.getSession() ); } ValueContainer o = m_realProvider.getPropertyValue(ws, path); if( isCacheable(o) ) { e = new Element( key, o ); m_valueCache.put( e ); } return o; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout getting propery value",e); } catch( RuntimeException e ) { throw new RepositoryException("Error getting propery value",e); } } @SuppressWarnings("unchecked") public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws RepositoryException { try { Element e = m_valueCache.get( getNid(ws,parentpath) ); if( e != null ) return (List<Path>)e.getValue(); List<Path> list = m_realProvider.listNodes(ws, parentpath); e = new Element( getNid(ws,parentpath), list ); m_valueCache.put( e ); return list; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout getting propery value"); } catch( RuntimeException e ) { // Release lock m_valueCache.put( new Element(getNid(ws,parentpath),null) ); throw new RepositoryException("Error getting propery value", e); } } @SuppressWarnings("unchecked") public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { try { Element e = m_valueCache.get( getPid(ws,path) ); if( e != null ) return (List<QName>)e.getValue(); List<QName> list = m_realProvider.listProperties(ws, path); e = new Element( getPid(ws,path), list ); m_valueCache.put( e ); return list; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout listing properties"); } catch( RuntimeException e ) { // Release lock m_valueCache.put( new Element(getPid(ws,path),null) ); throw new RepositoryException("Error listing properties"); } } public Collection<String> listWorkspaces() throws RepositoryException { return m_realProvider.listWorkspaces(); } -/* - public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException + + public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) throws RepositoryException { - // - // We need to make sure UUID mapping is still okay. - // - - Element e = m_valueCache.get( getRUid(ws,srcpath) ); - if( e != null ) + if( type == ItemType.NODE ) { - String uuid = (String)e.getValue(); - m_valueCache.remove( uuid ); - m_valueCache.remove( getRUid(ws,srcpath) ); + if( m_valueCache.isKeyInCache( getNid(ws,path) ) ) + return true; + } + else + { + if( m_valueCache.isKeyInCache( getVid( ws, path ) ) ) + return true; } - - m_realProvider.move(ws, srcpath, destpath); - } -*/ - public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) throws RepositoryException - { - if( m_valueCache.isKeyInCache( getNid(ws,path) ) ) - return true; - - if( m_valueCache.isKeyInCache( getVid( ws, path ) )) - return true; return m_realProvider.itemExists(ws, path,type); } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc ) throws RepositoryException { WorkspaceImpl ws = tx.getWorkspace(); m_valueCache.remove( getVid(ws,path ) ); m_realProvider.putPropertyValue(tx, path, vc); if( isCacheable( vc ) ) { Element e = new Element( getVid( ws, path ), vc ); m_valueCache.put( e ); } } public void remove(StoreTransaction tx, Path path) throws RepositoryException { m_realProvider.remove(tx,path); WorkspaceImpl ws = tx.getWorkspace(); m_valueCache.remove( getVid(ws,path) ); m_valueCache.remove( getPid(ws,path) ); m_valueCache.remove( getNid(ws,path) ); if( !path.isRoot() ) m_valueCache.remove( getNid(ws,path.getParentPath()) ); } public void storeFinished( StoreTransaction tx ) throws RepositoryException { m_realProvider.storeFinished( tx ); } public void storeCancelled( StoreTransaction tx ) throws RepositoryException { m_realProvider.storeCancelled( tx ); // Something fairly hairy happened, so we hedge our bets by emptying the cache // completely. m_valueCache.removeAll(); } public StoreTransaction storeStarted( WorkspaceImpl ws ) throws RepositoryException { return m_realProvider.storeStarted( ws ); } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException { m_realProvider.reorderNodes(tx, internalPath, childOrder); } }
jalkanen/Priha
af06bdc292694a96a82bccb200ccb117384c5802
Optimization of getItem()
diff --git a/src/java/org/priha/core/ProviderManager.java b/src/java/org/priha/core/ProviderManager.java index 6cec6cc..f583ae3 100644 --- a/src/java/org/priha/core/ProviderManager.java +++ b/src/java/org/priha/core/ProviderManager.java @@ -1,671 +1,693 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009' Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import javax.jcr.version.VersionException; import org.priha.core.values.QNameValue; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.RepositoryProvider; import org.priha.providers.StoreTransaction; import org.priha.providers.ValueContainer; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * This is a front-end class for managing multiple providers * for a single repository. * <p> * The ProviderManager is a singleton per Repository. */ public class ProviderManager implements ItemStore { private HashMap<String,ProviderInfo> m_workspaceAccess; private ProviderInfo[] m_providers; private RepositoryImpl m_repository; private Logger log = Logger.getLogger(ProviderManager.class.getName()); private String m_defaultWorkspaceName; public ProviderManager( RepositoryImpl repository ) throws ConfigurationException { m_repository = repository; initialize(); } public static final String PROP_PRIHA_PROVIDERS = "priha.providers"; public static final String PROP_PRIHA_PROVIDER_PREFIX = "priha.provider."; public static final String DEFAULT_PROVIDERLIST = "defaultProvider"; /** * Initializes all the Providers defined in the property file. * * @throws ConfigurationException If the properties would define an illegal configuration. */ private void initialize() throws ConfigurationException { m_workspaceAccess = new HashMap<String,ProviderInfo>(); String providerList = m_repository.getProperty( PROP_PRIHA_PROVIDERS ); if( providerList == null ) throw new ConfigurationException("Required property missing",PROP_PRIHA_PROVIDERS); String[] providers = providerList.split("\\s"); if( providers.length == 0 ) throw new ConfigurationException("Empty property",PROP_PRIHA_PROVIDERS); m_providers = new ProviderInfo[providers.length]; for( int i = 0; i < providers.length; i++ ) { Properties props = filterProperties(m_repository,providers[i]); String className = props.getProperty("class"); if( className == null ) throw new ConfigurationException("Provider "+providers[i]+" does not declare a class name. "+ "There should be a property called '"+PROP_PRIHA_PROVIDER_PREFIX+providers[i]+".class' in your properties."); String workspaceList = props.getProperty("workspaces","default"); String[] workspaces = workspaceList.split("\\s"); if( m_defaultWorkspaceName == null ) { if( workspaces.length == 0 ) throw new ConfigurationException("The first provider ("+providers[i]+") MUST have at least one workspace defined!"); m_defaultWorkspaceName = workspaces[0]; log.fine("Default workspace is set to '"+m_defaultWorkspaceName+"'"); } log.fine("Provider "+i+": "+providers[i]+" is a "+className); RepositoryProvider p = instantiateProvider( m_repository, className, props ); m_providers[i] = new ProviderInfo(); m_providers[i].provider = p; m_providers[i].workspaces = workspaces; m_providers[i].lock = new ReentrantReadWriteLock(); for( String ws : workspaces ) { if( m_workspaceAccess.containsKey(ws) ) throw new ConfigurationException("Workspace "+ws+" is defined multiple times. Very likely you have forgotten to declare a workspace property for a Provider declaration."); m_workspaceAccess.put(ws, m_providers[i]); } } } /** * [0] = /largefiles/ * [1] = / * * "/" => 1 * "/largefiles" => 0 * "/largefiles2" => 1 * "/largefiles/foo" => 0 * * @param p * @return * @throws ConfigurationException */ private final ProviderInfo getProviderInfo(WorkspaceImpl wi, Path p) throws ConfigurationException { ProviderInfo pi = m_workspaceAccess.get(wi.getName()); if( pi != null ) return pi; throw new ConfigurationException("Nonexistant workspace: "+wi.getName()); } /** * Filters the properties set when the Repository was created to find * the property set for a provider. * <p> * Essentially returns a property set where all instances of * <code>priha.provider.[providerName].property = value</code> * are replaced with <code>property = value</code>. * * @param repository The repository from which the properties are read * @param providerName The name to filter with * @return A valid set of Properties. It can also be empty, if there * were no properties defined for this providerName. * @see ProviderManager#instantiateProvider(RepositoryImpl, String, Properties) */ public static Properties filterProperties( RepositoryImpl repository, String providerName ) { Properties props = new Properties(); String prefix = PROP_PRIHA_PROVIDER_PREFIX + providerName + "."; for( Enumeration<String> e = repository.getPropertyNames(); e.hasMoreElements(); ) { String key = e.nextElement(); if( key.startsWith(prefix) ) { String val = repository.getProperty(key); key = key.substring(prefix.length()); props.setProperty(key, val); } } return props; } /** * Instantiates a RepositoryProvider using the given class name and * the properties, and calls its start() method. * * @param rep The RepositoryImpl who will own this RepositoryProvider * @param className The FQN of the class. * @param props A filtered set of Properties * @return A started RepositoryProvider. * * @throws ConfigurationException If the provider cannot be instantiated or the configuration * is faulty. * * @see ProviderManager#filterProperties(RepositoryImpl, String) */ public static RepositoryProvider instantiateProvider(RepositoryImpl rep, String className, Properties props) throws ConfigurationException { Class<?> cl; RepositoryProvider provider; try { cl = Class.forName( className ); provider = (RepositoryProvider) cl.newInstance(); provider.start( rep, props ); } catch (ClassNotFoundException e) { throw new ConfigurationException("Could not find provider class",className); } catch (InstantiationException e) { throw new ConfigurationException("Could not instantiate provider class",className); } catch (IllegalAccessException e) { throw new ConfigurationException("Could not access provider class",className); } return provider; } public void open(Credentials credentials, String workspaceName) throws NoSuchWorkspaceException, RepositoryException { ProviderInfo pi = m_workspaceAccess.get(workspaceName); if( pi == null ) throw new NoSuchWorkspaceException("No such workspace: '"+workspaceName+"'"); try { pi.lock.writeLock().lock(); pi.provider.open( m_repository, credentials, workspaceName ); } finally { pi.lock.writeLock().unlock(); } } private ValueContainer getPropertyValue(WorkspaceImpl impl, Path ptPath) throws RepositoryException { ProviderInfo pi = getProviderInfo(impl,ptPath); try { pi.lock.readLock().lock(); ValueContainer stored = pi.provider.getPropertyValue( impl, ptPath ); return stored; } finally { pi.lock.readLock().unlock(); } } /** * Returns the set of workspaces declared in the config file. * * @throws ConfigurationException */ public Collection<String> listWorkspaces() throws ConfigurationException { return m_workspaceAccess.keySet(); } public List<Path>listNodes(WorkspaceImpl impl, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( impl, path ); try { pi.lock.readLock().lock(); return pi.provider.listNodes( impl, path ); } finally { pi.lock.readLock().unlock(); } } public void close(WorkspaceImpl impl) { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.close( impl ); } finally { pi.lock.writeLock().unlock(); } } } /** * Removes the item at the end of the path. * * @param impl * @param path * @throws RepositoryException */ public void remove(StoreTransaction tx, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); try { pi.lock.writeLock().lock(); pi.provider.remove( tx, path ); } finally { pi.lock.writeLock().unlock(); } } /** * Loads the state of a node from the repository. * * @param ws TODO * @param path * @return A brand new NodeImpl. * * @throws RepositoryException */ public NodeImpl loadNode( WorkspaceImpl ws, Path path ) throws RepositoryException { NodeImpl ni = null; Path ptPath = path.resolve( JCRConstants.Q_JCR_PRIMARYTYPE ); PropertyImpl primaryType = ws.createPropertyImpl( ptPath ); ValueContainer v = getPropertyValue( ws, ptPath ); if( v == null ) throw new RepositoryException("Repository did not return a primary type for path "+path); primaryType.loadValue( v.getValue() ); QName pt = ((QNameValue.Impl)v.getValue()).getQValue().getValue(); QNodeTypeManager ntm = QNodeTypeManager.getInstance(); QNodeType type = ntm.getNodeType( pt ); QNodeDefinition nd = type.findNodeDefinition( pt ); ni = ws.getSession().createNode( path, type, nd, false ); return ni; } /** * LOad the state of a single property from the repository. * * @param ws * @param ni * @param ptPath * @param name * @return * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private PropertyImpl loadProperty(WorkspaceImpl ws, NodeImpl ni, Path ptPath, QName name) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueContainer values = getPropertyValue( ws, ptPath ); PropertyImpl p = ws.createPropertyImpl( ptPath ); // // Find the proper property definition. // QPropertyDefinition pd = ni.getPrimaryQNodeType().findPropertyDefinition(name,values.isMultiple()); if( pd == null ) { for( NodeType mixin : ni.getMixinNodeTypes() ) { pd = ((QNodeType.Impl)mixin).getQNodeType().findPropertyDefinition( name, values.isMultiple() ); if( pd != null ) break; } if( pd == null ) throw new RepositoryException("Unable to locate property definition for nodetype "+ni.getPrimaryNodeType()+", name="+name); } p.setDefinition( pd.new Impl(ws.getSession()) ); // FIXME: Inoptimal if( values.isMultiple() ) p.loadValue( values.getValues(), values.getType() ); else p.loadValue( values.getValue() ); return p; } public void addNode(StoreTransaction tx, NodeImpl ni) throws RepositoryException { Path path = ni.getInternalPath(); if( !path.isRoot() && !itemExists(tx.getWorkspace(), path.getParentPath(), ItemType.NODE) ) throw new ConstraintViolationException("Parent path is missing for path "+path); ProviderInfo pi = getProviderInfo(tx.getWorkspace(),path); try { pi.lock.writeLock().lock(); pi.provider.addNode(tx, path, ni.getQDefinition()); } finally { pi.lock.writeLock().unlock(); } } public void copy(WorkspaceImpl m_workspace, Path srcpath, Path destpath) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } public NodeImpl findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); Path path = pi.provider.findByUUID(ws, uuid); return loadNode(ws, path); } catch(ItemNotFoundException e) {} finally { pi.lock.readLock().unlock(); } } throw new ItemNotFoundException("Could not locate a node by this UUID: "+uuid); } public ItemImpl getItem(WorkspaceImpl ws, Path path) throws InvalidPathException, RepositoryException { - try + // + // TODO: Not sure yet whether this optimization really makes sense. It appears to + // work slightly faster, since it does not incur the overhead of two loadNodes() + // + if( false ) { - NodeImpl ni = loadNode( ws, path ); + try + { + NodeImpl ni = loadNode( ws, path ); - return ni; + return ni; + } + catch( RepositoryException e ) + { + if( path.isRoot() ) throw e; // Otherwise we just get a relatively unclear "root has no parent" + + NodeImpl ni = loadNode( ws, path.getParentPath() ); + + return loadProperty( ws, ni, path, path.getLastComponent() ); + } } - catch( RepositoryException e ) + else { - if( path.isRoot() ) throw e; // Otherwise we just get a relatively unclear "root has no parent" - + + if( itemExists( ws, path, ItemType.NODE ) ) + { + return loadNode( ws, path ); + } + + if( path.isRoot() ) + throw new PathNotFoundException(); + NodeImpl ni = loadNode( ws, path.getParentPath() ); - + return loadProperty( ws, ni, path, path.getLastComponent() ); } } public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.itemExists(ws, path, type); } finally { pi.lock.readLock().unlock(); } } public void putProperty(StoreTransaction tx, Path path, ValueContainer value ) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); ValueContainer vc = value.deepClone(tx.getWorkspace().getSession()); try { pi.lock.writeLock().lock(); pi.provider.putPropertyValue( tx, path, vc ); } finally { pi.lock.writeLock().unlock(); } } public void stop() { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.stop(m_repository); } finally { pi.lock.writeLock().unlock(); } } } public Collection<? extends PropertyImpl> getReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { ArrayList<PropertyImpl> result = new ArrayList<PropertyImpl>(); List<Path> paths = new ArrayList<Path>(); for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); paths.addAll(pi.provider.findReferences( ws, uuid )); } finally { pi.lock.readLock().unlock(); } } for( Path path : paths ) { NodeImpl nd = loadNode( ws, path.getParentPath() ); result.add( nd.getProperty(ws.getSession().fromQName(path.getLastComponent())) ); } return result; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.listProperties(ws, path); } finally { pi.lock.readLock().unlock(); } } public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( ws.getName() ); try { pi.lock.writeLock().lock(); return pi.provider.storeStarted( ws ); } finally { pi.lock.writeLock().unlock(); } } public void storeFinished(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeFinished( tx ); } finally { pi.lock.writeLock().unlock(); } } public void storeCancelled(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeCancelled( tx ); } finally { pi.lock.writeLock().unlock(); } } /** * Stores information about a provider. */ private class ProviderInfo { public String[] workspaces; public RepositoryProvider provider; public ReadWriteLock lock; } /** * Returns the name of the default workspace. This is usually "default", but * it may change depending on how you configure Priha. * * @return */ public String getDefaultWorkspace() { return m_defaultWorkspaceName; } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.reorderNodes( tx, internalPath, childOrder ); } finally { pi.lock.writeLock().unlock(); } } }
jalkanen/Priha
fd5728c12115645bc27bca262bc3c07ec60596cc
Now avoids calling getParent() in enterState() if it's not needed.
diff --git a/src/java/org/priha/core/ItemImpl.java b/src/java/org/priha/core/ItemImpl.java index 3917abf..fe81c82 100644 --- a/src/java/org/priha/core/ItemImpl.java +++ b/src/java/org/priha/core/ItemImpl.java @@ -1,410 +1,419 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.PathRef; import org.priha.util.*; /** * Provides a basic implementation for Items. An Item stores a reference * to its Path, the Session, and keeps a record of its ItemState. Therefore * it's a fairly lightweight object. */ public abstract class ItemImpl implements Item { protected PathRef m_path; protected final SessionImpl m_session; protected boolean m_isNew; /** * Create an Item for a particular session and path. * * @param session Session which owns this Item * @param path Path at which the Item is created. */ public ItemImpl(SessionImpl session, Path path) { m_session = session; m_path = session.getPathManager().getPathRef(path); } /** * Returns the path reference object. * * @return The internal path reference. */ public PathRef getPathReference() { if( m_path == null ) throw new RuntimeException("Path reference must not be null!"); return m_path; } /** * Return the current state of this Item. * * @return An {@link ItemState} representing the state. */ public ItemState getState() { // // Check if the state exists in the change list. // ItemState state = ItemState.UNDEFINED; try { state = m_session.m_provider.getState( m_path ); } catch( PathNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } // If this object exists, but is not in the change list, then it's just // a simply existing object return state != null ? state : ItemState.EXISTS; } /** * Changes the {@link ItemState} of the Item, and places it in the appropriate * queues. * * @param state New state. * @throws RepositoryException If the state cannot be entered for some reason. */ @SuppressWarnings("fallthrough") public void enterState( ItemState state ) throws RepositoryException { ItemState oldState = getState(); SessionProvider sp = m_session.m_provider; switch( state ) { case EXISTS: break; case NEW: if( oldState == ItemState.NEW ) break; m_isNew = true; /* FALLTHROUGH OK */ case REMOVED: // FIXME: Slightly hacky, this. if( state == ItemState.REMOVED && oldState == ItemState.REMOVED ) break; case MOVED: // // Additions and removals also affect the parent. // sp.m_changedItems.add( state, this ); - if( !getInternalPath().isRoot() && !getParent().isModified() ) + Path path = getInternalPath(); + if( !path.isRoot() ) { - getParent().enterState(ItemState.UPDATED); + // + // We try to avoid calling getParent(), since it causes hits to the database. + // + Path parent = getInternalPath().getParentPath(); + + if( sp.getState(parent) == null ) + { + getParent().enterState(ItemState.UPDATED); + } } break; case UPDATED: if( oldState == ItemState.EXISTS || oldState == ItemState.UNDEFINED ) { // If we're already modified, no use repeating that information sp.m_changedItems.add( state, this ); } break; case UNDEFINED: default: throw new InvalidItemStateException("State cannot be set to UNDEFINED - that is the starting state of any Item only."); } } /** * {@inheritDoc} */ public void accept(ItemVisitor visitor) throws RepositoryException { if( isNode() ) { visitor.visit( (Node) this ); } else { visitor.visit( (Property) this ); } } /** * {@inheritDoc} */ public Item getAncestor(int depth) throws ItemNotFoundException, AccessDeniedException, RepositoryException { try { Path ancestorPath = getInternalPath().getAncestorPath(depth); return m_session.getItem(ancestorPath); } catch( InvalidPathException e ) { throw new ItemNotFoundException(e.getMessage()); } } /** * {@inheritDoc} */ public int getDepth() throws RepositoryException { return getInternalPath().depth(); } /** * {@inheritDoc} */ public String getName() throws RepositoryException { return m_session.fromQName( getInternalPath().getLastComponent() ); } /** * Returns the QName of this item. * * @return A QName. * @throws NamespaceException If the namespace cannot be parsed. * @throws RepositoryException If something else goes wrong. */ public QName getQName() throws NamespaceException, RepositoryException { QName qname = getInternalPath().getLastComponent(); return qname; } /** * {@inheritDoc} */ public NodeImpl getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException { try { Path parentPath = getInternalPath().getParentPath(); NodeImpl parent = (NodeImpl)m_session.getItem(parentPath); return parent; } catch( InvalidPathException e ) { throw new ItemNotFoundException(e.getMessage()); } } /** * Get the internal path representation for this Item. * * @return The internal Path. */ public Path getInternalPath() { try { return m_session.getPath( m_path ); } catch( PathNotFoundException e ) { throw new RuntimeException("Invalid path received: "+m_path,e); } } /** * {@inheritDoc} */ public String getPath() throws RepositoryException { return PathFactory.getMappedPath( m_session, getInternalPath() ); } /** * {@inheritDoc} */ public SessionImpl getSession() throws RepositoryException { return m_session; } /** * {@inheritDoc} */ public boolean isModified() { // // An Item is not modified, if it's, well, not modified or it's been recently // added (then it's NEW). // ItemState state = getState(); return state != ItemState.EXISTS && state != ItemState.NEW; } /** * {@inheritDoc} */ public boolean isNew() { return m_isNew || getState() == ItemState.UNDEFINED; } /** * {@inheritDoc} */ public boolean isNode() { return false; } /** * {@inheritDoc} */ public boolean isSame(Item otherItem) throws RepositoryException { if( m_session.getRepository() == otherItem.getSession().getRepository() ) { if( getPath().equals(otherItem.getPath()) ) { if( isNode() == otherItem.isNode() ) { if( isNode() ) { return true; } else if( getParent().getPath().equals(otherItem.getParent().getPath()) ) { return true; } } } } return false; } /** * {@inheritDoc} */ public void refresh(boolean keepChanges) throws InvalidItemStateException, RepositoryException { if( !m_session.itemExists(getInternalPath()) ) throw new InvalidItemStateException("You cannot refresh an Item which has been deleted!"); if( getState() == ItemState.REMOVED || getState() == ItemState.MOVED ) throw new InvalidItemStateException("Node has been removed"); m_session.refresh( keepChanges, getInternalPath() ); } /** * {@inheritDoc} */ public abstract void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException; /** * {@inheritDoc} */ public abstract void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException ; /** * Returns a human-readable description of the Item. * * @return Something readable. */ @Override public String toString() { try { return "Node["+m_session.getWorkspace().getName()+":"+getPath()+"]"; } catch( RepositoryException e ) { return "Node["+m_session.getWorkspace().getName()+":"+getInternalPath()+"]"; } } /** * {@inheritDoc} */ @Override public int hashCode() { return getInternalPath().hashCode()-17; } /** * Performs mandatory housekeeping right before saving. * @throws RepositoryException If something goes wrong */ protected void preSave() throws RepositoryException { if( getState() == ItemState.UNDEFINED ) { throw new IllegalStateException("Node "+getInternalPath()+" must not be in UNDEFINED state at this point (this is a bug in Priha, please report!)"); } } /** * Performs mandatory housekeeping after item state has been persisted to disk. * */ protected void postSave() { m_isNew = false; } private transient long m_creationTime = System.currentTimeMillis(); /** * Returns the creation time of this Item instance. * * @return The creation time. */ public long getCreationTime() { return m_creationTime; } }
jalkanen/Priha
6e11124c257f1f7c564bdc3a7c964c6e36d131b1
Initial implementation of Observation.
diff --git a/ChangeLog b/ChangeLog index ec11275..1fc45bc 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,519 @@ +2010-01-04 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.7.2 + + * Implemented Observation. It does not *quite* work yet, but + it's only nine errors until TCK pass. + 2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> * Fixed XML import tests for versioning by properly checking for checked-in Nodes in XMLImport. You may test Versioning, but the TCK tests are disabled. You can turn them on by editing Release.DESCRIPTORS and setting Repository.OPTION_VERSIONING_SUPPORTED to STR_TRUE. * 0.7.1 * FileProvider speedup - added internal cache for mangleName(). 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 2845b74..e4756ef 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ - public static final int MINORREVISION = 1; + public static final int MINORREVISION = 2; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, - Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, + Repository.OPTION_OBSERVATION_SUPPORTED, STR_TRUE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/SessionImpl.java b/src/java/org/priha/core/SessionImpl.java index 48c01d6..b4bf056 100644 --- a/src/java/org/priha/core/SessionImpl.java +++ b/src/java/org/priha/core/SessionImpl.java @@ -1,614 +1,621 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.AccessControlException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.QLock; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceMapper; import org.priha.core.values.ValueFactoryImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.PathManager; import org.priha.path.PathRef; import org.priha.path.Path.Component; import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.xml.*; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * The SessionImpl class implements a JCR Session. It is non thread safe, * so each Thread must have its own Session. */ public class SessionImpl implements Session, NamespaceMapper { static final String PRIHA_OLD_PATH = "priha:oldPath"; private static final String JCR_SYSTEM = "jcr:system"; /** * This is a magical property which gets added to a Node whenever * a move occurs. It's value is a Path which points from source to target * and target to source nodes which have been saved - it's point is * to make sure that the user will save both the source and the target * at the same time. This property is never saved to the Provider. */ static final String MOVE_CONSTRAINT = "priha:moveConstraint"; private RepositoryImpl m_repository; private WorkspaceImpl m_workspace; private List<String> m_lockTokens = new ArrayList<String>(); private SimpleCredentials m_credentials; private Logger log = Logger.getLogger( getClass().getName() ); private boolean m_isSuperSession = false; private ValueFactoryImpl m_valueFactory = new ValueFactoryImpl(this); + private String m_sessionId = UUID.randomUUID().toString(); + protected SessionProvider m_provider; public SessionImpl( RepositoryImpl rep, Credentials creds, String name ) throws RepositoryException { m_repository = rep; m_workspace = new WorkspaceImpl( this, name, rep.getProviderManager() ); m_provider = new SessionProvider( this, rep.getProviderManager() ); if( creds instanceof SimpleCredentials ) { m_credentials = (SimpleCredentials)creds; } if( !hasNode("/") ) { repopulate(); } } + public String getId() + { + return m_sessionId; + } + public boolean setSuper(boolean value) { boolean oldval = m_isSuperSession; m_isSuperSession = value; return oldval; } /** * Returns true, if this Session should be considered to be a supersession, * which can do whatever it wants (that is, mostly ignore any Constraint Violations. * <p> * One should be careful, since it is possible with this method to end up in * a repository with an inconsistent state. * * @return */ public boolean isSuper() { return m_isSuperSession; } public List<Path> listNodes( Path parentpath ) throws RepositoryException { return m_provider.listNodes(parentpath); } boolean hasNode( String absPath ) throws RepositoryException { return hasNode( PathFactory.getPath(this,absPath) ); } public boolean hasNode( Path absPath ) throws RepositoryException { checkLive(); return m_provider.itemExists( absPath, ItemType.NODE ); } boolean hasProperty( Path absPath ) throws RepositoryException { checkLive(); return m_provider.itemExists( absPath, ItemType.PROPERTY ); } public void addLockToken(String lt) { m_lockTokens.add(lt); } /** * Any credentials are fine to give full access. */ public void checkPermission(String absPath, String actions) throws AccessControlException, RepositoryException { checkLive(); actions = actions.trim(); if( actions.equals( "read" ) ) return; if( m_credentials == null && !isSuper() ) throw new AccessControlException("Read-only session"); return; } /** Quick way to check for write permissions. */ protected void checkWritePermission() throws AccessControlException, RepositoryException { try { checkPermission("/","add_node"); } catch( AccessControlException e ) { throw new AccessDeniedException(e.getMessage()); } } public Object getAttribute(String name) { Object res = null; if( m_credentials != null ) { res = m_credentials.getAttribute(name); } return res; } public String[] getAttributeNames() { if( m_credentials != null ) { return m_credentials.getAttributeNames(); } return new String[0]; } public ItemImpl getItem( Path absPath ) throws PathNotFoundException, RepositoryException { checkLive(); ItemImpl ii = m_provider.getItem( absPath ); return ii; } public ItemImpl getItem(String absPath) throws PathNotFoundException, RepositoryException { return getItem( PathFactory.getPath(this,absPath) ); } public String[] getLockTokens() { return m_lockTokens.toArray( new String[m_lockTokens.size()] ); } public NodeImpl getNodeByUUID(String uuid) throws ItemNotFoundException, RepositoryException { checkLive(); return m_provider.findByUUID(uuid); } public RepositoryImpl getRepository() { return m_repository; } public NodeImpl getRootNode() throws RepositoryException { return (NodeImpl) getItem(Path.ROOT); } public String getUserID() { return "anonymous"; } public ValueFactoryImpl getValueFactory() throws UnsupportedRepositoryOperationException, RepositoryException { checkLive(); return m_valueFactory; } public WorkspaceImpl getWorkspace() { return m_workspace; } public boolean hasPendingChanges() throws RepositoryException { checkLive(); return m_provider.hasPendingChanges(); } public Session impersonate(Credentials credentials) throws LoginException, RepositoryException { checkLive(); return m_repository.login( credentials, getWorkspace().getName() ); } public final boolean isLive() { return m_workspace != null; } private final void checkLive() throws RepositoryException { if( !isLive() ) throw new RepositoryException("This Session is no longer live and cannot be used."); } public boolean itemExists(String absPath) throws RepositoryException { checkLive(); return itemExists( PathFactory.getPath(this,absPath) ); } public void logout() { if( isLive() ) { m_repository.removeSession(this); LockManager.getInstance(m_workspace).expireSessionLocks( this ); m_workspace.logout(); m_workspace = null; } } /** * A convenience class to move stuff based on Paths instead of Strings. */ public void move( Path srcPath, Path destPath ) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, NamespaceException, RepositoryException { // FIXME: This should really be the main routine move( srcPath.toString( this ), destPath.toString(this) ); } public void move(String srcAbsPath, String destAbsPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { checkLive(); checkWritePermission(); internalMove(srcAbsPath,destAbsPath,true); } public void internalMove( Path srcPath, Path destPath, boolean obeyConstraints ) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, NamespaceException, RepositoryException { // FIXME: This should really be the main routine internalMove( srcPath.toString( this ), destPath.toString(this), obeyConstraints ); } /** * Moves work as follows: * <ol> * <li>We add a new Node to the destAbsPath * <li>We copy all properties from the old Node to the new Node * <li>The old Node gets tagged with a property "priha:oldPath" which contains the current path * <li>The Path of the old Node (and all other Nodes which refer to it) is changed to point at the new location * <li>The Node is marked as being MOVED instead of REMOVED. * </ol> */ public void internalMove(String srcAbsPath, String destAbsPath, boolean obeyConstraints) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); if( destAbsPath.endsWith("]") && !isSuper() ) throw new ConstraintViolationException("Destination path must not have an index as its final component."); boolean isSuper = setSuper( true ); try { Path path = PathFactory.getPath( this, destAbsPath ); if( m_workspace.isCheckedIn( (NodeImpl)getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( hasNode( path ) ) { throw new ItemExistsException("Destination node "+getWorkspace().getName()+":"+path.toString(this)+" already exists!"); } NodeImpl srcnode = getRootNode().getNode(srcAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( m_workspace ); if( lm.findLock( srcnode.getParent().getInternalPath() ) != null ) throw new LockException( "Lock on source path prevents move" ); QLock lock = lm.findLock( srcnode.getInternalPath() ); if( lock != null ) lm.moveLock( lock, PathFactory.getPath(newDestPath) ); NodeImpl destnode = getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); destnode.tag( PRIHA_OLD_PATH, srcnode.getPath() ); for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); String newPath = destAbsPath + "/" + relPath; System.out.println("Child path move "+child.getPath()+" => "+newPath ); internalMove( child.getPath(), newPath, obeyConstraints ); } for( PropertyIterator pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = (PropertyImpl)pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> "+newDestPath // ); // Primary type has already been set, so we won't move that. if( !p.getName().equals( "jcr:primaryType" ) ) { if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } p.remove(); } // Set up move constraints (that is, making sure the user can only save // a top node, and not just moved bits). if( obeyConstraints ) { srcnode.getParent().tag( MOVE_CONSTRAINT, destnode.getParent().getPath() ); destnode.getParent().tag( MOVE_CONSTRAINT, srcnode.getParent().getPath() ); } // Since this is a move op, we want to make sure that the old path // does not change. //srcnode.freezePath(); // Finally, remove the source node. //srcnode.remove(); srcnode.enterState( ItemState.MOVED ); // m_provider.remove( srcnode ); // FIXME: Make sure this is ok getPathManager().move( srcnode.getInternalPath(), destnode.getInternalPath() ); // FIXME: OK with new ChangeStore? } finally { setSuper( isSuper ); } } void refresh( boolean keepChanges, Path path ) throws RepositoryException { checkLive(); m_provider.refresh( keepChanges, path ); } public void refresh(boolean keepChanges) throws RepositoryException { refresh( keepChanges, Path.ROOT ); } /** * This method makes sure that certain default stuff is available. * @throws RepositoryException */ private void repopulate() throws RepositoryException { boolean isSuper = setSuper(true); if( !hasNode("/") ) { NodeImpl ni = null; log.info("Repository empty; setting up root node..."); QNodeType rootType = getWorkspace().getNodeTypeManager().getNodeType("nt:unstructured").getQNodeType(); QNodeDefinition nd = rootType.findNodeDefinition( QName.valueOf("*") ); ni = new NodeImpl( this, "/", rootType, nd, true ); ni.enterState( ItemState.NEW ); ni.addMixin( "mix:referenceable" ); // Make referenceable. //m_provider.addNode( ni ); ni.sanitize(); save(); } if( !hasNode("/"+JCR_SYSTEM) ) { getRootNode().addNode(JCR_SYSTEM, "nt:unstructured"); // FIXME: Should probably set up all sorts of things. save(); } setSuper(isSuper); } public void removeLockToken(String lt) { m_lockTokens.remove(lt); } public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { saveNodes( Path.ROOT ); } /** * Saves all modified nodes that start with the given path prefix. This * can be used to save a node and all its children. * * @param pathprefix * @throws RepositoryException */ protected void saveNodes( Path pathprefix ) throws RepositoryException { checkLive(); checkWritePermission(); m_provider.save( pathprefix ); } public boolean itemExists( Path absPath ) throws RepositoryException { return hasNode(absPath) || hasProperty(absPath); } public void remove(ItemImpl itemImpl) throws RepositoryException { checkLive(); checkWritePermission(); m_provider.remove( itemImpl ); } public List<PropertyImpl> getReferences(String uuid) throws RepositoryException { checkLive(); return m_provider.getReferences( uuid ); } /* ========================================================================= */ /* XML import/export */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, VersionException, InvalidSerializedDataException, LockException, RepositoryException { checkLive(); checkWritePermission(); XMLImport importer = new XMLImport( this, false, PathFactory.getPath(this,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { log.log( Level.WARNING, "Could not get SAX parser", e ); throw new RepositoryException("Could not get SAX parser, please check logs."); } catch (SAXException e) { log.log( Level.WARNING, "Importing failed", e ); if( e.getException() != null && e.getException() instanceof RepositoryException ) throw (RepositoryException) e.getException(); throw new InvalidSerializedDataException("Importing failed: "+e.getMessage()); } } public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, RepositoryException { XMLImport importer = new XMLImport( this, false, PathFactory.getPath(this,parentAbsPath), uuidBehavior ); return importer; } public void exportDocumentView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse) throws PathNotFoundException, SAXException, RepositoryException { checkLive(); XMLExport export = new XMLDocExport(this); export.export( absPath, contentHandler, skipBinary, noRecurse ); } public void exportDocumentView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse) throws IOException, PathNotFoundException, RepositoryException { checkLive(); XMLExport export = new XMLDocExport( this ); ContentHandler handler = new StreamContentHandler( out ); try { export.export( absPath, handler, skipBinary, noRecurse ); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void exportSystemView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse) throws PathNotFoundException, SAXException, RepositoryException { checkLive(); XMLExport export = new XMLSysExport( this ); export.export( absPath, contentHandler, skipBinary, noRecurse ); } public void exportSystemView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse) throws IOException, PathNotFoundException, RepositoryException { checkLive(); XMLExport export = new XMLSysExport( this ); ContentHandler handler = new StreamContentHandler( out ); try { export.export( absPath, handler, skipBinary, noRecurse ); } catch (SAXException e) { // TODO Auto-generated catch block diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index cd4358f..f731f86 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,844 +1,849 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.*; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); private static final int DEFAULT_CACHESIZE = 1000; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { // // It's faster to use a LinkedHashSet here, then copy to an ArrayList // when exiting. // Set<Path> res = new LinkedHashSet<Path>(); for( Change c : m_changedItems.getLatestChangesForParent(parentpath) ) { ItemImpl ni = c.getItem(); if( ni.isNode() ) { Path path = ni.getInternalPath(); if( !res.contains(path) && c.getState() != ItemState.REMOVED ) { res.add( path ); } } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } ArrayList<Path> ls = new ArrayList<Path>(res.size()); ls.addAll( res ); return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean itemExists(Path path, ItemType type) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && ((type == ItemType.NODE && c.getItem().isNode()) || (type == ItemType.PROPERTY && !c.getItem().isNode()) ) ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.itemExists(m_workspace, path, type); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; + List<Change> changesDone = new ArrayList<Change>(); try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.itemExists( m_workspace, change.getPath(), ItemType.NODE ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } - } + } + changesDone.add( change ); } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; + + m_workspace.getObservationManager().fireEvent( changesDone ); + } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends Path> listProperties(Path path) throws RepositoryException { LinkedHashSet<Path> result = new LinkedHashSet<Path>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.add( path.resolve(pName) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been added. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Change c : m_changedItems.getLatestChangesForParent(path) ) { ItemImpl ii = c.getItem(); if( ii.isNode() == false && (c.getState() != ItemState.REMOVED && c.getState() != ItemState.MOVED ) ) { Path p = ii.getInternalPath(); if( p.getParentPath().equals(path) ) { result.add( p ); } } } return result; } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.itemExists( m_workspace, path, ItemType.NODE ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { super(); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { super(); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { return c_sessionPathManager.getPath( p ); } public PathManager getPathManager() { return c_sessionPathManager; } public ItemState getState( PathRef m_path ) throws PathNotFoundException { Change c = m_changedItems.getLatestChange( getPath(m_path) ); return c != null ? c.getState() : null; } } diff --git a/src/java/org/priha/core/WorkspaceImpl.java b/src/java/org/priha/core/WorkspaceImpl.java index 69a9937..bb7299f 100644 --- a/src/java/org/priha/core/WorkspaceImpl.java +++ b/src/java/org/priha/core/WorkspaceImpl.java @@ -1,522 +1,522 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.UUID; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.observation.ObservationManager; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceRegistryImpl; +import org.priha.core.observation.ObservationManagerImpl; import org.priha.nodetype.QNodeTypeManager; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.query.PrihaQueryManager; import org.priha.util.LazyPropertyIteratorImpl; import org.priha.xml.XMLImport; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Implements a JCR Workspace. This class mostly functions as a facade for * ProviderManager, which takes care of the actual repository management. */ public class WorkspaceImpl implements Workspace { private SessionImpl m_session; private String m_name; private ProviderManager m_providerManager; private QNodeTypeManager.Impl m_nodeTypeManager; private Logger log = Logger.getLogger(WorkspaceImpl.class.getName()); /** * Create a new Workspace instance. * * @param session The SessionImpl to which this Workspace is tied to * @param name The name of the Workspace * @param mgr The ProviderManager instance which owns the repository. * @throws RepositoryException If a NodeTypeManager cannot be instantiated. */ public WorkspaceImpl( SessionImpl session, String name, ProviderManager mgr ) throws RepositoryException { m_session = session; m_name = name; m_providerManager = mgr; m_nodeTypeManager = QNodeTypeManager.getManager(this); } /** * Creates a new property implementation without a property definition. * This is meant for providers to create an "empty" property definition, * which the WorkspaceImpl will then update later on. * * @param path * @return * @throws RepositoryException */ public PropertyImpl createPropertyImpl( Path path ) throws RepositoryException { // String name = path.getLastComponent(); //NodeImpl nd = (NodeImpl) m_session.getItem(p); //PropertyDefinition pd = ((GenericNodeType)nd.getPrimaryNodeType()).findPropertyDefinition(name); PropertyImpl pi = new PropertyImpl( m_session, path, null ); return pi; } /** * If removeExisting is true, removes Nodes with conflicting UUIDs. If it's false, * this exists with a ItemExistsException. * * Does not save the Session. * * @param srcNode * @param removeExisting * @throws RepositoryException */ private void checkUUIDs( NodeImpl srcNode, boolean removeExisting ) throws RepositoryException { try { String uuid = srcNode.getUUID(); Node n = getSession().getNodeByUUID( uuid ); if( removeExisting ) { System.out.println("Removing node due to UUID conflict "+n); n.remove(); } else { throw new ItemExistsException("There already exists a Node by UUID "+uuid+" in the destination workspace! "+n.getPath()); } } catch( UnsupportedRepositoryOperationException e ) { // Fine, this node just does not have an UUID. } catch( ItemNotFoundException e ) { // Fine, expected as well. } for( NodeIterator ni = srcNode.getNodes(); ni.hasNext(); ) { checkUUIDs( (NodeImpl)ni.nextNode(), removeExisting ); } } /** * {@inheritDoc} */ public void clone(String srcWorkspace, String srcAbsPath, String destAbsPath, boolean removeExisting) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { checkLock(destAbsPath); getSession().checkWritePermission(); SessionImpl srcSession = getSession().getRepository().login(srcWorkspace); boolean isSuper = m_session.setSuper( true ); try { // // Do the check here, since once we're in super mode, addNode() will happily // allow adding to an indexed path. // if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot clone to a path which ends with an index."); if( removeExisting && getSession().itemExists( destAbsPath ) ) { // getSession().getItem( destAbsPath ).remove(); //getSession().save(); } checkUUIDs( (NodeImpl)srcSession.getItem( srcAbsPath ), removeExisting ); //getSession().save(); copy( srcSession, srcAbsPath, destAbsPath, true ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * {@inheritDoc} */ public void copy(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { copy( getName(), srcAbsPath, destAbsPath ); } /** * Throws a LockException if the given absolute path or any of its child nodes * is locked. */ private void checkLock( String abspath ) throws LockException, RepositoryException { LockManager lm = LockManager.getInstance( this ); if( lm.findLock( PathFactory.getPath( m_session, abspath ) ) != null ) throw new LockException("Destination path "+abspath+" is locked and cannot be modified."); } /** * {@inheritDoc} */ public void copy(String srcWorkspace, String srcAbsPath, String destAbsPath) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Destination path must not end with an index."); SessionImpl srcSession = getSession().getRepository().login( srcWorkspace ); // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); boolean isSuper = m_session.setSuper( true ); try { copy( srcSession, srcAbsPath, destAbsPath, false ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * Checks if the node or any of its parents are checked in. * * @param n * @return * @throws RepositoryException */ protected boolean isCheckedIn( NodeImpl n ) throws RepositoryException { if( !n.isCheckedOut() ) return true; if( n.getInternalPath().isRoot() ) return false; return isCheckedIn( n.getParent() ); } /** * Performs the actual copy, but does not save. * * @param srcSession * @param srcAbsPath * @param destAbsPath * @throws NoSuchWorkspaceException * @throws ConstraintViolationException * @throws VersionException * @throws AccessDeniedException * @throws PathNotFoundException * @throws ItemExistsException * @throws LockException * @throws RepositoryException */ protected void copy(SessionImpl srcSession, String srcAbsPath, String destAbsPath, boolean preserveUUIDs ) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { Path path = PathFactory.getPath( getSession(), destAbsPath ); if( isCheckedIn( (NodeImpl)m_session.getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( m_session.hasNode( destAbsPath ) ) { NodeImpl nx = getSession().getRootNode().getNode(destAbsPath); if( !nx.getDefinition().allowsSameNameSiblings() ) throw new ItemExistsException("Destination node "+destAbsPath+" already exists, and does not allow same name siblings!"); } NodeImpl srcnode = srcSession.getRootNode().getNode(srcAbsPath); // System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( srcSession.getWorkspace() ); if( lm.hasChildLock( srcnode.getInternalPath() ) ) throw new LockException( "Lock on source path prevents copy" ); NodeImpl destnode = m_session.getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); if( isCheckedIn( destnode ) ) { throw new VersionException("Destination node "+destnode.getPath()+" (or one of its parent nodes) is checked in, and therefore unmodifiable."); } for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); copy( srcSession, child.getPath(), destAbsPath + "/" + relPath, preserveUUIDs ); } for( LazyPropertyIteratorImpl pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> // "+newDestPath // ); // // The primary type is already set above upon the creation of the Node. // if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE )) continue; // // Section 7.1.7; the new node must get a new UUID when copying; // but we allow UUIDs to be preserved for e.g. clone. // if( p.getQName().equals( JCRConstants.Q_JCR_UUID) && !preserveUUIDs ) { destnode.setProperty( p.getName(), UUID.randomUUID().toString() ); } else { // // Copy the property // if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } } } /** * {@inheritDoc} */ public String[] getAccessibleWorkspaceNames() throws RepositoryException { Collection<String> list = m_providerManager.listWorkspaces(); return list.toArray(new String[0]); } /** * {@inheritDoc} */ // FIXME: SuperUserSession leaks. public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession,true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); return importer; } /** * {@inheritDoc} */ public String getName() { return m_name; } /** * {@inheritDoc} */ public NamespaceRegistryImpl getNamespaceRegistry() throws RepositoryException { return RepositoryImpl.getGlobalNamespaceRegistry(); } /** * {@inheritDoc} */ public QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_nodeTypeManager; } /** * Unsupported at the moment. */ - public ObservationManager getObservationManager() throws UnsupportedRepositoryOperationException, RepositoryException + public ObservationManagerImpl.Impl getObservationManager() throws UnsupportedRepositoryOperationException, RepositoryException { - throw new UnsupportedRepositoryOperationException("Workspace.getObservationManager()"); - // TODO Auto-generated method stub + return ObservationManagerImpl.getInstance(this); } /** * {@inheritDoc} */ public PrihaQueryManager getQueryManager() throws RepositoryException { return new PrihaQueryManager(getSession()); } /** * {@inheritDoc} */ public SessionImpl getSession() { return m_session; } /** * {@inheritDoc} */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, InvalidSerializedDataException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession, true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { throw new RepositoryException("Could not get SAX parser!",e); } catch (SAXException e) { if( e.getException() != null && (e.getException() instanceof RepositoryException) ) { throw (RepositoryException) e.getException(); } throw new InvalidSerializedDataException("Importing failed",e); } finally { suSession.logout(); } } /** * Implemented simply by starting a new Session, which then performs the copy, * and then calling save() on it. */ public void move(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot move to a path with an index in the name"); SessionImpl s = m_session.getRepository().superUserLogin( getName() ); try { s.move( srcAbsPath, destAbsPath ); s.save(); } finally { s.logout(); } } /** * Unsupported at the moment. */ public void restore(Version[] versions, boolean removeExisting) throws ItemExistsException, UnsupportedRepositoryOperationException, VersionException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Workspace.restore()"); } /** * Performs a logout; to be called by SessionImpl only. */ public void logout() { m_providerManager.close(this); } /** * Checks directly from the repository if an item exists. * * @param path * @return * @throws InvalidPathException */ public boolean nodeExists(Path path) throws RepositoryException { return m_providerManager.itemExists(this, path, ItemType.NODE); } } diff --git a/src/java/org/priha/core/observation/ObservationManagerImpl.java b/src/java/org/priha/core/observation/ObservationManagerImpl.java new file mode 100644 index 0000000..1fcadec --- /dev/null +++ b/src/java/org/priha/core/observation/ObservationManagerImpl.java @@ -0,0 +1,408 @@ +package org.priha.core.observation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Logger; + +import javax.jcr.AccessDeniedException; +import javax.jcr.ItemNotFoundException; +import javax.jcr.RepositoryException; +import javax.jcr.UnsupportedRepositoryOperationException; +import javax.jcr.observation.*; + +import org.priha.core.NodeImpl; +import org.priha.core.SessionImpl; +import org.priha.core.WorkspaceImpl; +import org.priha.path.Path; +import org.priha.path.PathFactory; +import org.priha.util.GenericIterator; +import org.priha.util.ChangeStore.Change; + +/** + * Implements an ObservationManager. Again, the actual implementation is a per-Session class instantiated + * at request. + * + */ +// FIXME: This class is not particularly optimized. +public class ObservationManagerImpl +{ + private static ObservationManagerImpl c_manager = new ObservationManagerImpl(); + + private ArrayList<EventListenerWrapper> m_listeners = new ArrayList<EventListenerWrapper>(); + + private Logger log = Logger.getLogger(ObservationManagerImpl.class.getName()); + + public void addEventListener(SessionImpl session, EventListener listener, int eventTypes, Path absPath, + boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal) + throws RepositoryException + { + EventListenerWrapper elw = new EventListenerWrapper(session,listener,eventTypes,absPath,isDeep,uuid,nodeTypeName,noLocal); + + m_listeners.add(elw); + } + + public EventListenerIterator getRegisteredEventListeners(SessionImpl session) throws RepositoryException + { + List<EventListener> list = new ArrayList<EventListener>(); + + for( Iterator<EventListenerWrapper> i = m_listeners.iterator() ; i.hasNext(); ) + { + EventListenerWrapper elw = i.next(); + if( elw.getSessionId().equals(session.getId()) ) + { + list.add( elw.getListener() ); + } + } + + return new Iter(list); + } + + public void removeEventListener(EventListener listener) throws RepositoryException + { + for( Iterator<EventListenerWrapper> i = m_listeners.iterator() ; i.hasNext(); ) + { + if( i.next().getListener() == listener ) + { + i.remove(); + return; + } + } + } + + public void fireEvent( SessionImpl srcSession, List<Change> changes ) + { + for( Iterator<EventListenerWrapper> i = m_listeners.iterator() ; i.hasNext(); ) + { + EventListenerWrapper elw = i.next(); + + // Fire the event + + try + { + elw.getListener().onEvent( new EventIteratorImpl(filterEvents(srcSession,elw,changes)) ); + } + catch( Exception e ) + { + log.warning("Unable to fire event "+ e.getMessage()); + } + } + } + + private List<Event> filterEvents( SessionImpl session, EventListenerWrapper elw, List<Change> changes ) throws ItemNotFoundException, AccessDeniedException, RepositoryException + { + ArrayList<Event> list = new ArrayList<Event>(); + + for( Change c : changes ) + { + System.out.println(c); + // Session filtering + if( elw.isNoLocal() && session.getId().equals(elw.getSessionId()) ) + { + continue; + } + + // Path filtering + if( elw.getAbsPath() != null ) + { + Path itemPath = c.getPath(); + Path ePath = elw.getAbsPath(); + + // + // This fairly complicated sentence fulfils the contract on page 272 of JCR-1.0 spec. + // + if( !(( (!itemPath.isRoot() && ePath.equals(itemPath.getParentPath())) && !elw.isDeep()) || + (ePath.isParentOf(itemPath) && elw.isDeep() )) ) + { + continue; + } + + } + + // UUID filtering + + if( elw.getUuids() != null ) + { + NodeImpl parent = c.getItem().getParent(); + + try + { + String parentUUID = parent.getUUID(); + + if( Arrays.binarySearch( elw.getUuids(), parentUUID ) < 0 ) + continue; + } + catch( UnsupportedRepositoryOperationException e ) {} + } + + // Nodetype filtering + + if( elw.getNodeTypeNames() != null ) + { + NodeImpl parent = c.getItem().getParent(); + + boolean success = false; + for( String s : elw.getNodeTypeNames() ) + { + if( parent.isNodeType(s) ) + { + success = true; + break; + } + } + + if( !success ) continue; + } + + // EventType filtering + int eventType = -1; + + switch( c.getState() ) + { + case NEW: + case MOVED: + if( c.getItem().isNode() ) + eventType = Event.NODE_ADDED; + else + eventType = Event.PROPERTY_ADDED; + break; + + case UPDATED: + if( !c.getItem().isNode() ) + eventType = Event.PROPERTY_CHANGED; + + break; + + case REMOVED: + if( c.getItem().isNode() ) + eventType = Event.NODE_REMOVED; + else + eventType = Event.PROPERTY_REMOVED; + + break; + + } + + if( (elw.getEventTypes() & eventType) == 0 ) + { + continue; + } + + // Add to the event list + + + if( eventType != -1 ) + { + Event e = new EventImpl(session, eventType, c.getPath()); + list.add( e ); + System.out.println("Firing "+e); + } + } + + return list; + } + + private static class EventIteratorImpl + extends GenericIterator + implements EventIterator + { + public EventIteratorImpl(List<Event> list) + { + super(list); + } + + public Event nextEvent() + { + return (Event) super.next(); + } + } + + private static class EventImpl implements Event + { + SessionImpl m_session; + int m_eventType; + Path m_path; + + public EventImpl(SessionImpl s, int eventType, Path path) + { + m_session = s; + m_eventType = eventType; + m_path = path; + } + + public String getPath() throws RepositoryException + { + return m_path.toString(m_session); + } + + public int getType() + { + return m_eventType; + } + + public String getUserID() + { + return m_session.getUserID(); + } + + public String toString() + { + return getEventString(m_eventType) + " " + m_path.toString(); + } + + private String getEventString(int type) + { + switch( type ) + { + case NODE_ADDED: + return "NODE_ADDED"; + + case NODE_REMOVED: + return "NODE_REMOVED"; + + case PROPERTY_ADDED: + return "PROPERTY_ADDED"; + + case PROPERTY_CHANGED: + return "PROPERTY_CHANGED"; + + case PROPERTY_REMOVED: + return "PROPERTY_REMOVED"; + + default: + return "UNKNOWN"; + } + } + } + + /** + * Provides iteration through EventListeners. + * + */ + private static class Iter extends GenericIterator implements EventListenerIterator + { + public Iter(List<EventListener> list) + { + super( list ); + } + + public EventListener nextEventListener() + { + return (EventListener)super.next(); + } + + public Object next() + { + return nextEventListener(); + } + } + + /** + * Wraps everything interesting for an EventListener. + */ + private static class EventListenerWrapper + { + private String m_sessionId; + private EventListener m_listener; + private int m_eventTypes; + private Path m_absPath; + private boolean m_isDeep; + private String[] m_uuids; + private String[] m_nodeTypeNames; + private boolean m_noLocal; + + public EventListenerWrapper( SessionImpl session, EventListener listener, int eventTypes, + Path absPath, boolean isDeep, String[] uuids, String[] nodeTypeNames, boolean noLocal ) + { + m_sessionId = session.getId(); + m_listener = listener; + m_eventTypes = eventTypes; + m_absPath = absPath; + m_isDeep = isDeep; + m_uuids = uuids; + m_nodeTypeNames = nodeTypeNames; + m_noLocal = noLocal; + + if( m_uuids != null ) Arrays.sort(m_uuids); + } + + public String getSessionId() + { + return m_sessionId; + } + public EventListener getListener() + { + return m_listener; + } + public int getEventTypes() + { + return m_eventTypes; + } + public Path getAbsPath() + { + return m_absPath; + } + public boolean isDeep() + { + return m_isDeep; + } + public String[] getUuids() + { + return m_uuids; + } + public String[] getNodeTypeNames() + { + return m_nodeTypeNames; + } + public boolean isNoLocal() + { + return m_noLocal; + } + } + + /** + * Session-local ObservationManager. + */ + public class Impl implements ObservationManager + { + SessionImpl m_session; + + public Impl(SessionImpl session) + { + m_session = session; + } + + public void addEventListener(EventListener listener, int eventTypes, String absPath, + boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal) + throws RepositoryException + { + ObservationManagerImpl.this.addEventListener(m_session, listener, eventTypes, + PathFactory.getPath(m_session, absPath), + isDeep, uuid, nodeTypeName, noLocal); + } + + public EventListenerIterator getRegisteredEventListeners() throws RepositoryException + { + return ObservationManagerImpl.this.getRegisteredEventListeners(m_session); + } + + public void removeEventListener(EventListener listener) throws RepositoryException + { + ObservationManagerImpl.this.removeEventListener(listener); + } + + public void fireEvent( List<Change> change ) + { + ObservationManagerImpl.this.fireEvent( m_session, change ); + } + } + + /** + * Get an instance for a Workspace. + */ + public static ObservationManagerImpl.Impl getInstance(WorkspaceImpl workspaceImpl) + { + return c_manager.new Impl(workspaceImpl.getSession()); + } +} diff --git a/src/java/org/priha/util/ChangeStore.java b/src/java/org/priha/util/ChangeStore.java index 5e06286..61b3920 100644 --- a/src/java/org/priha/util/ChangeStore.java +++ b/src/java/org/priha/util/ChangeStore.java @@ -1,437 +1,442 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.util.*; import org.priha.core.ItemImpl; import org.priha.core.ItemState; import org.priha.core.PropertyImpl; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.ValueContainer; /** * Provides a list of changes, which can be both played back * one by one, as well as searched rapidly. * <p> * Internally, this class stores both a List of Change objects, * as well as a HashMap pointing at the latest change. It can be * iterated both forwards (using peek() and remove() and iterator()) as well * as backwards (using values()). * <p> * In addition, it stores a separate reference to all the changes relating * to a particular parent path (making it fairly fast to filter based on a path). */ public class ChangeStore implements Iterable<ChangeStore.Change> { private ArrayList<Change> m_changes = new ArrayList<Change>(); private HashMap<Path,Change> m_latest = new HashMap<Path,Change>(); private HashMap<Path,List<Change>> m_childChanges = new HashMap<Path,List<Change>>(); /** * Create a ChangeStore without the HashMap. */ public ChangeStore() {} /** * Returns the newest ItemImpl that corresponds to the Path given. * * @param path Path to search for * @return Newest Item or null, if no such thing is found. */ public ItemImpl getLatestItem( Path path ) { Change c = getLatestChange( path ); if( c != null ) return c.getItem(); return null; } /** * Finds the latest change. * * @param path Path to search for * @return The Change or null, if no such thing found. */ public Change getLatestChange( Path path ) { Change c = m_latest.get( path ); return c; } /** * Get all the latest changes, ignoring any duplicate changes. * * @return A list of latest changes. */ public List<Change> getLatestChanges() { ArrayList<Change> changes = new ArrayList<Change>(); changes.addAll( m_latest.values() ); return changes; } /** * Returns a list of Changes filtered by a parent path. * * @param parent The path to filter against * @return A list of Changes. */ public List<Change> getLatestChangesForParent( Path parent ) { ArrayList<Change> changes = new ArrayList<Change>(); List<Change> c = m_childChanges.get(parent); if( c != null ) changes.addAll( c ); return changes; } /** * Adds a new Item with given ItemState to the end of the Change List. * * @param newState New state * @param ii The Item */ public void add( ItemState newState, ItemImpl ii ) { Change c = new Change( newState, ii ); add( c ); } /** * Adds a whole Change object at the end of the Change List. * * @param c The Change to add * @return True, at the moment. */ public boolean add( Change c ) { if( c.getState() == ItemState.UNDEFINED ) { dump(); throw new IllegalStateException("You cannot add an UNDEFINED Item "+c.getItem().getInternalPath()); } m_changes.add(c); m_latest.put( c.getPath(), c ); if( !c.getPath().isRoot() ) { try { List<Change> pc = m_childChanges.get( c.getPath().getParentPath() ); if( pc == null ) { pc = new ArrayList<Change>(); m_childChanges.put( c.getPath().getParentPath(), pc ); } pc.add( c ); } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot add path "+c.getPath()); } } return true; } /** * Gets the first change from the change list. Returns null, if there are no more * changes. * * @return The first change from the list, or null, if the list was empty. */ public Change peek() { if( m_changes.size() > 0 ) return m_changes.get(0); return null; } /** * Removes the first change from the change list. * * @return The first change from the list, or null, if the list was empty. */ public Change remove() { Change c = null; if( m_changes.size() > 0 ) { c = m_changes.remove(0); m_latest.remove( c.getPath() ); if( !c.getPath().isRoot() ) { try { Path parent = c.getPath().getParentPath(); List<Change> pc = m_childChanges.get( parent ); pc.remove( c ); // FIXME: SLow. if( pc.isEmpty() ) { m_childChanges.remove( parent ); } } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot remove "+c.getPath()); } } } return c; } /** * Clears the changes. * * @return The number of changes removed from the queue. */ public int clear() { int numChanges = m_changes.size(); m_changes.clear(); m_latest.clear(); m_childChanges.clear(); return numChanges; } /** * Returns a forward iterator for the Changes. * * @return A forward iterator for the Changes. */ public Iterator<Change> iterator() { return new ForwardIterator(); } /** * Returns a <b>backward</b> iterator for the Items in the change list. The first * value you get is the newest value on the stack. This means * that the iteration order for iterator() and values() is reversed. * * @return A reverse iterator for the values. */ public Iterator<ItemImpl> values() { return new ItemIterator(); } /** * Returns true, if there are no changes. * * @return True, if there are no changes. */ public final boolean isEmpty() { return m_changes.isEmpty(); } /** * Implements a backwards iterator through the Items in the list. */ private class ItemIterator implements Iterator<ItemImpl> { int m_position; protected ItemIterator() { m_position = m_changes.size()-1; } public final boolean hasNext() { return m_position > 0; } public final ItemImpl next() { return m_changes.get(m_position--).getItem(); } public void remove() { throw new UnsupportedOperationException(); } } private class ForwardIterator implements Iterator<Change> { int m_position; protected ForwardIterator() { m_position = 0; } public final boolean hasNext() { return m_position < m_changes.size(); } public final Change next() { return m_changes.get(m_position++); } public void remove() { if( m_position == 0 ) throw new IllegalStateException(); Change c = m_changes.remove( --m_position ); m_latest.remove( c.getPath() ); if( !c.getPath().isRoot() ) { try { Path parent = c.getPath().getParentPath(); List<Change> pc = m_childChanges.get( parent ); pc.remove( c ); // FIXME: SLow. if( pc.isEmpty() ) { m_childChanges.remove( parent ); } } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot remove "+c.getPath()); } } } } /** * Dumps the store contents for debugging to System.out. */ public void dump() { System.out.println("DUMP OF CHANGESTORE @"+Integer.toHexString(this.hashCode())); System.out.println(this); } /** * Outputs a human-readable description of the contents of the ChangeStore. * * @return Somethign human-readable. */ public String toString() { StringBuilder sb = new StringBuilder(); for( Change c : this ) { sb.append( c.getState().toString() + ": " + c.getPath() + ": " + c.getItem() + "\n" ); } return sb.toString(); } /** * Stores a single change. */ public static final class Change { private ItemState m_state; private ItemImpl m_item; private Path m_path; private ValueContainer m_valueContainer; /** * Create a new Change for the given ItemState and item. If the * Item is a property, also the Value is copied internally. * * @param newState The new state * @param item The item */ public Change( ItemState newState, ItemImpl item ) { m_state = newState; m_item = item; m_path = item.getInternalPath(); if( !item.isNode() ) { m_valueContainer = ((PropertyImpl)item).getValueContainer(); if( m_valueContainer.isEmpty() && newState != ItemState.REMOVED ) throw new IllegalArgumentException("Null value in valuecontainer for "+m_path); } } /** * Returns the Item for this Change. * * @return The Item. */ public final ItemImpl getItem() { return m_item; } /** * Returns the ItemState for this Change. * * @return The ItemState. */ public final ItemState getState() { return m_state; } /** * Returns the Path for this Change. * * @return The Path. */ public final Path getPath() { return m_path; } /** * Return the ValueContainer for the Change. * * @return The ValueContainer, or null, if the Change concerned a Node. */ public final ValueContainer getValue() { return m_valueContainer; } + + public String toString() + { + return m_state.toString()+" "+m_item.getInternalPath(); + } } } diff --git a/tests/etc/repositoryStubImpl.properties b/tests/etc/repositoryStubImpl.properties index c5c3822..16da182 100644 --- a/tests/etc/repositoryStubImpl.properties +++ b/tests/etc/repositoryStubImpl.properties @@ -1,140 +1,142 @@ javax.jcr.tck.repository_stub_impl=org.apache.jackrabbit.test.PrihaRepositoryStub testroot = /testroot javax.jcr.tck.testroot=/testroot javax.jcr.tck.nodename1=TestNode javax.jcr.tck.nodename2=TestNode2 javax.jcr.tck.nodename3=TestNode3 javax.jcr.tck.nodename4=TestNode4 javax.jcr.tck.propertyname1=aaa javax.jcr.tck.propertyname2=bbb javax.jcr.tck.propertyname3=ccc javax.jcr.tck.workspacename=testworkspace javax.jcr.tck.nodetype=nt:unstructured javax.jcr.tck.nodetypenochildren=nt:base javax.jcr.tck.versionableNodeType=nt:unstructured javax.jcr.tck.sameNameSibsTrueNodeType=nt:unstructured javax.jcr.tck.sameNameSibsFalseNodeType=test:sameNameSibsFalseChildNodeDefinition javax.jcr.tck.SessionTest.testSaveContstraintViolationException.nodetype2=nt:linkedFile javax.jcr.tck.NodeTest.testSaveContstraintViolationException.nodetype2=nt:linkedFile javax.jcr.tck.versionableNodeType=nt:unstructured javax.jcr.tck.propertyValue=Gobble # A nodetype with mandatory referenceability javax.jcr.tck.SetPropertyNodeTest.nodetype=priha:referenceable # A nodetype with a mandatory child node javax.jcr.tck.NodeTest.testRemoveMandatoryNode.nodetype2=nt:file # The child of the previous javax.jcr.tck.NodeTest.testRemoveMandatoryNode.nodetype3=nt:unstructured # The name of the previous javax.jcr.tck.NodeTest.testRemoveMandatoryNode.nodename3=jcr:content # Not allowing same name sibs javax.jcr.tck.NodeTest.testAddNodeItemExistsException.nodetype=test:sameNameSibsFalseChildNodeDefinition #javax.jcr.tck.NodeTest.nodetype=priha:referenceable # javax.jcr.tck.NodeUUIDTest.nodetype=priha:referenceable javax.jcr.tck.NodeUUIDTest.propertyname1=ref javax.jcr.tck.NodeUUIDTest.nodetype2=priha:referenceable # Configuration settings for the serialization. # Note that the serialization test tries to use as many features of the repository # as possible, but fails silently if a feature is not available. You have to # specify all of the following configuration entries, even if your repository does # not support the feature that is associated with them. # Root node for the example tree javax.jcr.tck.SerializationTest.testroot=/testdata/serialization # Node type to use for the example tree. Specify a node type that allows complex trees and all property types if possible javax.jcr.tck.SerializationTest.nodetype=nt:unstructured # Name of the nodes for source and target tree javax.jcr.tck.SerializationTest.sourceFolderName=source javax.jcr.tck.SerializationTest.targetFolderName=target javax.jcr.tck.SerializationTest.rootNodeName=test # List the properties whose values may change during serialization/deserialization. For example, # the UUID of a node is unique in the repository, so it will have to change when you re-import # a tree at a different location. javax.jcr.tck.SerializationTest.propertyValueMayChange= jcr:created jcr:uuid jcr:versionHistory jcr:baseVersion jcr:predecessors P_Reference # List all properties which are skipped during xml import according specification chapter 7.3.3 javax.jcr.tck.SerializationTest.propertySkipped=jcr:baseVersion # The name of the test node types. For easier diagnostics, the node types have names # that tell you the kind of information they store javax.jcr.tck.SerializationTest.nodeTypesTestNode=NodeTypes javax.jcr.tck.SerializationTest.mixinTypeTestNode=MixinTypes javax.jcr.tck.SerializationTest.propertyTypesTestNode=PropertyTypes javax.jcr.tck.SerializationTest.sameNameChildrenTestNode=SameNameChildren javax.jcr.tck.SerializationTest.multiValuePropertiesTestNode=MultiValueProperties javax.jcr.tck.SerializationTest.referenceableNodeTestNode=ReferenceableNode javax.jcr.tck.SerializationTest.orderChildrenTestNode=OrderChildren javax.jcr.tck.SerializationTest.namespaceTestNode=Namespace # The name of the test property types. javax.jcr.tck.SerializationTest.stringTestProperty=P_String javax.jcr.tck.SerializationTest.binaryTestProperty=P_Binary javax.jcr.tck.SerializationTest.dateTestProperty=P_Date javax.jcr.tck.SerializationTest.longTestProperty=P_Long javax.jcr.tck.SerializationTest.doubleTestProperty=P_Double javax.jcr.tck.SerializationTest.booleanTestProperty=P_Boolean javax.jcr.tck.SerializationTest.nameTestProperty=P_Name javax.jcr.tck.SerializationTest.pathTestProperty=P_Path javax.jcr.tck.SerializationTest.referenceTestProperty=P_Reference javax.jcr.tck.SerializationTest.multiValueTestProperty=P_MultiValue # node type not allowing same name sibs javax.jcr.tck.SerializationTest.sameNameSibsFalseChildNodeDefinition=test:sameNameSibsFalseChildNodeDefinition # Test method: testVersioningExceptionSessionFileChild # specified nodetype must be versionable and allow child nodes of the same type. javax.jcr.tck.SerializationTest.testVersioningExceptionSessionFileChild.nodetype=test:versionable # Test method: testVersioningExceptionSessionFileParent # specified nodetype must be versionable and allow child nodes of the same type. javax.jcr.tck.SerializationTest.testVersioningExceptionSessionFileParent.nodetype=test:versionable # Test method: testSessionImportXmlOverwriteException # requires a node type that does not allow same name siblings javax.jcr.tck.SerializationTest.testSessionImportXmlOverwriteException.nodetype=nt:folder # The name of the test node types. For easier diagnostics, the node types have names # that tell you the kind of information they store javax.jcr.tck.SerializationTest.nodeTypesTestNode=NodeTypes javax.jcr.tck.SerializationTest.mixinTypeTestNode=MixinTypes javax.jcr.tck.SerializationTest.propertyTypesTestNode=PropertyTypes javax.jcr.tck.SerializationTest.sameNameChildrenTestNode=SameNameChildren javax.jcr.tck.SerializationTest.multiValuePropertiesTestNode=MultiValueProperties javax.jcr.tck.SerializationTest.referenceableNodeTestNode=ReferenceableNode javax.jcr.tck.SerializationTest.orderChildrenTestNode=OrderChildren javax.jcr.tck.SerializationTest.namespaceTestNode=Namespace # Test class: ExportSysViewTest javax.jcr.tck.ExportSysViewTest.testroot=/testdata # Priha does not support orderable child nodes, so we give just a nodetype javax.jcr.tck.NodeOrderableChildNodesTest.nodetype2=priha:referenceable # XPathDocOrderTest javax.jcr.tck.XPathDocOrderTest.testroot=/querytest # XPathOrderByTest javax.jcr.tck.XPathOrderByTest.testroot=/querytest javax.jcr.tck.NodeOrderableChildNodesTest.nodetype2=nt:unstructured javax.jcr.tck.NodeOrderableChildNodesTest.nodetype3=nt:unstructured javax.jcr.tck.NodeOrderableChildNodesTest.testOrderBeforeUnsupportedRepositoryOperationException.nodetype2=nt:folder javax.jcr.tck.NodeOrderableChildNodesTest.testOrderBeforeUnsupportedRepositoryOperationException.nodetype3=nt:folder +# ObservationManager +javax.jcr.tck.AddEventListenerTest.nodetype2=nt:folder
jalkanen/Priha
38e73e329c911a01e0ca4d0c7e45f78538d64b6e
Just made configuration easier.
diff --git a/tests/java/org/priha/core/MultiThreadTest.java b/tests/java/org/priha/core/MultiThreadTest.java index 8155d3a..64a87ce 100644 --- a/tests/java/org/priha/core/MultiThreadTest.java +++ b/tests/java/org/priha/core/MultiThreadTest.java @@ -1,265 +1,267 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.Random; import java.util.Vector; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.VersionException; import junit.framework.TestCase; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.core.PerformanceTest.Perf; public class MultiThreadTest extends TestCase { private static final int NUM_THREADS = 10; + private static final int NUM_ITERS = 100; Vector<String> propertyPaths = new Vector<String>(); Vector<String> uuids = new Vector<String>(); public void testFileProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("filenocache.properties"); runRepoTest( rep, "File" ); } public void testEhFileProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("fileehcache.properties"); runRepoTest( rep, "FileEh" ); } public void testMemoryProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("memorynocache.properties"); runRepoTest( rep, "Memory" ); } public void testJdbcProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); runRepoTest( rep, "Jdbc" ); } public void testEhJdbcProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcehcache.properties"); runRepoTest( rep, "JdbcEh" ); } private void runRepoTest( RepositoryImpl rep, String prefix ) throws InterruptedException, LoginException, RepositoryException { try { TestThread[] threads = new TestThread[NUM_THREADS]; for( int i = 0; i < NUM_THREADS; i++ ) { threads[i] = new TestThread(rep); threads[i].setName( prefix+"-TestThread-"+i ); threads[i].start(); } boolean someonestillalive = true; while(someonestillalive) { someonestillalive = false; Thread.sleep( 1000 ); for( TestThread tt : threads ) { if( !tt.isAlive() ) { if( tt.m_result != null ) fail( tt.m_result ); } else { someonestillalive = true; } } System.out.print( "." ); System.out.flush(); } } finally { System.out.println("\nAll threads done, now emptying repository..."); TestUtil.emptyRepo( rep ); } } public class TestThread extends Thread { private Repository m_repo; private Session m_session; public String m_result = null; - private int m_numItems = 10; - + private int m_numItems = 20; + private int m_readIters = NUM_ITERS; + public TestThread( RepositoryImpl rep ) { m_repo = rep; } private void createRandomNodes() throws RepositoryException { Node nd = m_session.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("Save"); for( int i = 0; i < m_numItems; i++ ) { createRandomNode(nd); } m_session.save(); } private void createRandomNode(Node nd) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { String name = TestUtil.getUniqueID(16); String hash = "x-"+name.charAt(0); try { if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); n.addMixin("mix:referenceable"); Property p = n.setProperty( "test", TestUtil.getUniqueID(16) ); nd.save(); propertyPaths.add( p.getPath() ); uuids.add( n.getProperty("jcr:uuid").getString() ); } catch( RepositoryException e ) { // This is fine, since there should be some collisions } } public void readWriteRandomNodes() throws InterruptedException, RepositoryException { Random rand = new Random(); - for( int i = 0; i < 500; i++ ) + for( int i = 0; i < m_readIters; i++ ) { Thread.sleep( rand.nextInt(20) ); int item = rand.nextInt( propertyPaths.size() ); try { Item ii = m_session.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), 16, ((Property)ii).getString().length() ); if( rand.nextDouble() > 0.95 ) { createRandomNode( m_session.getRootNode() ); } } catch( PathNotFoundException e ) {} // OK } } public void readRandomNodes() throws InterruptedException, PathNotFoundException, RepositoryException { Random rand = new Random(); - for( int i = 0; i < 5000; i++ ) + for( int i = 0; i < m_readIters; i++ ) { //Thread.sleep( rand.nextInt(20) ); int item = rand.nextInt( propertyPaths.size() ); try { Item ii = m_session.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), 16, ((Property)ii).getString().length() ); } catch( PathNotFoundException e ) {} // OK } } public void run() { Random rnd = new Random(); try { Thread.sleep( rnd.nextInt( 1000 ) ); m_session = m_repo.login(new SimpleCredentials("xxx",new char[0])); createRandomNodes(); Thread.sleep( 500 ); readWriteRandomNodes(); //Thread.sleep( rnd.nextInt( 1000 ) ); readRandomNodes(); } catch( Throwable t ) { t.printStackTrace(); m_result = t.getMessage(); } finally { m_session.logout(); } System.out.println("TestThread "+getName()+" finished"); } } }
jalkanen/Priha
f46b90f6b333f969f38fe311ad722036a5534cbc
Fixed XML import tests for versioning by properly checking for checked-in Nodes in XMLImport.
diff --git a/ChangeLog b/ChangeLog index 92beb52..ec11275 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,514 +1,520 @@ 2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> + * Fixed XML import tests for versioning by properly checking for + checked-in Nodes in XMLImport. You may test Versioning, but + the TCK tests are disabled. You can turn them on by editing + Release.DESCRIPTORS and setting Repository.OPTION_VERSIONING_SUPPORTED + to STR_TRUE. + * 0.7.1 * FileProvider speedup - added internal cache for mangleName(). 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit diff --git a/README b/README index 178138a..24e6054 100644 --- a/README +++ b/README @@ -1,80 +1,76 @@ This is Priha, a JSR-170 Java Content Repository implementation. Unlike the all-singing, all-dancing, fully CRM-certified implementations, Priha is targeted at small applications, embedders and hobbyists, who like to have a simple repository model with as few external dependencies as possible. You can start off with Priha, and then just simply switch to a more efficient solution (like Jackrabbit) once you start to need the performance / reliability. The word "priha" is an ancient Finnish word and it roughly means a "young man". It is not in common use these days, except as an idiom "ylen sankia priha" ("a very chubby young man"). Which, if you ever were to use it correctly in the presence of a Finnish person, would probably get you a free beer and plenty of questions. - GOALS ===== The goals of the project are: * Provide a "good enough" implementation to ship with JSPWiki 3.0. * Optimize for fast fetching of medium-sized text objects (i.e. wikipages) * Good storage of large binaries (i.e. attachments) * Provide integrated versioning * Provide an SPI so that different types of providers can be used without hiding the JSR structure to something which cannot be understood by a mortal man. * Provide an SPI so powerful that JSPWiki can be easily migrated and keep the existing clarity of its Providers. * Scalability up to medium size systems (200 wikis, each with 2000 pages, total of 400,000 nodes). * Ships with as few external libraries as possible The anti-goals (i.e. the things I don't particularly want to pay attention to, because they are not useful (yet) in JSPWiki context) are: - * Class 1 or Class 2 compliancy. If we happen to pass the TCK, that's - great. But it will happen by accident. - * Transactions support * HA or clustering support. These should be left to an industrial-scale JSR implementation. * JNDI * Custom Nodetypes REQUIREMENTS ============ Priha requires and takes advantage of Java 5 (JDK 1.5). To compile and run the JCR tests you need the included libraries. To run Priha, you need: * a JAXP-compliant XML parser library somewhere in your classpath (the one with JDK5 is fine) * jcr-1.0.jar somewhere in the classpath as well That's it! See doc/Configuration.txt for further information about how Priha is configured. LICENSE ======= Priha is licensed under the Apache 2.0 license. Please see the LICENSE file in the same directory as this document. diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 8932ee5..0a6b595 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1341,1025 +1341,1025 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); } // FIXME: No rollback support public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { if( getState() == ItemState.NEW ) throw new InvalidItemStateException("Cannot call save on newly added node "+getInternalPath()); internalSave(); } public int compareTo(Node nd) { try { return getPath().compareTo(nd.getPath()); } catch( RepositoryException e ) { return 0; } // FIXME: This should never occur } public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { remove(false,true); } public void removeNodeOnly() throws VersionException, LockException, ConstraintViolationException, RepositoryException { remove(false,false); } /** * If isRemoving = true, will remove subnodes without question. */ private void remove(boolean isRemoving,boolean removeVersionHistory) throws VersionException, LockException, ConstraintViolationException, RepositoryException { if( getState() == ItemState.REMOVED ) { // System.out.println(getPath()+" has already been removed"); return; // Die nicely } Path path = getInternalPath(); if( !m_session.m_provider.nodeExistsInRepository( path ) && m_session.m_provider.m_changedItems.getLatestItem(path) == null ) { m_session.m_provider.m_changedItems.dump(); throw new InvalidItemStateException("Item has already been removed by another Session "+getPath()); } if( path.isRoot() || path.equals( JCRConstants.Q_JCR_SYSTEM_PATH ) ) { return; // Refuse to remove } NodeImpl parent = getParent(); NodeType parentType = parent.getPrimaryNodeType(); if( !getSession().isSuper() ) { // Anything from under /jcr:system cannot be deleted by the user if( JCRConstants.Q_JCR_SYSTEM_PATH.isParentOf( path )) return; if( getParent().isLockedWithoutToken() ) throw new LockException("The parent is locked, so you cannot remove it."); if( !parentType.canRemoveItem(getName()) && getParent().getState() != ItemState.REMOVED && !isRemoving ) { throw new ConstraintViolationException("Attempted to delete a mandatory child node:"+getInternalPath()); } } QLock li = m_lockManager.getLock( path ); if( li != null ) m_lockManager.removeLock( li ); // // Remove version history // if( removeVersionHistory && isNodeType( "mix:versionable" ) ) { // // Version histories cannot be removed unless you have a // superuser session. // boolean isSuper = m_session.setSuper(true); try { getVersionHistory().remove(); } catch( UnsupportedRepositoryOperationException e ) { // This may happen if you've just created a Node, then hit remove() on it immediately, since // in that case, we do not have an UUID yet. } finally { m_session.setSuper( isSuper ); } } // // Removal happens in a depth-first manner. // // // Remove children. We do this in a reverse order in order // not to force annoying moves for same-name siblings. It's just faster. // LazyNodeIteratorImpl ndi = (LazyNodeIteratorImpl) getNodes(); ndi.skip( ndi.getSize() ); while( ndi.hasPrevious() ) { NodeImpl nd = ndi.previousNode(); // System.out.println("REMOVING "+nd.getPath()); nd.remove(true,removeVersionHistory); } boolean isSuper = m_session.setSuper(true); // // Remove properties // for( PropertyIterator pit = getProperties(); pit.hasNext(); ) { pit.nextProperty().remove(); } // This is a hack which just resets the state and then adds this to the remove queue. FIXME! // m_state = ItemState.UPDATED; enterState( ItemState.REMOVED ); // // Fix same name siblings, but don't bother if the parent is already removed. // Again, we go for the super session. // try { int myIndex = getInternalPath().getLastComponent().getIndex(); if( !isRemoving ) { for( NodeIterator ni = getParent().getNodes( getName() ); ni.hasNext(); ) { NodeImpl n = (NodeImpl)ni.nextNode(); int siblingIndex = n.getInternalPath().getLastComponent().getIndex(); if( myIndex >= siblingIndex ) continue; Path destPath = new Path(n.getParent().getInternalPath(), new Path.Component(getQName(),siblingIndex-1) ); // System.out.println("Moving "+n+" to "+destPath); // m_session.m_provider.m_changedItems.dump(); getSession().move( n.getInternalPath().toString( m_session ), destPath.toString( m_session ) ); } } } finally { m_session.setSuper(isSuper); } log.finer("Removed "+getPath()); } /** * Locates a PropertyDefinition for the given property name from the array of * the mixintypes and the primary type for this Node. * * @param propertyName The QName of the property to look for * @param multiple Is this a multiproperty or a single property? * @return A valid PropertyDefinition, or null, if it cannot be located. * @throws RepositoryException If mixin node types cannot be determined. */ public QPropertyDefinition findPropertyDefinition(QName propertyName,boolean multiple) throws RepositoryException { QPropertyDefinition qp; // // Mixin types can override the primary type; especially since the // primary type can contain a wildcard. // for( NodeType nt : getMixinNodeTypes() ) { QNodeType qnt = ((QNodeType.Impl)nt).getQNodeType(); qp = qnt.findPropertyDefinition(propertyName, multiple); if( qp != null ) return qp; } return getPrimaryQNodeType().findPropertyDefinition(propertyName, multiple); } /** * Assumes nothing, goes through the properties, makes sure all things are correct. */ public void sanitize() throws RepositoryException { // log.finest("Sanitizing node "+getInternalPath()); if( m_definition == null ) { try { @SuppressWarnings("unused") PropertyImpl primarytype = getProperty( Q_JCR_PRIMARYTYPE ); } catch( Exception e ) { if( getInternalPath().isRoot() ) { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, "nt:unstructured", PropertyType.NAME ); pix.enterState(ItemState.NEW); } else { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, assignChildType( getInternalPath().getLastComponent() ).toString(), PropertyType.NAME ); pix.enterState(ItemState.NEW); } } if( getParent() != null ) { QNodeType mytype = getPrimaryQNodeType(); m_definition = getParent().getPrimaryQNodeType().findNodeDefinition( mytype.getQName() ); } else { // FIXME: Not correct m_definition = QNodeTypeManager.getInstance().findNodeDefinition( Q_NT_UNSTRUCTURED ); } if( m_definition == null ) { throw new RepositoryException("Cannot assign a node definition for "+getInternalPath()); } } // autoCreateProperties(); QNodeType mytype = getPrimaryQNodeType(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl pi = (PropertyImpl)i.next(); if( pi.getDefinition() == null ) { QPropertyDefinition pd = mytype.findPropertyDefinition( pi.getQName(), false ); // FIXME: Really? pi.m_definition = pd.new Impl(m_session); // FIXME: Inoptimal } } } /** * We consider nodes to be equal if they have the exact same path, and * all the properties are equal too. */ @Override public boolean equals(Object obj) { if( obj == this ) return true; if( obj instanceof NodeImpl ) { NodeImpl ni = (NodeImpl) obj; if( !ni.getInternalPath().equals(getInternalPath()) ) return false; if( !ni.m_session.getWorkspace().getName().equals(m_session.getWorkspace().getName()) ) return false; // All tests have succeeded return true; } return false; } @Override protected void preSave() throws RepositoryException { super.preSave(); } /** * Checks the mandatory properties for this Nodetype and throws a ConstraintViolationException * if it's not existing. * * @param nt * @throws RepositoryException */ void checkMandatoryProperties(QNodeType nt) throws RepositoryException { for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isMandatory() && !hasProperty(pd.getQName()) ) { throw new ConstraintViolationException("Node "+getInternalPath()+" is missing property "+pd.getQName()); } } } /* ============================================================ * * Mixins * */ public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { ValueFactory vf = m_session.getValueFactory(); NodeType mixin = getNodeTypeManager().getNodeType(mixinName); if( !mixin.isMixin() ) throw new NoSuchNodeTypeException("Type "+mixinName+" is not a mixin type!"); if( isLockedWithoutToken() ) throw new LockException( "Node is locked, so cannot add new mixin types." ); if( !isCheckedOut() ) throw new VersionException( "Node is not checked out, so cannot add new mixin types."); boolean oldsuper = m_session.setSuper( true ); try { Property p; p = getProperty(Q_JCR_MIXINTYPES); Value[] v = p.getValues(); Value[] newval = new Value[v.length+1]; for( int i = 0; i < v.length; i++ ) { newval[i] = v[i]; } newval[newval.length-1] = vf.createValue(mixinName,PropertyType.NAME); PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, newval, PropertyType.NAME ); pi.enterState(ItemState.UPDATED); } catch( PathNotFoundException e ) { Value[] values = new Value[] { vf.createValue(mixinName,PropertyType.NAME) }; PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, values, PropertyType.NAME ); pi.enterState(ItemState.NEW); } finally { m_session.setSuper( oldsuper ); } //autoCreateProperties(); } public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException { if( isLocked() ) return false; NodeType nt = getNodeTypeManager().getNodeType( mixinName ); if( !nt.isMixin() ) { throw new NoSuchNodeTypeException(mixinName+" is not a mixin type!"); } if( hasMixinType(nt.getName()) ) { return false; } if( !isCheckedOut() ) return false; // FIXME: This is a bit complicated and slow. if( mixinName.equals("mix:versionable") && m_session.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false") ) return false; return true; } - boolean hasMixinType(String mixinType) + public boolean hasMixinType(String mixinType) { try { Property pi = getProperty( Q_JCR_MIXINTYPES ); for( Value v : pi.getValues() ) { String mixin = v.getString(); if( mixin.equals(mixinType) ) return true; } } catch( RepositoryException e ) {} return false; } public NodeType[] getMixinNodeTypes() throws RepositoryException { ArrayList<NodeType> mixinTypes = new ArrayList<NodeType>(); // // If there are no mixin types, then let's just return an empty array. // try { Property p = getProperty( Q_JCR_MIXINTYPES ); for( Value v : p.getValues() ) { NodeType nt = m_session.getWorkspace().getNodeTypeManager().getNodeType( v.getString() ); mixinTypes.add( nt ); } } catch( RepositoryException e ) {} return mixinTypes.toArray( new NodeType[0] ); } public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( isLocked() ) throw new LockException("Node locked, cannot remove mixin"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); Property mixinTypes = getProperty("jcr:mixinTypes"); Value[] vals = mixinTypes.getValues(); boolean found = false; for( int i = 0; i < vals.length; i++ ) { if( vals[i].getString().equals(mixinName) ) { vals[i] = null; found = true; } } if( found ) { mixinTypes.setValue( vals ); } else { throw new NoSuchNodeTypeException("No such mixin type to remove: "+mixinName); } } /*============================================================================== * * Locking * */ LockManager m_lockManager = LockManager.getInstance(getSession().getWorkspace()); public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { if( !hasMixinType("mix:lockable") ) throw new UnsupportedRepositoryOperationException("This node is not lockable: "+getInternalPath()); if( getState() == ItemState.NEW ) throw new LockException("This node has no persistent state"); if( isModified() ) throw new InvalidItemStateException("You may only lock Nodes which are not currently modified"); if( isDeep && m_lockManager.hasChildLock(getInternalPath()) ) { throw new LockException("A child of this node already holds a lock, so you cannot deep lock this node."); } if( isLocked() ) { throw new LockException("This Node is already locked."); } QLock lock = new QLock( this, isDeep, isSessionScoped ); m_session.addLockToken( lock.getToken() ); boolean isSuper = m_session.setSuper(true); try { setProperty("jcr:lockOwner", lock.getLockOwner()); setProperty("jcr:lockIsDeep", isDeep); } finally { m_session.setSuper(isSuper); } save(); m_lockManager.addLock( lock ); return lock.getLockInstance(m_session); } public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { QLock lock = m_lockManager.getLock( getInternalPath() ); if( lock == null ) throw new LockException("This Node has not been locked."); if( lock.getLockToken(m_session) == null ) throw new LockException("This Session does not own this Lock, so it cannot be unlocked."); if( isModified() ) throw new InvalidItemStateException("This Node must not be modified prior to unlocking"); Property p = getProperty("jcr:lockOwner"); p.remove(); p = getProperty("jcr:lockIsDeep"); p.remove(); m_session.removeLockToken( lock.getLockToken(m_session) ); m_lockManager.removeLock( lock ); lock.invalidate(); save(); } public QLock.Impl getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); // // Must return a clone of the Lock which is particular to this session. // if( li != null ) return li.getLockInstance(m_session); return null; } public boolean holdsLock() throws RepositoryException { QLock li = m_lockManager.getLock( getInternalPath() ); return li != null; } public boolean isLocked() throws RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); return li != null; } /** * Returns true, if this Node is locked (that is, it or it's parents are locked) * but the Session which owns this Session does not hold a token to modify it. * * @return True, if you cannot modify this Node due to missing token. */ protected boolean isLockedWithoutToken() { if( !getInternalPath().isRoot() ) { QLock li = m_lockManager.findLock(getInternalPath()); if( li != null && li.getLockToken(m_session) == null ) { return true; } } return false; } /* ==================================================== * * Versioning * */ public boolean isCheckedOut() throws RepositoryException { try { PropertyImpl p = getProperty(Q_JCR_ISCHECKEDOUT); return p.getBoolean(); } catch(PathNotFoundException e) { // Fine; no property exists. } // // Check if this is a versionable node in the first place. // if( isNodeType( "mix:versionable" ) && !isNew() ) return false; return true; } public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.cancelMerge()"); } public VersionImpl checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException { if( !hasMixinType("mix:versionable") ) { throw new UnsupportedRepositoryOperationException("Node is not mix:versionable (8.2.5)"); } if( !isCheckedOut() ) { return getBaseVersion(); } if( isModified() ) { throw new InvalidItemStateException("Node has unsaved changes (8.2.5)"); } if( hasProperty("jcr:mergeFailed") ) { throw new VersionException("Node has failed merges (8.2.5)"); } // // Phew! Preconditions have been checked. Now, let's get to real business. // boolean isSuper = getSession().setSuper(true); try { VersionHistoryImpl vh = getVersionHistory(); int version = 0; try { if( !getBaseVersion().getName().equals("jcr:rootVersion") ) version = Integer.parseInt( getBaseVersion().getName() ); } catch( ItemNotFoundException e ) {} // There's not yet a base version. VersionImpl v = (VersionImpl) vh.addNode( Integer.toString( ++version ), "nt:version" ); if(!hasProperty("nt:versionHistory")) setProperty( "nt:versionHistory", vh ); // // Set up version properties // v.setProperty( JCR_PREDECESSORS, getProperty(JCR_PREDECESSORS).getValues() ); v.setProperty( "jcr:uuid", UUID.randomUUID().toString() ); v.setProperty( JCR_SUCCESSORS, new Value[0], PropertyType.REFERENCE ); setProperty( JCR_PREDECESSORS, new Value[0], PropertyType.REFERENCE ); PropertyImpl preds = v.getProperty(JCR_PREDECESSORS); // // Set up successors and predecessors // for( Value val : preds.getValues() ) { String uuid = val.getString(); Node pred = m_session.getNodeByUUID(uuid); Value[] s = pred.getProperty( JCR_SUCCESSORS ).getValues(); List<Value> successorList = new ArrayList<Value>(); successorList.addAll( Arrays.asList(s) ); successorList.add( m_session.getValueFactory().createValue(v) ); pred.setProperty( JCR_SUCCESSORS, successorList.toArray(s) ); } setProperty( "jcr:baseVersion", v ); setProperty( "jcr:isCheckedOut", false ); // // Store the contents into the frozen node of the Version node. // NodeImpl fn = v.addNode(JCR_FROZENNODE,"nt:frozenNode"); for( LazyPropertyIteratorImpl pi = getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE ) ) { fn.setProperty( "jcr:frozenPrimaryType", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_UUID ) ) { fn.setProperty( JCR_FROZENUUID, p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_MIXINTYPES ) ) { fn.setProperty( "jcr:frozenMixinTypes", p.getValues() ); } else if( p.getDefinition().getOnParentVersion() == OnParentVersionAction.COPY ) { // FIXME: SHould probably deal with the others as well. if( p.getDefinition().isMultiple() ) { fn.setProperty( p.getName(), p.getValues() ); } else { fn.setProperty( p.getName(), p.getValue() ); } } } for( NodeIterator ni = getNodes(); ni.hasNext(); ) { NodeImpl n = (NodeImpl)ni.nextNode(); switch( n.getDefinition().getOnParentVersion() ) { case OnParentVersionAction.ABORT: throw new VersionException("Child node "+n.getPath()+" prevented versioning, as it has OnParentVersionAction ABORT"); case OnParentVersionAction.COMPUTE: throw new RepositoryException("COMPUTE child nodes not supported for path "+getPath()); case OnParentVersionAction.COPY: m_session.getWorkspace().copy(m_session, n.getPath(), fn.getPath(), false); break; case OnParentVersionAction.IGNORE: // Ignore, yay break; case OnParentVersionAction.INITIALIZE: throw new RepositoryException("INITIALIZE child nodes not supported for path "+getPath()); case OnParentVersionAction.VERSION: if( n.hasMixinType("mix:versionable") ) { NodeImpl vc = fn.addNode( n.getName(), "nt:versionedChild" ); vc.setProperty("jcr:childVersionHistory", n.getVersionHistory()); } else { // FIXME: Does not stop at versionable nodes m_session.getWorkspace().copy(m_session, n.getPath(), fn.getPath()+"/"+n.getName(), true); } break; } } vh.save(); save(); // FIXME: Here. return v; } finally { getSession().setSuper( isSuper ); } } public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException { if( !isNodeType( "mix:versionable" ) ) throw new UnsupportedRepositoryOperationException("Not versionable (8.2.6)"); if( isCheckedOut() ) return; // Nothing happens boolean isSuper = getSession().setSuper( true ); try { setProperty( "jcr:isCheckedOut", true ); // // We don't support multiple predecessors, so this is okay, I think. // setProperty( JCR_PREDECESSORS, new ValueImpl[] { getSession().getValueFactory().createValue( getBaseVersion() ) } ); setProperty( JCR_SUCCESSORS, new ValueImpl[0] ); // // Persist immediately. // save(); } finally { getSession().setSuper( isSuper ); } } public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.doneMerge()"); } public VersionImpl getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException { try { String bvUuid = getProperty( Q_JCR_BASEVERSION ).getString(); return (VersionImpl) getSession().getNodeByUUID( bvUuid ); } catch( PathNotFoundException e ) { throw new UnsupportedRepositoryOperationException("This is not a versioned node."); } } public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { Version v = getVersionHistory().getVersion(versionName); restore( v, removeExisting ); } public void restore(Version version, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException { restore( version, null, removeExisting ); } public void restore(Version version, String relPath, boolean removeExisting) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException diff --git a/src/java/org/priha/core/WorkspaceImpl.java b/src/java/org/priha/core/WorkspaceImpl.java index ee1182c..69a9937 100644 --- a/src/java/org/priha/core/WorkspaceImpl.java +++ b/src/java/org/priha/core/WorkspaceImpl.java @@ -1,521 +1,522 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.UUID; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.observation.ObservationManager; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceRegistryImpl; import org.priha.nodetype.QNodeTypeManager; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.query.PrihaQueryManager; import org.priha.util.LazyPropertyIteratorImpl; import org.priha.xml.XMLImport; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Implements a JCR Workspace. This class mostly functions as a facade for * ProviderManager, which takes care of the actual repository management. */ public class WorkspaceImpl implements Workspace { private SessionImpl m_session; private String m_name; private ProviderManager m_providerManager; private QNodeTypeManager.Impl m_nodeTypeManager; private Logger log = Logger.getLogger(WorkspaceImpl.class.getName()); /** * Create a new Workspace instance. * * @param session The SessionImpl to which this Workspace is tied to * @param name The name of the Workspace * @param mgr The ProviderManager instance which owns the repository. * @throws RepositoryException If a NodeTypeManager cannot be instantiated. */ public WorkspaceImpl( SessionImpl session, String name, ProviderManager mgr ) throws RepositoryException { m_session = session; m_name = name; m_providerManager = mgr; m_nodeTypeManager = QNodeTypeManager.getManager(this); } /** * Creates a new property implementation without a property definition. * This is meant for providers to create an "empty" property definition, * which the WorkspaceImpl will then update later on. * * @param path * @return * @throws RepositoryException */ public PropertyImpl createPropertyImpl( Path path ) throws RepositoryException { // String name = path.getLastComponent(); //NodeImpl nd = (NodeImpl) m_session.getItem(p); //PropertyDefinition pd = ((GenericNodeType)nd.getPrimaryNodeType()).findPropertyDefinition(name); PropertyImpl pi = new PropertyImpl( m_session, path, null ); return pi; } /** * If removeExisting is true, removes Nodes with conflicting UUIDs. If it's false, * this exists with a ItemExistsException. * * Does not save the Session. * * @param srcNode * @param removeExisting * @throws RepositoryException */ private void checkUUIDs( NodeImpl srcNode, boolean removeExisting ) throws RepositoryException { try { String uuid = srcNode.getUUID(); Node n = getSession().getNodeByUUID( uuid ); if( removeExisting ) { System.out.println("Removing node due to UUID conflict "+n); n.remove(); } else { throw new ItemExistsException("There already exists a Node by UUID "+uuid+" in the destination workspace! "+n.getPath()); } } catch( UnsupportedRepositoryOperationException e ) { // Fine, this node just does not have an UUID. } catch( ItemNotFoundException e ) { // Fine, expected as well. } for( NodeIterator ni = srcNode.getNodes(); ni.hasNext(); ) { checkUUIDs( (NodeImpl)ni.nextNode(), removeExisting ); } } /** * {@inheritDoc} */ public void clone(String srcWorkspace, String srcAbsPath, String destAbsPath, boolean removeExisting) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { checkLock(destAbsPath); getSession().checkWritePermission(); SessionImpl srcSession = getSession().getRepository().login(srcWorkspace); boolean isSuper = m_session.setSuper( true ); try { // // Do the check here, since once we're in super mode, addNode() will happily // allow adding to an indexed path. // if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot clone to a path which ends with an index."); if( removeExisting && getSession().itemExists( destAbsPath ) ) { // getSession().getItem( destAbsPath ).remove(); //getSession().save(); } checkUUIDs( (NodeImpl)srcSession.getItem( srcAbsPath ), removeExisting ); //getSession().save(); copy( srcSession, srcAbsPath, destAbsPath, true ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * {@inheritDoc} */ public void copy(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { copy( getName(), srcAbsPath, destAbsPath ); } /** * Throws a LockException if the given absolute path or any of its child nodes * is locked. */ private void checkLock( String abspath ) throws LockException, RepositoryException { LockManager lm = LockManager.getInstance( this ); if( lm.findLock( PathFactory.getPath( m_session, abspath ) ) != null ) throw new LockException("Destination path "+abspath+" is locked and cannot be modified."); } /** * {@inheritDoc} */ public void copy(String srcWorkspace, String srcAbsPath, String destAbsPath) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Destination path must not end with an index."); SessionImpl srcSession = getSession().getRepository().login( srcWorkspace ); // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); boolean isSuper = m_session.setSuper( true ); try { copy( srcSession, srcAbsPath, destAbsPath, false ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * Checks if the node or any of its parents are checked in. * * @param n * @return * @throws RepositoryException */ protected boolean isCheckedIn( NodeImpl n ) throws RepositoryException { if( !n.isCheckedOut() ) return true; if( n.getInternalPath().isRoot() ) return false; return isCheckedIn( n.getParent() ); } /** * Performs the actual copy, but does not save. * * @param srcSession * @param srcAbsPath * @param destAbsPath * @throws NoSuchWorkspaceException * @throws ConstraintViolationException * @throws VersionException * @throws AccessDeniedException * @throws PathNotFoundException * @throws ItemExistsException * @throws LockException * @throws RepositoryException */ protected void copy(SessionImpl srcSession, String srcAbsPath, String destAbsPath, boolean preserveUUIDs ) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { Path path = PathFactory.getPath( getSession(), destAbsPath ); if( isCheckedIn( (NodeImpl)m_session.getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( m_session.hasNode( destAbsPath ) ) { NodeImpl nx = getSession().getRootNode().getNode(destAbsPath); if( !nx.getDefinition().allowsSameNameSiblings() ) throw new ItemExistsException("Destination node "+destAbsPath+" already exists, and does not allow same name siblings!"); } NodeImpl srcnode = srcSession.getRootNode().getNode(srcAbsPath); // System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( srcSession.getWorkspace() ); if( lm.hasChildLock( srcnode.getInternalPath() ) ) throw new LockException( "Lock on source path prevents copy" ); NodeImpl destnode = m_session.getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); if( isCheckedIn( destnode ) ) { throw new VersionException("Destination node "+destnode.getPath()+" (or one of its parent nodes) is checked in, and therefore unmodifiable."); } for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); copy( srcSession, child.getPath(), destAbsPath + "/" + relPath, preserveUUIDs ); } for( LazyPropertyIteratorImpl pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> // "+newDestPath // ); // // The primary type is already set above upon the creation of the Node. // if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE )) continue; // // Section 7.1.7; the new node must get a new UUID when copying; // but we allow UUIDs to be preserved for e.g. clone. // if( p.getQName().equals( JCRConstants.Q_JCR_UUID) && !preserveUUIDs ) { destnode.setProperty( p.getName(), UUID.randomUUID().toString() ); } else { // // Copy the property // if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } } } /** * {@inheritDoc} */ public String[] getAccessibleWorkspaceNames() throws RepositoryException { Collection<String> list = m_providerManager.listWorkspaces(); return list.toArray(new String[0]); } /** * {@inheritDoc} */ // FIXME: SuperUserSession leaks. public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession,true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); return importer; } /** * {@inheritDoc} */ public String getName() { return m_name; } /** * {@inheritDoc} */ public NamespaceRegistryImpl getNamespaceRegistry() throws RepositoryException { return RepositoryImpl.getGlobalNamespaceRegistry(); } /** * {@inheritDoc} */ public QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_nodeTypeManager; } /** * Unsupported at the moment. */ public ObservationManager getObservationManager() throws UnsupportedRepositoryOperationException, RepositoryException { throw new UnsupportedRepositoryOperationException("Workspace.getObservationManager()"); // TODO Auto-generated method stub } /** * {@inheritDoc} */ public PrihaQueryManager getQueryManager() throws RepositoryException { return new PrihaQueryManager(getSession()); } /** * {@inheritDoc} */ public SessionImpl getSession() { return m_session; } /** * {@inheritDoc} */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, InvalidSerializedDataException, LockException, AccessDeniedException, RepositoryException { + SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession, true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { throw new RepositoryException("Could not get SAX parser!",e); } catch (SAXException e) { if( e.getException() != null && (e.getException() instanceof RepositoryException) ) { throw (RepositoryException) e.getException(); } throw new InvalidSerializedDataException("Importing failed",e); } finally { suSession.logout(); } } /** * Implemented simply by starting a new Session, which then performs the copy, * and then calling save() on it. */ public void move(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot move to a path with an index in the name"); SessionImpl s = m_session.getRepository().superUserLogin( getName() ); try { s.move( srcAbsPath, destAbsPath ); s.save(); } finally { s.logout(); } } /** * Unsupported at the moment. */ public void restore(Version[] versions, boolean removeExisting) throws ItemExistsException, UnsupportedRepositoryOperationException, VersionException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Workspace.restore()"); } /** * Performs a logout; to be called by SessionImpl only. */ public void logout() { m_providerManager.close(this); } /** * Checks directly from the repository if an item exists. * * @param path * @return * @throws InvalidPathException */ public boolean nodeExists(Path path) throws RepositoryException { return m_providerManager.itemExists(this, path, ItemType.NODE); } } diff --git a/src/java/org/priha/xml/XMLImport.java b/src/java/org/priha/xml/XMLImport.java index 4a0b8d1..4a51b83 100644 --- a/src/java/org/priha/xml/XMLImport.java +++ b/src/java/org/priha/xml/XMLImport.java @@ -1,585 +1,609 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.priha.core.JCRConstants; import org.priha.core.NodeImpl; import org.priha.core.SessionImpl; import org.priha.core.namespace.NamespaceRegistryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.Path; import org.priha.util.Base64; import org.priha.util.QName; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Does the chunky work of importing stuff into the repository. Always requires * a Session within which the stuff is sent to the repo; however, you can * either ask the importer to commit stuff on its own, or just skip it. */ public class XMLImport extends DefaultHandler { private SessionImpl m_session; private boolean m_immediateCommit; private Path m_currentPath; private int m_uuidBehavior; private ParserStyle m_style = ParserStyle.UNKNOWN; private NodeImpl m_currentNode; private NodeStore m_currentStore; private PropertyStore m_currentProperty; private boolean m_readingValue = false; private StringBuilder m_charContent; private static Logger log = Logger.getLogger(XMLImport.class.getName()); public XMLImport( SessionImpl session, boolean immediateCommit, Path startPath, int uuidBehavior ) throws RepositoryException { if( !session.getRootNode().hasNode(startPath.toString()) ) throw new PathNotFoundException("The parent path "+startPath+" does not exist, so cannot import to it!"); + NodeImpl parent = (NodeImpl)session.getItem(startPath); + + if( parent.hasMixinType("mix:versionable") ) + { + if( !parent.isCheckedOut() ) + { + throw new VersionException("Cannot import to a checked in node"); + } + } + else + { + NodeImpl p = parent.getParent(); + while( !p.getInternalPath().isRoot() && !p.hasMixinType("mix:versionable") ) + { + p = p.getParent(); + } + + if( !p.getInternalPath().isRoot() && !p.isCheckedOut() ) + { + throw new VersionException("Cannot import to a non-versionable child of a checked-in node"); + } + } + + m_session = session; m_immediateCommit = immediateCommit; m_currentPath = startPath; m_uuidBehavior = uuidBehavior; m_currentNode = session.getRootNode().getNode( startPath.toString() ); } public void doImport( InputStream xmlDoc ) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware( true ); spf.setValidating( false ); spf.setFeature( "http://xml.org/sax/features/namespace-prefixes", true ); SAXParser parser = spf.newSAXParser(); boolean s = m_session.setSuper( true ); try { parser.parse( xmlDoc, this ); } finally { m_session.setSuper( s ); } } private void checkSystem() throws SAXException { if( m_style == ParserStyle.DOCUMENT ) throw new SAXException("System View elements found in a Document View document!"); m_style = ParserStyle.SYSTEM; } private void checkDocument() throws SAXException { if( m_style == ParserStyle.SYSTEM ) throw new SAXException("Document view elements found in a System level document."); m_style = ParserStyle.DOCUMENT; } private PropertyStore getProp(NodeStore ns, QName name) { for( PropertyStore ps : ns.m_properties ) { if( ps.m_propertyName.equals(name) ) return ps; } return null; } /** * This method takes the item which has just been read from the XML * event stream, and creates the corresponding Nodes and Properties in the repository. * * @param ns The NodeStore * @throws ValueFormatException * @throws IllegalStateException * @throws RepositoryException */ private void deserializeStore( NodeStore ns ) throws ValueFormatException, IllegalStateException, RepositoryException { PropertyStore psp = getProp(ns,JCRConstants.Q_JCR_PRIMARYTYPE); String primaryType; String uuid = null; NodeImpl uuidNode = null; if( psp != null && psp.m_values.size() > 0 ) primaryType = psp.m_values.get(0).getString(); else primaryType = "nt:unstructured"; // FIXME: Stupid guess. String path = m_currentPath.toString(); log.finest("Deserializing node at "+path); if( m_session.itemExists(path) ) { throw new ItemExistsException("There already exists a node at "+path); } // // Find the UUID and, if it exists, a possible previous Node which // has the same UUID. // PropertyStore uuidPS = ns.findProperty( JCRConstants.Q_JCR_UUID ); if( uuidPS != null ) { uuid = uuidPS.m_values.get(0).getString(); try { uuidNode = m_session.getNodeByUUID( uuid ); } catch( ItemNotFoundException e ) {} } NodeImpl nd; // // Do we need to replace an existing Node with the same UUID? // if( m_uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING && uuid != null && uuidNode != null ) { log.fine("Replacing node "+uuidNode.getPath()+" due to UUID_COLLISION_REPLACE_EXISTING"); NodeImpl parent = uuidNode.getParent(); uuidNode.remove(); m_currentNode = parent; } // System.out.println("Adding "+m_currentStore.m_nodeName); nd = m_currentNode.addNode( m_currentStore.m_nodeName, primaryType ); // // If there's an UUID, we have to figure out what to do with it. // if( uuid != null ) { //nd.addMixin( "mix:referenceable" ); switch( m_uuidBehavior ) { case ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW: if( uuidNode != null ) throw new ItemExistsException("UUID "+uuid+" already exists in repository, and IMPORT_UUID_COLLISION_THROW was defined."); nd.setProperty( "jcr:uuid", uuid ); break; case ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW: // Will be created automatically on save() break; case ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING: if( uuidNode != null ) { // Yes, there is a collision if( uuidNode.getInternalPath().isParentOf( m_currentPath ) ) { throw new ConstraintViolationException("Importing this node ("+nd.getPath()+") would result in one of its parents being removed - "+ "which, in general, is kinda like traveling back in time and shooting your "+ "grandparents. Most time traveling guidelines strongly recommend against this, as "+ "it will lead to paradoxes. This is also why it is not possible within JCR. Not that "+ "this is exactly time travel technology, far from it, but it just keeps stuff neat "+ "and tidy, you know."); } log.fine("Removing node "+uuidNode.getPath()+" due to UUID_COLLISION_REMOVE_EXISTING"); log.fine("New node is "+nd); uuidNode.remove(); } nd.setProperty( "jcr:uuid", uuid ); break; case ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING: nd.setProperty( "jcr:uuid", uuid ); break; } } m_currentNode = nd; for( PropertyStore ps : ns.m_properties ) { // // Known property names which need to be handled separately. // if( ps.m_propertyName.equals(JCRConstants.Q_JCR_PRIMARYTYPE) ) continue; if( ps.m_propertyName.equals(JCRConstants.Q_JCR_MIXINTYPES) ) { for( Value v : ps.m_values ) { nd.addMixin( v.getString() ); } continue; } // Already handled if( ps.m_propertyName.equals(JCRConstants.Q_JCR_UUID) ) continue; // We don't yet support exporting version histories. if( ps.m_propertyName.equals(JCRConstants.Q_JCR_BASEVERSION) ) continue; // // Start the real unmarshalling // log.finest(" Property: "+ps.m_propertyName); // // Now we try to figure out whether this should be a multi or a single property. // The problem is when it is a multi property, but it was written as a single value. // // If there is a multidefinition, but no single definition, we assume this // to be a multiproperty. If both exist, we'll assume a single property, unless // the single property is matched to be a wildcard. // QPropertyDefinition pdmulti = nd.findPropertyDefinition( ps.m_propertyName, true ); QPropertyDefinition pdsingle = nd.findPropertyDefinition( ps.m_propertyName, false ); boolean ismultiproperty = (pdmulti != null && (pdsingle == null || (pdsingle != null && pdsingle.isWildCard() && !pdmulti.isWildCard()) ) ); if( ps.m_values.size() == 1 && !ismultiproperty ) { nd.setProperty( m_session.fromQName( ps.m_propertyName ), ps.m_values.get(0) ); //System.out.println(" "+ps.m_propertyName+" => SINGLE = "+ps.m_values.get(0)); } else { nd.setProperty( m_session.fromQName( ps.m_propertyName ), ps.m_values.toArray( new Value[ps.m_values.size()] ) ); //System.out.println(" "+ps.m_propertyName+" => MULTI = "+ps.m_values.size()+" items"); } } // System.out.println("Imported new node "+nd); if( m_immediateCommit ) { m_session.save(); } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { String name = qName != null ? qName : localName; if( name.equals("sv:node") ) { checkSystem(); String nodeName = attrs.getValue("sv:name"); // Hitting a new Node means that all the properties have been read, // so we can deserialize the last store. if( m_currentStore != null ) { try { log.finest("New -> "); deserializeStore( m_currentStore ); } catch( Exception e ) { throw new SAXException("Deserialization failed",e); } } m_currentStore = new NodeStore(); if( nodeName.equals("jcr:root") ) { nodeName = "/"; } m_currentStore.m_nodeName = nodeName; try { m_currentPath = m_currentPath.resolve(m_session.toQName( nodeName ) ); } catch( RepositoryException e ) { throw new SAXException(e); } return; } else if( name.equals("sv:property") ) { checkSystem(); try { NamespaceRegistryImpl nr = m_session.getWorkspace().getNamespaceRegistry(); String propName = attrs.getValue("sv:name"); String propType = attrs.getValue("sv:type"); m_currentProperty = new PropertyStore(); m_currentProperty.m_propertyName = nr.toQName( propName ); m_currentProperty.m_propertyType = PropertyType.valueFromName( propType ); } catch( Exception e ) { throw new SAXException("Unable to parse property name",e); } return; } else if( name.equals("sv:value") ) { checkSystem(); m_readingValue = true; m_charContent = new StringBuilder(); return; } // // Alright, this is then a Document view document. // checkDocument(); String nodeName = name; m_currentStore = new NodeStore(); m_currentStore.m_nodeName = nodeName; try { for( int i = 0; i < attrs.getLength(); i++ ) { String attname = attrs.getQName(i); if( attname.equals( "" ) ) attname = attrs.getLocalName(i); m_currentProperty = new PropertyStore(); String attvalue = attrs.getValue(i); NamespaceRegistryImpl nr = m_session.getWorkspace().getNamespaceRegistry(); m_currentProperty.m_propertyName = nr.toQName( attname ); m_currentProperty.m_propertyType = PropertyType.STRING; m_currentProperty.addValue( m_session.getValueFactory().createValue( attvalue ) ); m_currentStore.m_properties.add( m_currentProperty ); } m_currentPath = m_currentPath.resolve(m_session.toQName( nodeName ) ); deserializeStore( m_currentStore ); } catch( RepositoryException e ) { throw new SAXException(e); } return; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String name = qName != null ? qName : localName; if( name.equals("sv:node") ) { boolean isSuper = m_session.setSuper( true ); try { log.finest("End -> "); if( m_currentStore != null ) deserializeStore( m_currentStore ); m_currentNode = m_currentNode.getParent(); m_currentPath = m_currentPath.getParentPath(); m_currentStore = null; } catch (RepositoryException e) { log.log( Level.WARNING, "Node deserialization failed", e ); throw new SAXException("Could not deserialize node",e); } finally { m_session.setSuper( isSuper ); } } else if( name.equals("sv:value") ) { if( m_readingValue ) { ValueImpl v; try { if( m_currentProperty.m_propertyType == PropertyType.BINARY ) { InputStream in = new Base64.InputStream( new ByteArrayInputStream(m_charContent.toString().getBytes("UTF-8")) ); v = m_session.getValueFactory().createValue( in ); } else { v = m_session.getValueFactory().createValue( m_charContent.toString(), m_currentProperty.m_propertyType ); } m_currentProperty.m_values.add( v ); } catch (Exception e) { log.log( Level.WARNING, "Node deserialization failed; unable to parse a variable value", e ); throw new SAXException("Could not deserialize node",e); } finally { m_readingValue = false; m_charContent = null; } } } else if( name.equals("sv:property") ) { m_currentStore.m_properties.add( m_currentProperty ); m_currentProperty = null; } else { // Document view try { m_currentPath = m_currentPath.getParentPath(); m_currentNode = m_currentNode.getParent(); } catch( Exception e ) { throw new SAXException(e); } } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { // System.out.println(prefix + " = " + uri ); try { NamespaceRegistry r = m_session.getWorkspace().getNamespaceRegistry(); r.registerNamespace( prefix, uri ); } catch( NamespaceException e ) { // Ignore quietly; this is usually because there are mappings in the // document which are known to us. // e.printStackTrace(); } catch( RepositoryException e ) { throw new SAXException(e); } } /** * Parse the character data coming in; that is, create the Values which are put * into the properties. * <p> * Unfortunately, this method handles Binary properties by reading them completely * into memory as a String, and turning that into a byte array, essentially taking * 3x the amount of memory that what it should. Better solutions are welcomed... */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if( m_style == ParserStyle.DOCUMENT ) { try { String valueString = new String(ch,start,length); // FIXME: Should not do this yet NodeImpl xmlText = m_currentNode.addNode( "jcr:xmltext" ); xmlText.setProperty( "jcr:xmlcharacters", valueString ); } catch( RepositoryException e ) { throw new SAXException(e); } return; } // System if( m_readingValue ) { String valueString = new String(ch,start,length); if( m_charContent == null ) m_charContent = new StringBuilder(); m_charContent.append(valueString); } } /** Just stores the state of the parser. */ private static enum ParserStyle { DOCUMENT, SYSTEM, UNKNOWN } private static class NodeStore { public String m_nodeName; public List<PropertyStore> m_properties = new ArrayList<PropertyStore>(); public PropertyStore findProperty( QName name ) { for( PropertyStore ps : m_properties ) { if( ps.m_propertyName.equals(name) ) return ps; } return null; } @Override public String toString() { return m_nodeName; } } private static class PropertyStore {
jalkanen/Priha
44514f646670d1d7b5ea992eb859590a28c2d035
OOps, svn.
diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 155860a..2845b74 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ public static final int MINORREVISION = 1; /** * E.g. "alpha" or "beta". */ - public static final String POSTFIX = "alpha"; + public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } }
jalkanen/Priha
33652715cdf39ea76093dfbfa82437dca08311d2
FileProvider speedup: Added internal cache for mangleName().
diff --git a/ChangeLog b/ChangeLog index f7c96d6..92beb52 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,518 @@ +2010-01-02 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.7.1 + + * FileProvider speedup - added internal cache for mangleName(). + 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index d3d4538..155860a 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 7; /** * The current minor revision. */ - public static final int MINORREVISION = 0; + public static final int MINORREVISION = 1; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "alpha"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index f693256..3138597 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -1,1663 +1,1684 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import java.io.*; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import org.priha.core.ItemType; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.core.binary.FileBinarySource; import org.priha.core.values.QValue; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.Path.Component; import org.priha.util.*; /** * A simple file system -based provider. This is not particularly optimized. * Stores UUIDs and references as journaling files which are compacted * at every N writes and on shutdown. If there is a power outage just * in the middle of this process, it's possible that the file ends up * being corrupted. Currently there is no way to rebuild the UUIDs. * <p> * The FileProvider does not support failure recovery at the moment. So it's probably not * the best provider for production systems. */ public class FileProvider implements RepositoryProvider, PerformanceReporter { private static final String PROP_NUM_PROPERTIES = "numProperties"; private static final String PROP_MULTIPLE = "multiple"; private static final String PROP_TYPE = "type"; private static final String PROP_PATH = "path"; private static final int BUFFER_SIZE = 4096; private static final String LOCKFILE = ".prihalock"; private String m_root; private String m_workspaceRoot; private Logger log = Logger.getLogger( getClass().getName() ); private long[] m_hitCount; private Path m_systemPath; private Map<String,UUIDObjectStore<Path[]>> m_references = new HashMap<String, UUIDObjectStore<Path[]>>(); private Map<String,UUIDObjectStore<Path>> m_uuids = new HashMap<String, UUIDObjectStore<Path>>(); + private Map<String,String> m_mangledNames = new Hashtable<String, String>(); + private long m_cacheMisses = 0; + private long m_cacheHits = 0; + public FileProvider() throws RepositoryException { resetCounts(); } /** * Returns the File which houses all of the workspaces. * @return */ private String getWorkspaceRoot() { if( m_workspaceRoot == null ) { m_workspaceRoot = m_root + "/workspaces"; } return m_workspaceRoot; } /** * Figures out what the filename for a Workspace is. * @param ws * @return */ // FIXME: Should escape the filename properly. private String getWorkspaceFilename( Workspace ws ) { return ws.getName(); } /** * Figures out the what the filename for a given path is. * @param path * @return * @throws RepositoryException * @throws NamespaceException */ // FIXME: Should escape the path properly private String getPathFilename( Path path ) throws NamespaceException, RepositoryException { String p = path.toString( RepositoryImpl.getGlobalNamespaceRegistry() ); return mangleName(p); } /** * Create a valid filename based on the QName and a suffix. * * @param name * @param suffix * @return */ private String makeFilename( QName name, String suffix ) { String filename; try { filename = RepositoryImpl.getGlobalNamespaceRegistry().fromQName(name); } catch( NamespaceException e ) { filename = name.getLocalPart(); } if( suffix != null ) filename = filename + suffix; return mangleName(filename); } /** * Returns the directory for a particular Workspace. * * @param wsname * @return */ private String getWorkspaceDir( String wsname ) { String wsDir = getWorkspaceRoot() + "/" + wsname; return wsDir; } /** * Returns the directory in which a particular Node in a particular workspace resides * * @param ws * @param path * @return * @throws RepositoryException * @throws NamespaceException */ private File getNodeDir( Workspace ws, Path path ) throws NamespaceException, RepositoryException { if( m_systemPath.isParentOf( path ) || m_systemPath.equals( path ) ) { return new File( m_root, getPathFilename(path) ); } String wsDir = getWorkspaceDir( getWorkspaceFilename(ws) ); File nodeDir = new File( wsDir, getPathFilename(path) ); return nodeDir; } public void addNode(StoreTransaction tx, Path path, QNodeDefinition def) throws RepositoryException { m_hitCount[Count.AddNode.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path ); nodeDir.mkdirs(); if( !path.isRoot() ) { List<String> order = getOrder(ws,path.getParentPath()); if( !order.contains( path.getLastComponent().toString() ) ) { order.add( path.getLastComponent().toString() ); saveOrder( ws, path.getParentPath(), order ); } } } private void acquirePaths( Path startPath, File dir, List<Path> list, boolean recurse ) { File[] files = dir.listFiles(); if( files == null || files.length == 0 ) return; for( File f : files ) { if( f.isDirectory() ) { try { Properties props = getPropertyInfo( f, Q_JCR_PRIMARYTYPE ); Path p = PathFactory.getPath( props.getProperty( PROP_PATH ) ); list.add( p.getParentPath() ); if( recurse ) { acquirePaths( p.getParentPath(), f, list, recurse ); } } catch( PathNotFoundException e ) { // Skip, don't include. } catch( IOException e ) { // Skip, don't include. } catch (NamespaceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidPathException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch( NullPointerException e ) { e.printStackTrace(); } } } } public List<String> listWorkspaces() { m_hitCount[Count.ListWorkspaces.ordinal()]++; ArrayList<String> list = new ArrayList<String>(); File[] dirs = new File(getWorkspaceRoot()).listFiles(); if( dirs != null ) { for( File f : dirs ) { if( f.isDirectory() ) { list.add( f.getName() ); } } } return list; } private boolean deleteContents( File dir ) { // System.out.println("Deleting "+dir.getAbsolutePath()); for( File f : dir.listFiles() ) { if( f.isDirectory() ) { deleteContents( f ); } if( !f.delete() ) return false; } return true; } public void start(RepositoryImpl rep, Properties props) throws ConfigurationException { m_hitCount[Count.Start.ordinal()]++; try { m_systemPath = PathFactory.getPath( RepositoryImpl.getGlobalNamespaceRegistry(), "/jcr:system" ); } catch( RepositoryException e ) { throw new ConfigurationException("Unable to create a /jcr:system instance: "+e.getMessage()); } String wsList = props.getProperty("workspaces", "default"); m_root = props.getProperty("directory"); // // Make sure that root exists. // File root = new File(m_root); root.mkdirs(); // // Make sure this instance is the only one using that root. // File lockFile = new File(m_root, LOCKFILE); if( lockFile.exists() ) { String msg = "Cannot use the Priha FileProvider repository while another instance of Priha is using it. "+ "If you are sure there are no other instances using this same repository, please "+ "remove the '"+lockFile.getAbsolutePath()+"' file and restart."; log.severe( msg ); throw new ConfigurationException(msg); } // // Create the lock file; and make sure it gets cleaned up properly in // most cases. // try { lockFile.createNewFile(); lockFile.deleteOnExit(); } catch( IOException e ) { throw new ConfigurationException("Cannot start Priha ",e); } // // Initializing the workspaces. // log.fine("Initializing FileProvider with root "+m_root); String[] workspaces = wsList.split("\\s"); for( String wsname : workspaces ) { File wsroot = new File(getWorkspaceDir(wsname)); if( !wsroot.exists() ) { wsroot.mkdirs(); log.finer("Created workspace directory "+wsroot); } // // Reset the workspaces. // m_references.put( wsname, new UUIDObjectStore<Path[]>(mangleName(wsname)+"-references.ser") ); m_uuids.put( wsname, new UUIDObjectStore<Path>(mangleName(wsname)+"-uuid.ser") ); } } public void stop(RepositoryImpl rep) { m_hitCount[Count.Stop.ordinal()]++; log.fine("Shutting down FileProvider..."); for( UUIDObjectStore<Path[]> s : m_references.values() ) { s.shutdown(); } for( UUIDObjectStore<Path> s : m_uuids.values() ) { s.shutdown(); } m_references.clear(); m_uuids.clear(); // // Clean up the lockfile, in case we're e.g. switching repos mid-flight. // File lockFile = new File(m_root, LOCKFILE); lockFile.delete(); + + log.finer("Manglename cache hits = "+m_cacheHits+", misses = "+m_cacheMisses); } public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Copy.ordinal()]++; throw new UnsupportedRepositoryOperationException("copy()"); } public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws NamespaceException, RepositoryException { m_hitCount[Count.ListNodes.ordinal()]++; ArrayList<Path> list = new ArrayList<Path>(); File startPath = getNodeDir( ws, parentpath ); if( !startPath.exists() ) throw new PathNotFoundException("No such path found: "+parentpath); //acquirePaths( parentpath, startPath, list, false ); List<String> orderArray = getOrder( ws, parentpath ); for( String s : orderArray ) { Path childPath = parentpath.resolve( Path.Component.valueOf( s ) ); list.add( childPath ); } // // The .order -file will probably not contain the system path for anyone else // except the workspace which was created first. // if( parentpath.isRoot() && !list.contains( m_systemPath )) { list.add( 0, m_systemPath ); } return list; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.ListProperties.ordinal()]++; File nodeDir = getNodeDir( ws, path ); List<QName> proplist = new ArrayList<QName>(); try { File[] files = nodeDir.listFiles( new PropertyTypeFilter() ); if( files != null ) { for( File propertyFile : files ) { Properties props; FileInputStream in = null; try { in = new FileInputStream(propertyFile); props = FastPropertyStore.load(in); String qname = props.getProperty(PROP_PATH); proplist.add( PathFactory.getPath( qname ).getLastComponent() ); } finally { if( in != null ) in.close(); } } } } catch( IOException e ) { throw new RepositoryException("Thingy said booboo", e); } return proplist; } public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Move.ordinal()]++; throw new UnsupportedRepositoryOperationException("move()"); } /** * A Node exists only if it has a primaryType.info in the directory. */ public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) { m_hitCount[Count.ItemExists.ordinal()]++; File nodeDir; try { File propFile; if( type == ItemType.NODE ) { nodeDir = getNodeDir( ws, path ); propFile = new File( nodeDir, mangleName("jcr:primaryType.info") ); } else if( type == ItemType.PROPERTY ) { nodeDir = getNodeDir( ws, path.getParentPath() ); propFile = new File( nodeDir, makeFilename( path.getLastComponent(), ".info" ) ); } else { throw new IllegalArgumentException("Type "+type.name()+" not supported"); } return propFile.exists(); } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_hitCount[Count.Open.ordinal()]++; List<String> wsnames = listWorkspaces(); if( wsnames.indexOf(workspaceName) == -1 ) throw new NoSuchWorkspaceException(workspaceName); log.finer("Workspace "+workspaceName+" has been opened."); } public void close(WorkspaceImpl ws) { log.finer( "Workspace "+ws.getName()+" closing..." ); m_hitCount[Count.Close.ordinal()]++; /* try { m_uuids.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } catch( NullPointerException e ) { log.warning( "A non-configured workspace '"+ws.getName()+"' detected. If you are using a multiprovider configuration, please check this workspace actually exists." ); return; } try { m_references.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } */ } private void writeValue( File f, ValueImpl v ) throws IOException, IllegalStateException, RepositoryException { OutputStream out = null; InputStream in = null; try { if( v instanceof QValue.QValueInner ) { byte[] ba = ((QValue.QValueInner)v).getQValue().getString().getBytes("UTF-8"); in = new ByteArrayInputStream(ba); } else { in = v.getStream(); } out = new FileOutputStream( f ); copyContents( in, out ); } finally { // // ...and close all the streams. // if( out != null ) { try { out.close(); } finally { if( in != null ) in.close(); } } } } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc) throws RepositoryException { m_hitCount[Count.PutPropertyValue.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path.getParentPath() ); saveUuidShortcut(ws,path,vc); QName qname = path.getLastComponent(); File inf = new File( nodeDir, makeFilename( qname, ".info" ) ); Properties props = new Properties(); props.setProperty( PROP_PATH, path.toString() ); props.setProperty( PROP_TYPE, PropertyType.nameFromValue( vc.getType() ) ); props.setProperty( PROP_MULTIPLE, vc.isMultiple() ? "true" : "false" ); OutputStream out = null; try { if( vc.isMultiple() ) { props.setProperty( PROP_NUM_PROPERTIES, Integer.toString(vc.getValues().length) ); Value[] values = vc.getValues(); // // Let's clear previous references, if this is an attempt to save // a null value. // if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl[] oldval = getPropertyValue( ws, path ).getValues(); for( ValueImpl vi : oldval ) { String uuid = vi.getString(); cleanRefMapping( ws, path, uuid ); } } catch( PathNotFoundException e ){} // This is okay } for( int i = 0; i < values.length; i++ ) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); saveRefShortcut( ws, path, (ValueImpl)values[i] ); writeValue( df, (ValueImpl)values[i] ); } // Remove the rest of old values int i = values.length; while(true) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); if( df.exists() ) df.delete(); else break; } } else { if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl oldval = getPropertyValue( ws, path ).getValue(); cleanRefMapping( ws, path, oldval.getString() ); } catch(PathNotFoundException e) {} // OK saveRefShortcut( ws, path, vc.getValue() ); } File df = new File( nodeDir, makeFilename( qname, ".data" ) ); writeValue( df, vc.getValue() ); } out = new FileOutputStream(inf); FastPropertyStore.store( out, props ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * Saves a shortcut to an UUID. The contents of the file are the path of the Node. * */ private void saveUuidShortcut(WorkspaceImpl ws, Path path, ValueContainer vc) throws RepositoryException { if( path.getLastComponent().equals(Q_JCR_UUID) ) { UUIDObjectStore<Path> uuids = m_uuids.get( ws.getName() ); uuids.setObject( vc.getValue().valueAsString(), path.getParentPath() ); } } private ValueImpl prepareValue( WorkspaceImpl ws, File propFile, String propType ) throws IOException, RepositoryException { ValueFactoryImpl vf = ws.getSession().getValueFactory(); ValueImpl value; if( propType.equals(PropertyType.TYPENAME_STRING) ) { value = vf.createValue( readContentsAsString(propFile) ); } else if( propType.equals(PropertyType.TYPENAME_BOOLEAN) ) { value = vf.createValue( "true".equals(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DOUBLE) ) { value = vf.createValue( Double.parseDouble(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_LONG) ) { value = vf.createValue( Long.parseLong(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DATE) ) { value = vf.createValue( readContentsAsString( propFile ), PropertyType.DATE ); } else if( propType.equals(PropertyType.TYPENAME_NAME) ) { String qnameStr = readContentsAsString(propFile); QName qn = QName.valueOf( qnameStr ); value = vf.createValue( qn, PropertyType.NAME ); } else if( propType.equals(PropertyType.TYPENAME_PATH )) { String val = readContentsAsString(propFile); value = vf.createValue( val, PropertyType.PATH ); } else if( propType.equals(PropertyType.TYPENAME_REFERENCE ) ) { value = vf.createValue( readContentsAsString(propFile), PropertyType.REFERENCE ); } else if( propType.equals(PropertyType.TYPENAME_BINARY) ) { value = vf.createValue( new FileBinarySource(propFile) ); } else throw new RepositoryException("Cannot deserialize property type "+propType); return value; } /** * Returns the contents of the .info -file. * * @param nodeDir * @return * @throws PathNotFoundException * @throws IOException */ private Properties getPropertyInfo( File nodeDir, QName name ) throws PathNotFoundException, IOException { File inf = new File( nodeDir, makeFilename( name, ".info" ) ); if( !inf.exists() ) { throw new PathNotFoundException("The property metadata file was not found: "+inf.getAbsolutePath()); } Properties props; FileInputStream in = null; try { in = new FileInputStream( inf ); props = FastPropertyStore.load(in); } finally { if( in != null ) in.close(); } return props; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.GetPropertyValue.ordinal()]++; File nodeDir = getNodeDir( ws, path.getParentPath() ); try { Properties props = getPropertyInfo( nodeDir, path.getLastComponent() ); String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); ValueImpl[] result = new ValueImpl[items]; for( int i = 0; i < items; i++ ) { File df = new File( nodeDir, makeFilename(path.getLastComponent(),"."+i+".data") ); ValueImpl v = prepareValue( ws, df, propType ); result[i] = v; } return new ValueContainer(result, PropertyType.valueFromName( propType ) ); } File df = new File( nodeDir, makeFilename( path.getLastComponent(), ".data" ) ); ValueImpl v = prepareValue(ws, df, propType); return new ValueContainer(v); } catch( IOException e ) { throw new RepositoryException("Unable to read property file",e); } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ - // TODO: This method is extremely speed-critical // TODO: Protect against windows special names (CON) etc. - protected static String mangleName( String name ) + protected String mangleName( String name ) { + // + // Check the internal cache first. + // + String cached = m_mangledNames.get(name); + + if( cached != null ) + { + m_cacheHits++; + return cached; + } + + m_cacheMisses++; StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } else if( ch == ':' ) { // Colon is not allowed on NTFS or OSX. sb.append( ';' ); } else if( ch >= 'A' && ch <= 'Z' ) { // JSR-170 is case sensitive, so we have to make // sure our storage is too. sb.append( ch ); sb.append( '^' ); } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } - return sb.toString(); + String result = sb.toString(); + + m_mangledNames.put(name, result); + + return result; } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } /** * Just copies all characters from <i>in</i> to <i>out</i>. */ private static void copyContents( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private static void copyContents(Reader in, Writer out) throws IOException { char[] buf = new char[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private String readContentsAsString( File file ) throws IOException { Reader in = new InputStreamReader( new FileInputStream(file), "UTF-8" ); try { StringWriter out = new StringWriter(); copyContents( in, out ); return out.toString(); } finally { in.close(); } } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; private long m_lastWrite = System.currentTimeMillis(); /* After this many writes the store is compacted. */ private static final int COMPACT_LIMIT = 100; /* But compacting is not done more often than this limit (in ms) */ private static final long COMPACT_TIME_LIMIT = 30*1000L; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); long now = System.currentTimeMillis(); if( ++m_writeCount > COMPACT_LIMIT && (now-m_lastWrite) > COMPACT_TIME_LIMIT ) { //System.out.println( now-m_lastWrite ); serialize(); m_writeCount = 0; m_lastWrite = now; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { // System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } }
jalkanen/Priha
72039e60e190a9b2831c28a15ada4894a78130a2
Implemented restore().
diff --git a/ChangeLog b/ChangeLog index ccff661..f7c96d6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,515 +1,517 @@ 2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> * Implemented Version labels. + + * Implemented first version of Node.restore(). 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 860aae9..8932ee5 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,583 +1,585 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; import org.priha.core.locks.LockManager; import org.priha.core.locks.QLock; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; /** * Implements a Node. This is one of the most heavy classes in Priha, with a lot * of stuff happening. The NodeImpl class does some basic caching for some state * objects, so keeping references can be faster in some cases. */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { + private static final String JCR_FROZENUUID = "jcr:frozenUuid"; + private static final String JCR_FROZENNODE = "jcr:frozenNode"; private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; /** * A compile-time flag for allowing/disallowing Same Name Sibling support. * addNode() will throw an exception if you disallow these. This is sometimes * useful for debugging. */ private static final boolean ALLOW_SNS = true; private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; private static final String NO_UUID = ""; // If there is no UUID for this Node. static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { enterState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.enterState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.enterState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public LazyPropertyIteratorImpl getProperties() throws RepositoryException { List<Path> ls = new ArrayList<Path>(); ls.addAll(m_session.m_provider.listProperties(getInternalPath())); return new LazyPropertyIteratorImpl( getSession(), ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // @@ -954,1437 +956,1516 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> protected PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } if( value == null ) { removeProperty(prop); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); } // FIXME: No rollback support public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { if( getState() == ItemState.NEW ) throw new InvalidItemStateException("Cannot call save on newly added node "+getInternalPath()); internalSave(); } public int compareTo(Node nd) { try { return getPath().compareTo(nd.getPath()); } catch( RepositoryException e ) { return 0; } // FIXME: This should never occur } public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { - remove(false); + remove(false,true); + } + + public void removeNodeOnly() throws VersionException, LockException, ConstraintViolationException, RepositoryException + { + remove(false,false); } /** * If isRemoving = true, will remove subnodes without question. */ - private void remove(boolean isRemoving) throws VersionException, LockException, ConstraintViolationException, RepositoryException + private void remove(boolean isRemoving,boolean removeVersionHistory) throws VersionException, LockException, ConstraintViolationException, RepositoryException { if( getState() == ItemState.REMOVED ) { // System.out.println(getPath()+" has already been removed"); return; // Die nicely } Path path = getInternalPath(); if( !m_session.m_provider.nodeExistsInRepository( path ) && m_session.m_provider.m_changedItems.getLatestItem(path) == null ) { m_session.m_provider.m_changedItems.dump(); throw new InvalidItemStateException("Item has already been removed by another Session "+getPath()); } if( path.isRoot() || path.equals( JCRConstants.Q_JCR_SYSTEM_PATH ) ) { return; // Refuse to remove } NodeImpl parent = getParent(); NodeType parentType = parent.getPrimaryNodeType(); if( !getSession().isSuper() ) { // Anything from under /jcr:system cannot be deleted by the user if( JCRConstants.Q_JCR_SYSTEM_PATH.isParentOf( path )) return; if( getParent().isLockedWithoutToken() ) throw new LockException("The parent is locked, so you cannot remove it."); if( !parentType.canRemoveItem(getName()) && getParent().getState() != ItemState.REMOVED && !isRemoving ) { throw new ConstraintViolationException("Attempted to delete a mandatory child node:"+getInternalPath()); } } QLock li = m_lockManager.getLock( path ); if( li != null ) m_lockManager.removeLock( li ); // // Remove version history // - if( isNodeType( "mix:versionable" ) ) + if( removeVersionHistory && isNodeType( "mix:versionable" ) ) { // // Version histories cannot be removed unless you have a // superuser session. // boolean isSuper = m_session.setSuper(true); try { getVersionHistory().remove(); } catch( UnsupportedRepositoryOperationException e ) { // This may happen if you've just created a Node, then hit remove() on it immediately, since // in that case, we do not have an UUID yet. } finally { m_session.setSuper( isSuper ); } } // // Removal happens in a depth-first manner. // // // Remove children. We do this in a reverse order in order // not to force annoying moves for same-name siblings. It's just faster. // LazyNodeIteratorImpl ndi = (LazyNodeIteratorImpl) getNodes(); ndi.skip( ndi.getSize() ); while( ndi.hasPrevious() ) { NodeImpl nd = ndi.previousNode(); // System.out.println("REMOVING "+nd.getPath()); - nd.remove(true); + nd.remove(true,removeVersionHistory); } boolean isSuper = m_session.setSuper(true); // // Remove properties // for( PropertyIterator pit = getProperties(); pit.hasNext(); ) { pit.nextProperty().remove(); } // This is a hack which just resets the state and then adds this to the remove queue. FIXME! // m_state = ItemState.UPDATED; enterState( ItemState.REMOVED ); // // Fix same name siblings, but don't bother if the parent is already removed. // Again, we go for the super session. // try { int myIndex = getInternalPath().getLastComponent().getIndex(); if( !isRemoving ) { for( NodeIterator ni = getParent().getNodes( getName() ); ni.hasNext(); ) { NodeImpl n = (NodeImpl)ni.nextNode(); int siblingIndex = n.getInternalPath().getLastComponent().getIndex(); if( myIndex >= siblingIndex ) continue; Path destPath = new Path(n.getParent().getInternalPath(), new Path.Component(getQName(),siblingIndex-1) ); // System.out.println("Moving "+n+" to "+destPath); // m_session.m_provider.m_changedItems.dump(); getSession().move( n.getInternalPath().toString( m_session ), destPath.toString( m_session ) ); } } } finally { m_session.setSuper(isSuper); } log.finer("Removed "+getPath()); } /** * Locates a PropertyDefinition for the given property name from the array of * the mixintypes and the primary type for this Node. * * @param propertyName The QName of the property to look for * @param multiple Is this a multiproperty or a single property? * @return A valid PropertyDefinition, or null, if it cannot be located. * @throws RepositoryException If mixin node types cannot be determined. */ public QPropertyDefinition findPropertyDefinition(QName propertyName,boolean multiple) throws RepositoryException { QPropertyDefinition qp; // // Mixin types can override the primary type; especially since the // primary type can contain a wildcard. // for( NodeType nt : getMixinNodeTypes() ) { QNodeType qnt = ((QNodeType.Impl)nt).getQNodeType(); qp = qnt.findPropertyDefinition(propertyName, multiple); if( qp != null ) return qp; } return getPrimaryQNodeType().findPropertyDefinition(propertyName, multiple); } /** * Assumes nothing, goes through the properties, makes sure all things are correct. */ public void sanitize() throws RepositoryException { // log.finest("Sanitizing node "+getInternalPath()); if( m_definition == null ) { try { @SuppressWarnings("unused") PropertyImpl primarytype = getProperty( Q_JCR_PRIMARYTYPE ); } catch( Exception e ) { if( getInternalPath().isRoot() ) { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, "nt:unstructured", PropertyType.NAME ); pix.enterState(ItemState.NEW); } else { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, assignChildType( getInternalPath().getLastComponent() ).toString(), PropertyType.NAME ); pix.enterState(ItemState.NEW); } } if( getParent() != null ) { QNodeType mytype = getPrimaryQNodeType(); m_definition = getParent().getPrimaryQNodeType().findNodeDefinition( mytype.getQName() ); } else { // FIXME: Not correct m_definition = QNodeTypeManager.getInstance().findNodeDefinition( Q_NT_UNSTRUCTURED ); } if( m_definition == null ) { throw new RepositoryException("Cannot assign a node definition for "+getInternalPath()); } } // autoCreateProperties(); QNodeType mytype = getPrimaryQNodeType(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl pi = (PropertyImpl)i.next(); if( pi.getDefinition() == null ) { QPropertyDefinition pd = mytype.findPropertyDefinition( pi.getQName(), false ); // FIXME: Really? pi.m_definition = pd.new Impl(m_session); // FIXME: Inoptimal } } } /** * We consider nodes to be equal if they have the exact same path, and * all the properties are equal too. */ @Override public boolean equals(Object obj) { if( obj == this ) return true; if( obj instanceof NodeImpl ) { NodeImpl ni = (NodeImpl) obj; if( !ni.getInternalPath().equals(getInternalPath()) ) return false; if( !ni.m_session.getWorkspace().getName().equals(m_session.getWorkspace().getName()) ) return false; // All tests have succeeded return true; } return false; } @Override protected void preSave() throws RepositoryException { super.preSave(); } /** * Checks the mandatory properties for this Nodetype and throws a ConstraintViolationException * if it's not existing. * * @param nt * @throws RepositoryException */ void checkMandatoryProperties(QNodeType nt) throws RepositoryException { for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isMandatory() && !hasProperty(pd.getQName()) ) { throw new ConstraintViolationException("Node "+getInternalPath()+" is missing property "+pd.getQName()); } } } /* ============================================================ * * Mixins * */ public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { ValueFactory vf = m_session.getValueFactory(); NodeType mixin = getNodeTypeManager().getNodeType(mixinName); if( !mixin.isMixin() ) throw new NoSuchNodeTypeException("Type "+mixinName+" is not a mixin type!"); if( isLockedWithoutToken() ) throw new LockException( "Node is locked, so cannot add new mixin types." ); if( !isCheckedOut() ) throw new VersionException( "Node is not checked out, so cannot add new mixin types."); boolean oldsuper = m_session.setSuper( true ); try { Property p; p = getProperty(Q_JCR_MIXINTYPES); Value[] v = p.getValues(); Value[] newval = new Value[v.length+1]; for( int i = 0; i < v.length; i++ ) { newval[i] = v[i]; } newval[newval.length-1] = vf.createValue(mixinName,PropertyType.NAME); PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, newval, PropertyType.NAME ); pi.enterState(ItemState.UPDATED); } catch( PathNotFoundException e ) { Value[] values = new Value[] { vf.createValue(mixinName,PropertyType.NAME) }; PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, values, PropertyType.NAME ); pi.enterState(ItemState.NEW); } finally { m_session.setSuper( oldsuper ); } //autoCreateProperties(); } public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException { if( isLocked() ) return false; NodeType nt = getNodeTypeManager().getNodeType( mixinName ); if( !nt.isMixin() ) { throw new NoSuchNodeTypeException(mixinName+" is not a mixin type!"); } if( hasMixinType(nt.getName()) ) { return false; } if( !isCheckedOut() ) return false; // FIXME: This is a bit complicated and slow. if( mixinName.equals("mix:versionable") && m_session.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false") ) return false; return true; } boolean hasMixinType(String mixinType) { try { Property pi = getProperty( Q_JCR_MIXINTYPES ); for( Value v : pi.getValues() ) { String mixin = v.getString(); if( mixin.equals(mixinType) ) return true; } } catch( RepositoryException e ) {} return false; } public NodeType[] getMixinNodeTypes() throws RepositoryException { ArrayList<NodeType> mixinTypes = new ArrayList<NodeType>(); // // If there are no mixin types, then let's just return an empty array. // try { Property p = getProperty( Q_JCR_MIXINTYPES ); for( Value v : p.getValues() ) { NodeType nt = m_session.getWorkspace().getNodeTypeManager().getNodeType( v.getString() ); mixinTypes.add( nt ); } } catch( RepositoryException e ) {} return mixinTypes.toArray( new NodeType[0] ); } public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( isLocked() ) throw new LockException("Node locked, cannot remove mixin"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); Property mixinTypes = getProperty("jcr:mixinTypes"); Value[] vals = mixinTypes.getValues(); boolean found = false; for( int i = 0; i < vals.length; i++ ) { if( vals[i].getString().equals(mixinName) ) { vals[i] = null; found = true; } } if( found ) { mixinTypes.setValue( vals ); } else { throw new NoSuchNodeTypeException("No such mixin type to remove: "+mixinName); } } /*============================================================================== * * Locking * */ LockManager m_lockManager = LockManager.getInstance(getSession().getWorkspace()); public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { if( !hasMixinType("mix:lockable") ) throw new UnsupportedRepositoryOperationException("This node is not lockable: "+getInternalPath()); if( getState() == ItemState.NEW ) throw new LockException("This node has no persistent state"); if( isModified() ) throw new InvalidItemStateException("You may only lock Nodes which are not currently modified"); if( isDeep && m_lockManager.hasChildLock(getInternalPath()) ) { throw new LockException("A child of this node already holds a lock, so you cannot deep lock this node."); } if( isLocked() ) { throw new LockException("This Node is already locked."); } QLock lock = new QLock( this, isDeep, isSessionScoped ); m_session.addLockToken( lock.getToken() ); boolean isSuper = m_session.setSuper(true); try { setProperty("jcr:lockOwner", lock.getLockOwner()); setProperty("jcr:lockIsDeep", isDeep); } finally { m_session.setSuper(isSuper); } save(); m_lockManager.addLock( lock ); return lock.getLockInstance(m_session); } public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { QLock lock = m_lockManager.getLock( getInternalPath() ); if( lock == null ) throw new LockException("This Node has not been locked."); if( lock.getLockToken(m_session) == null ) throw new LockException("This Session does not own this Lock, so it cannot be unlocked."); if( isModified() ) throw new InvalidItemStateException("This Node must not be modified prior to unlocking"); Property p = getProperty("jcr:lockOwner"); p.remove(); p = getProperty("jcr:lockIsDeep"); p.remove(); m_session.removeLockToken( lock.getLockToken(m_session) ); m_lockManager.removeLock( lock ); lock.invalidate(); save(); } public QLock.Impl getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); // // Must return a clone of the Lock which is particular to this session. // if( li != null ) return li.getLockInstance(m_session); return null; } public boolean holdsLock() throws RepositoryException { QLock li = m_lockManager.getLock( getInternalPath() ); return li != null; } public boolean isLocked() throws RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); return li != null; } /** * Returns true, if this Node is locked (that is, it or it's parents are locked) * but the Session which owns this Session does not hold a token to modify it. * * @return True, if you cannot modify this Node due to missing token. */ protected boolean isLockedWithoutToken() { if( !getInternalPath().isRoot() ) { QLock li = m_lockManager.findLock(getInternalPath()); if( li != null && li.getLockToken(m_session) == null ) { return true; } } return false; } /* ==================================================== * * Versioning * */ public boolean isCheckedOut() throws RepositoryException { try { PropertyImpl p = getProperty(Q_JCR_ISCHECKEDOUT); return p.getBoolean(); } catch(PathNotFoundException e) { // Fine; no property exists. } // // Check if this is a versionable node in the first place. // if( isNodeType( "mix:versionable" ) && !isNew() ) return false; return true; } public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.cancelMerge()"); } public VersionImpl checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException { if( !hasMixinType("mix:versionable") ) { throw new UnsupportedRepositoryOperationException("Node is not mix:versionable (8.2.5)"); } if( !isCheckedOut() ) { return getBaseVersion(); } if( isModified() ) { throw new InvalidItemStateException("Node has unsaved changes (8.2.5)"); } if( hasProperty("jcr:mergeFailed") ) { throw new VersionException("Node has failed merges (8.2.5)"); } // // Phew! Preconditions have been checked. Now, let's get to real business. // boolean isSuper = getSession().setSuper(true); try { VersionHistoryImpl vh = getVersionHistory(); int version = 0; - if( !getBaseVersion().getName().equals("jcr:rootVersion") ) - version = Integer.parseInt( getBaseVersion().getName() ); - + try + { + if( !getBaseVersion().getName().equals("jcr:rootVersion") ) + version = Integer.parseInt( getBaseVersion().getName() ); + } + catch( ItemNotFoundException e ) {} // There's not yet a base version. + VersionImpl v = (VersionImpl) vh.addNode( Integer.toString( ++version ), "nt:version" ); if(!hasProperty("nt:versionHistory")) setProperty( "nt:versionHistory", vh ); // // Set up version properties // v.setProperty( JCR_PREDECESSORS, getProperty(JCR_PREDECESSORS).getValues() ); v.setProperty( "jcr:uuid", UUID.randomUUID().toString() ); v.setProperty( JCR_SUCCESSORS, new Value[0], PropertyType.REFERENCE ); setProperty( JCR_PREDECESSORS, new Value[0], PropertyType.REFERENCE ); PropertyImpl preds = v.getProperty(JCR_PREDECESSORS); // // Set up successors and predecessors // for( Value val : preds.getValues() ) { String uuid = val.getString(); Node pred = m_session.getNodeByUUID(uuid); Value[] s = pred.getProperty( JCR_SUCCESSORS ).getValues(); List<Value> successorList = new ArrayList<Value>(); successorList.addAll( Arrays.asList(s) ); successorList.add( m_session.getValueFactory().createValue(v) ); pred.setProperty( JCR_SUCCESSORS, successorList.toArray(s) ); } setProperty( "jcr:baseVersion", v ); setProperty( "jcr:isCheckedOut", false ); // // Store the contents into the frozen node of the Version node. // - NodeImpl fn = v.addNode("jcr:frozenNode","nt:frozenNode"); + NodeImpl fn = v.addNode(JCR_FROZENNODE,"nt:frozenNode"); for( LazyPropertyIteratorImpl pi = getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE ) ) { fn.setProperty( "jcr:frozenPrimaryType", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_UUID ) ) { - fn.setProperty( "jcr:frozenUuid", p.getValue() ); + fn.setProperty( JCR_FROZENUUID, p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_MIXINTYPES ) ) { fn.setProperty( "jcr:frozenMixinTypes", p.getValues() ); } else if( p.getDefinition().getOnParentVersion() == OnParentVersionAction.COPY ) { // FIXME: SHould probably deal with the others as well. if( p.getDefinition().isMultiple() ) { fn.setProperty( p.getName(), p.getValues() ); } else { fn.setProperty( p.getName(), p.getValue() ); } } } for( NodeIterator ni = getNodes(); ni.hasNext(); ) { NodeImpl n = (NodeImpl)ni.nextNode(); switch( n.getDefinition().getOnParentVersion() ) { case OnParentVersionAction.ABORT: throw new VersionException("Child node "+n.getPath()+" prevented versioning, as it has OnParentVersionAction ABORT"); case OnParentVersionAction.COMPUTE: throw new RepositoryException("COMPUTE child nodes not supported for path "+getPath()); case OnParentVersionAction.COPY: m_session.getWorkspace().copy(m_session, n.getPath(), fn.getPath(), false); break; case OnParentVersionAction.IGNORE: // Ignore, yay break; case OnParentVersionAction.INITIALIZE: throw new RepositoryException("INITIALIZE child nodes not supported for path "+getPath()); case OnParentVersionAction.VERSION: if( n.hasMixinType("mix:versionable") ) { NodeImpl vc = fn.addNode( n.getName(), "nt:versionedChild" ); vc.setProperty("jcr:childVersionHistory", n.getVersionHistory()); } else { // FIXME: Does not stop at versionable nodes m_session.getWorkspace().copy(m_session, n.getPath(), fn.getPath()+"/"+n.getName(), true); } break; } } vh.save(); save(); // FIXME: Here. return v; } finally { getSession().setSuper( isSuper ); } } public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException { if( !isNodeType( "mix:versionable" ) ) throw new UnsupportedRepositoryOperationException("Not versionable (8.2.6)"); if( isCheckedOut() ) return; // Nothing happens boolean isSuper = getSession().setSuper( true ); try { setProperty( "jcr:isCheckedOut", true ); // // We don't support multiple predecessors, so this is okay, I think. // setProperty( JCR_PREDECESSORS, new ValueImpl[] { getSession().getValueFactory().createValue( getBaseVersion() ) } ); setProperty( JCR_SUCCESSORS, new ValueImpl[0] ); // // Persist immediately. // save(); } finally { getSession().setSuper( isSuper ); } } public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.doneMerge()"); } public VersionImpl getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException { try { String bvUuid = getProperty( Q_JCR_BASEVERSION ).getString(); return (VersionImpl) getSession().getNodeByUUID( bvUuid ); } catch( PathNotFoundException e ) { throw new UnsupportedRepositoryOperationException("This is not a versioned node."); } } public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { -// TODO Auto-generated method stub - throw new UnsupportedRepositoryOperationException(); - + Version v = getVersionHistory().getVersion(versionName); + + restore( v, removeExisting ); } public void restore(Version version, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException { -// TODO Auto-generated method stub - throw new UnsupportedRepositoryOperationException(); - + restore( version, null, removeExisting ); } public void restore(Version version, String relPath, boolean removeExisting) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { -// TODO Auto-generated method stub - - throw new UnsupportedRepositoryOperationException(); + if( m_session.hasPendingChanges() ) + throw new InvalidItemStateException("Can only restore when Session does not have pending changes."); + + if( isLockedWithoutToken() ) + throw new LockException("Lock prevents restore"); + + if( getVersionHistory().getRootVersion().isSame(version) ) + { + throw new VersionException("You cannot restore the root version"); + } + + if( !version.getContainingHistory().getUUID().equals(getVersionHistory().getUUID()) ) + { + throw new VersionException("Cannot restore a Version which is not a part of the version history of this Node"); + } + NodeImpl frozenNode = (NodeImpl)version.getNode(JCR_FROZENNODE); + NodeImpl existing = null; + NodeImpl parent = getParent(); + String name = getName(); + + try + { + existing = m_session.getNodeByUUID( frozenNode.getProperty(JCR_FROZENUUID).getString() ); + + if( !removeExisting ) + throw new ItemExistsException("Node by given UUID already exists, and cannot be removed."); + } + + catch( ItemNotFoundException e ) {} + + boolean isSuper = m_session.setSuper(true); + + try + { + if( existing != null ) + { + existing.removeNodeOnly(); + } + else + { + this.removeNodeOnly(); + } + + existing = parent.addNode( name, frozenNode.getProperty("jcr:frozenPrimaryType").getString() ); + + // + // Restore properties + // + for( LazyPropertyIteratorImpl pi = frozenNode.getProperties(); pi.hasNext(); ) + { + PropertyImpl p = pi.nextProperty(); + + if( p.getQName().equals(JCRConstants.Q_JCR_PRIMARYTYPE ) ) continue; + else if( p.getName().equals(JCR_FROZENUUID)) + { + existing.setProperty("jcr:uuid", p.getValue().toString()); + } + else if( p.getName().equals("jcr:frozenMixinTypes") ) + { + existing.setProperty("jcr:mixinTypes", p.getValues() ); + } + else if( p.getDefinition().isMultiple() ) + existing.setProperty(p.getName(), p.getValues()); + else + existing.setProperty(p.getName(), p.getValue()); + } + + existing.setProperty("jcr:isCheckedOut", false); + + m_session.save(); + } + finally + { + m_session.setSuper(isSuper); + } } public void restoreByLabel(String versionLabel, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { -// TODO Auto-generated method stub - throw new UnsupportedRepositoryOperationException(); - + Version v = getVersionHistory().getVersionByLabel(versionLabel); + + restore( v, removeExisting ); } public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws NoSuchWorkspaceException, AccessDeniedException, MergeException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } }
jalkanen/Priha
44fd3a6217c23ca45aff29926b5245a6460fb4a5
Implemented Version labeling. Fixed issue where setting "null" property value might confuse ChangeStore.
diff --git a/ChangeLog b/ChangeLog index 31df3f2..ccff661 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,516 @@ +2010-01-01 Janne Jalkanen <jalkanen@ecyrd.com> + + * Implemented Version labels. + 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * Minor changes in the versioning code; introduced AbstractVersion to catch a bunch of unmodifiable methods. As versioning is still disabled, no version bump here. 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 2024e23..860aae9 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1634,705 +1634,757 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { QNodeType qnt = ((QNodeType.Impl)nt).getQNodeType(); qp = qnt.findPropertyDefinition(propertyName, multiple); if( qp != null ) return qp; } return getPrimaryQNodeType().findPropertyDefinition(propertyName, multiple); } /** * Assumes nothing, goes through the properties, makes sure all things are correct. */ public void sanitize() throws RepositoryException { // log.finest("Sanitizing node "+getInternalPath()); if( m_definition == null ) { try { @SuppressWarnings("unused") PropertyImpl primarytype = getProperty( Q_JCR_PRIMARYTYPE ); } catch( Exception e ) { if( getInternalPath().isRoot() ) { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, "nt:unstructured", PropertyType.NAME ); pix.enterState(ItemState.NEW); } else { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, assignChildType( getInternalPath().getLastComponent() ).toString(), PropertyType.NAME ); pix.enterState(ItemState.NEW); } } if( getParent() != null ) { QNodeType mytype = getPrimaryQNodeType(); m_definition = getParent().getPrimaryQNodeType().findNodeDefinition( mytype.getQName() ); } else { // FIXME: Not correct m_definition = QNodeTypeManager.getInstance().findNodeDefinition( Q_NT_UNSTRUCTURED ); } if( m_definition == null ) { throw new RepositoryException("Cannot assign a node definition for "+getInternalPath()); } } // autoCreateProperties(); QNodeType mytype = getPrimaryQNodeType(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl pi = (PropertyImpl)i.next(); if( pi.getDefinition() == null ) { QPropertyDefinition pd = mytype.findPropertyDefinition( pi.getQName(), false ); // FIXME: Really? pi.m_definition = pd.new Impl(m_session); // FIXME: Inoptimal } } } /** * We consider nodes to be equal if they have the exact same path, and * all the properties are equal too. */ @Override public boolean equals(Object obj) { if( obj == this ) return true; if( obj instanceof NodeImpl ) { NodeImpl ni = (NodeImpl) obj; if( !ni.getInternalPath().equals(getInternalPath()) ) return false; if( !ni.m_session.getWorkspace().getName().equals(m_session.getWorkspace().getName()) ) return false; // All tests have succeeded return true; } return false; } @Override protected void preSave() throws RepositoryException { super.preSave(); } /** * Checks the mandatory properties for this Nodetype and throws a ConstraintViolationException * if it's not existing. * * @param nt * @throws RepositoryException */ void checkMandatoryProperties(QNodeType nt) throws RepositoryException { for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isMandatory() && !hasProperty(pd.getQName()) ) { throw new ConstraintViolationException("Node "+getInternalPath()+" is missing property "+pd.getQName()); } } } /* ============================================================ * * Mixins * */ public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { ValueFactory vf = m_session.getValueFactory(); NodeType mixin = getNodeTypeManager().getNodeType(mixinName); if( !mixin.isMixin() ) throw new NoSuchNodeTypeException("Type "+mixinName+" is not a mixin type!"); if( isLockedWithoutToken() ) throw new LockException( "Node is locked, so cannot add new mixin types." ); if( !isCheckedOut() ) throw new VersionException( "Node is not checked out, so cannot add new mixin types."); boolean oldsuper = m_session.setSuper( true ); try { Property p; p = getProperty(Q_JCR_MIXINTYPES); Value[] v = p.getValues(); Value[] newval = new Value[v.length+1]; for( int i = 0; i < v.length; i++ ) { newval[i] = v[i]; } newval[newval.length-1] = vf.createValue(mixinName,PropertyType.NAME); PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, newval, PropertyType.NAME ); pi.enterState(ItemState.UPDATED); } catch( PathNotFoundException e ) { Value[] values = new Value[] { vf.createValue(mixinName,PropertyType.NAME) }; PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, values, PropertyType.NAME ); pi.enterState(ItemState.NEW); } finally { m_session.setSuper( oldsuper ); } //autoCreateProperties(); } public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException { if( isLocked() ) return false; NodeType nt = getNodeTypeManager().getNodeType( mixinName ); if( !nt.isMixin() ) { throw new NoSuchNodeTypeException(mixinName+" is not a mixin type!"); } if( hasMixinType(nt.getName()) ) { return false; } if( !isCheckedOut() ) return false; // FIXME: This is a bit complicated and slow. if( mixinName.equals("mix:versionable") && m_session.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false") ) return false; return true; } boolean hasMixinType(String mixinType) { try { Property pi = getProperty( Q_JCR_MIXINTYPES ); for( Value v : pi.getValues() ) { String mixin = v.getString(); if( mixin.equals(mixinType) ) return true; } } catch( RepositoryException e ) {} return false; } public NodeType[] getMixinNodeTypes() throws RepositoryException { ArrayList<NodeType> mixinTypes = new ArrayList<NodeType>(); // // If there are no mixin types, then let's just return an empty array. // try { Property p = getProperty( Q_JCR_MIXINTYPES ); for( Value v : p.getValues() ) { NodeType nt = m_session.getWorkspace().getNodeTypeManager().getNodeType( v.getString() ); mixinTypes.add( nt ); } } catch( RepositoryException e ) {} return mixinTypes.toArray( new NodeType[0] ); } public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( isLocked() ) throw new LockException("Node locked, cannot remove mixin"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); Property mixinTypes = getProperty("jcr:mixinTypes"); Value[] vals = mixinTypes.getValues(); boolean found = false; for( int i = 0; i < vals.length; i++ ) { if( vals[i].getString().equals(mixinName) ) { vals[i] = null; found = true; } } if( found ) { mixinTypes.setValue( vals ); } else { throw new NoSuchNodeTypeException("No such mixin type to remove: "+mixinName); } } /*============================================================================== * * Locking * */ LockManager m_lockManager = LockManager.getInstance(getSession().getWorkspace()); public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { if( !hasMixinType("mix:lockable") ) throw new UnsupportedRepositoryOperationException("This node is not lockable: "+getInternalPath()); if( getState() == ItemState.NEW ) throw new LockException("This node has no persistent state"); if( isModified() ) throw new InvalidItemStateException("You may only lock Nodes which are not currently modified"); if( isDeep && m_lockManager.hasChildLock(getInternalPath()) ) { throw new LockException("A child of this node already holds a lock, so you cannot deep lock this node."); } if( isLocked() ) { throw new LockException("This Node is already locked."); } QLock lock = new QLock( this, isDeep, isSessionScoped ); m_session.addLockToken( lock.getToken() ); boolean isSuper = m_session.setSuper(true); try { setProperty("jcr:lockOwner", lock.getLockOwner()); setProperty("jcr:lockIsDeep", isDeep); } finally { m_session.setSuper(isSuper); } save(); m_lockManager.addLock( lock ); return lock.getLockInstance(m_session); } public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { QLock lock = m_lockManager.getLock( getInternalPath() ); if( lock == null ) throw new LockException("This Node has not been locked."); if( lock.getLockToken(m_session) == null ) throw new LockException("This Session does not own this Lock, so it cannot be unlocked."); if( isModified() ) throw new InvalidItemStateException("This Node must not be modified prior to unlocking"); Property p = getProperty("jcr:lockOwner"); p.remove(); p = getProperty("jcr:lockIsDeep"); p.remove(); m_session.removeLockToken( lock.getLockToken(m_session) ); m_lockManager.removeLock( lock ); lock.invalidate(); save(); } public QLock.Impl getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); // // Must return a clone of the Lock which is particular to this session. // if( li != null ) return li.getLockInstance(m_session); return null; } public boolean holdsLock() throws RepositoryException { QLock li = m_lockManager.getLock( getInternalPath() ); return li != null; } public boolean isLocked() throws RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); return li != null; } /** * Returns true, if this Node is locked (that is, it or it's parents are locked) * but the Session which owns this Session does not hold a token to modify it. * * @return True, if you cannot modify this Node due to missing token. */ protected boolean isLockedWithoutToken() { if( !getInternalPath().isRoot() ) { QLock li = m_lockManager.findLock(getInternalPath()); if( li != null && li.getLockToken(m_session) == null ) { return true; } } return false; } /* ==================================================== * * Versioning * */ public boolean isCheckedOut() throws RepositoryException { try { PropertyImpl p = getProperty(Q_JCR_ISCHECKEDOUT); return p.getBoolean(); } catch(PathNotFoundException e) { // Fine; no property exists. } // // Check if this is a versionable node in the first place. // if( isNodeType( "mix:versionable" ) && !isNew() ) return false; return true; } public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.cancelMerge()"); } public VersionImpl checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException { if( !hasMixinType("mix:versionable") ) { throw new UnsupportedRepositoryOperationException("Node is not mix:versionable (8.2.5)"); } if( !isCheckedOut() ) { return getBaseVersion(); } if( isModified() ) { throw new InvalidItemStateException("Node has unsaved changes (8.2.5)"); } if( hasProperty("jcr:mergeFailed") ) { throw new VersionException("Node has failed merges (8.2.5)"); } // // Phew! Preconditions have been checked. Now, let's get to real business. // boolean isSuper = getSession().setSuper(true); try { VersionHistoryImpl vh = getVersionHistory(); int version = 0; if( !getBaseVersion().getName().equals("jcr:rootVersion") ) version = Integer.parseInt( getBaseVersion().getName() ); VersionImpl v = (VersionImpl) vh.addNode( Integer.toString( ++version ), "nt:version" ); if(!hasProperty("nt:versionHistory")) setProperty( "nt:versionHistory", vh ); - + + // + // Set up version properties + // v.setProperty( JCR_PREDECESSORS, getProperty(JCR_PREDECESSORS).getValues() ); - //v.addMixin( "mix:referenceable" ); v.setProperty( "jcr:uuid", UUID.randomUUID().toString() ); v.setProperty( JCR_SUCCESSORS, new Value[0], PropertyType.REFERENCE ); setProperty( JCR_PREDECESSORS, new Value[0], PropertyType.REFERENCE ); PropertyImpl preds = v.getProperty(JCR_PREDECESSORS); + // + // Set up successors and predecessors + // for( Value val : preds.getValues() ) { String uuid = val.getString(); Node pred = m_session.getNodeByUUID(uuid); Value[] s = pred.getProperty( JCR_SUCCESSORS ).getValues(); List<Value> successorList = new ArrayList<Value>(); successorList.addAll( Arrays.asList(s) ); successorList.add( m_session.getValueFactory().createValue(v) ); pred.setProperty( JCR_SUCCESSORS, successorList.toArray(s) ); } setProperty( "jcr:baseVersion", v ); setProperty( "jcr:isCheckedOut", false ); // // Store the contents into the frozen node of the Version node. // NodeImpl fn = v.addNode("jcr:frozenNode","nt:frozenNode"); for( LazyPropertyIteratorImpl pi = getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE ) ) { fn.setProperty( "jcr:frozenPrimaryType", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_UUID ) ) { fn.setProperty( "jcr:frozenUuid", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_MIXINTYPES ) ) { fn.setProperty( "jcr:frozenMixinTypes", p.getValues() ); } else if( p.getDefinition().getOnParentVersion() == OnParentVersionAction.COPY ) { // FIXME: SHould probably deal with the others as well. if( p.getDefinition().isMultiple() ) { fn.setProperty( p.getName(), p.getValues() ); } else { fn.setProperty( p.getName(), p.getValue() ); } } } + for( NodeIterator ni = getNodes(); ni.hasNext(); ) + { + NodeImpl n = (NodeImpl)ni.nextNode(); + + switch( n.getDefinition().getOnParentVersion() ) + { + case OnParentVersionAction.ABORT: + throw new VersionException("Child node "+n.getPath()+" prevented versioning, as it has OnParentVersionAction ABORT"); + + case OnParentVersionAction.COMPUTE: + throw new RepositoryException("COMPUTE child nodes not supported for path "+getPath()); + + case OnParentVersionAction.COPY: + m_session.getWorkspace().copy(m_session, n.getPath(), fn.getPath(), false); + break; + + case OnParentVersionAction.IGNORE: + // Ignore, yay + break; + + case OnParentVersionAction.INITIALIZE: + throw new RepositoryException("INITIALIZE child nodes not supported for path "+getPath()); + + case OnParentVersionAction.VERSION: + + if( n.hasMixinType("mix:versionable") ) + { + NodeImpl vc = fn.addNode( n.getName(), "nt:versionedChild" ); + vc.setProperty("jcr:childVersionHistory", n.getVersionHistory()); + } + else + { + // FIXME: Does not stop at versionable nodes + m_session.getWorkspace().copy(m_session, n.getPath(), fn.getPath()+"/"+n.getName(), true); + } + + break; + } + } + vh.save(); save(); // FIXME: Here. return v; } finally { getSession().setSuper( isSuper ); } } public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException { - if( isCheckedOut() ) return; // Nothing happens - if( !isNodeType( "mix:versionable" ) ) throw new UnsupportedRepositoryOperationException("Not versionable (8.2.6)"); + if( isCheckedOut() ) return; // Nothing happens + boolean isSuper = getSession().setSuper( true ); try { setProperty( "jcr:isCheckedOut", true ); // // We don't support multiple predecessors, so this is okay, I think. // setProperty( JCR_PREDECESSORS, new ValueImpl[] { getSession().getValueFactory().createValue( getBaseVersion() ) } ); setProperty( JCR_SUCCESSORS, new ValueImpl[0] ); // // Persist immediately. // save(); } finally { getSession().setSuper( isSuper ); } } public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.doneMerge()"); } public VersionImpl getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException { - String bvUuid = getProperty( Q_JCR_BASEVERSION ).getString(); + try + { + String bvUuid = getProperty( Q_JCR_BASEVERSION ).getString(); - return (VersionImpl) getSession().getNodeByUUID( bvUuid ); + return (VersionImpl) getSession().getNodeByUUID( bvUuid ); + } + catch( PathNotFoundException e ) + { + throw new UnsupportedRepositoryOperationException("This is not a versioned node."); + } } public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restore(Version version, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restore(Version version, String relPath, boolean removeExisting) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restoreByLabel(String versionLabel, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws NoSuchWorkspaceException, AccessDeniedException, MergeException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } } diff --git a/src/java/org/priha/util/ChangeStore.java b/src/java/org/priha/util/ChangeStore.java index 5bbb56a..5e06286 100644 --- a/src/java/org/priha/util/ChangeStore.java +++ b/src/java/org/priha/util/ChangeStore.java @@ -1,437 +1,437 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.util.*; import org.priha.core.ItemImpl; import org.priha.core.ItemState; import org.priha.core.PropertyImpl; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.ValueContainer; /** * Provides a list of changes, which can be both played back * one by one, as well as searched rapidly. * <p> * Internally, this class stores both a List of Change objects, * as well as a HashMap pointing at the latest change. It can be * iterated both forwards (using peek() and remove() and iterator()) as well * as backwards (using values()). * <p> * In addition, it stores a separate reference to all the changes relating * to a particular parent path (making it fairly fast to filter based on a path). */ public class ChangeStore implements Iterable<ChangeStore.Change> { private ArrayList<Change> m_changes = new ArrayList<Change>(); private HashMap<Path,Change> m_latest = new HashMap<Path,Change>(); private HashMap<Path,List<Change>> m_childChanges = new HashMap<Path,List<Change>>(); /** * Create a ChangeStore without the HashMap. */ public ChangeStore() {} /** * Returns the newest ItemImpl that corresponds to the Path given. * * @param path Path to search for * @return Newest Item or null, if no such thing is found. */ public ItemImpl getLatestItem( Path path ) { Change c = getLatestChange( path ); if( c != null ) return c.getItem(); return null; } /** * Finds the latest change. * * @param path Path to search for * @return The Change or null, if no such thing found. */ public Change getLatestChange( Path path ) { Change c = m_latest.get( path ); return c; } /** * Get all the latest changes, ignoring any duplicate changes. * * @return A list of latest changes. */ public List<Change> getLatestChanges() { ArrayList<Change> changes = new ArrayList<Change>(); changes.addAll( m_latest.values() ); return changes; } /** * Returns a list of Changes filtered by a parent path. * * @param parent The path to filter against * @return A list of Changes. */ public List<Change> getLatestChangesForParent( Path parent ) { ArrayList<Change> changes = new ArrayList<Change>(); List<Change> c = m_childChanges.get(parent); if( c != null ) changes.addAll( c ); return changes; } /** * Adds a new Item with given ItemState to the end of the Change List. * * @param newState New state * @param ii The Item */ public void add( ItemState newState, ItemImpl ii ) { Change c = new Change( newState, ii ); add( c ); } /** * Adds a whole Change object at the end of the Change List. * * @param c The Change to add * @return True, at the moment. */ public boolean add( Change c ) { if( c.getState() == ItemState.UNDEFINED ) { dump(); throw new IllegalStateException("You cannot add an UNDEFINED Item "+c.getItem().getInternalPath()); } m_changes.add(c); m_latest.put( c.getPath(), c ); if( !c.getPath().isRoot() ) { try { List<Change> pc = m_childChanges.get( c.getPath().getParentPath() ); if( pc == null ) { pc = new ArrayList<Change>(); m_childChanges.put( c.getPath().getParentPath(), pc ); } pc.add( c ); } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot add path "+c.getPath()); } } return true; } /** * Gets the first change from the change list. Returns null, if there are no more * changes. * * @return The first change from the list, or null, if the list was empty. */ public Change peek() { if( m_changes.size() > 0 ) return m_changes.get(0); return null; } /** * Removes the first change from the change list. * * @return The first change from the list, or null, if the list was empty. */ public Change remove() { Change c = null; if( m_changes.size() > 0 ) { c = m_changes.remove(0); m_latest.remove( c.getPath() ); if( !c.getPath().isRoot() ) { try { Path parent = c.getPath().getParentPath(); List<Change> pc = m_childChanges.get( parent ); pc.remove( c ); // FIXME: SLow. if( pc.isEmpty() ) { m_childChanges.remove( parent ); } } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot remove "+c.getPath()); } } } return c; } /** * Clears the changes. * * @return The number of changes removed from the queue. */ public int clear() { int numChanges = m_changes.size(); m_changes.clear(); m_latest.clear(); m_childChanges.clear(); return numChanges; } /** * Returns a forward iterator for the Changes. * * @return A forward iterator for the Changes. */ public Iterator<Change> iterator() { return new ForwardIterator(); } /** * Returns a <b>backward</b> iterator for the Items in the change list. The first * value you get is the newest value on the stack. This means * that the iteration order for iterator() and values() is reversed. * * @return A reverse iterator for the values. */ public Iterator<ItemImpl> values() { return new ItemIterator(); } /** * Returns true, if there are no changes. * * @return True, if there are no changes. */ public final boolean isEmpty() { return m_changes.isEmpty(); } /** * Implements a backwards iterator through the Items in the list. */ private class ItemIterator implements Iterator<ItemImpl> { int m_position; protected ItemIterator() { m_position = m_changes.size()-1; } public final boolean hasNext() { return m_position > 0; } public final ItemImpl next() { return m_changes.get(m_position--).getItem(); } public void remove() { throw new UnsupportedOperationException(); } } private class ForwardIterator implements Iterator<Change> { int m_position; protected ForwardIterator() { m_position = 0; } public final boolean hasNext() { return m_position < m_changes.size(); } public final Change next() { return m_changes.get(m_position++); } public void remove() { if( m_position == 0 ) throw new IllegalStateException(); Change c = m_changes.remove( --m_position ); m_latest.remove( c.getPath() ); if( !c.getPath().isRoot() ) { try { Path parent = c.getPath().getParentPath(); List<Change> pc = m_childChanges.get( parent ); pc.remove( c ); // FIXME: SLow. if( pc.isEmpty() ) { m_childChanges.remove( parent ); } } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot remove "+c.getPath()); } } } } /** * Dumps the store contents for debugging to System.out. */ public void dump() { System.out.println("DUMP OF CHANGESTORE @"+Integer.toHexString(this.hashCode())); System.out.println(this); } /** * Outputs a human-readable description of the contents of the ChangeStore. * * @return Somethign human-readable. */ public String toString() { StringBuilder sb = new StringBuilder(); for( Change c : this ) { sb.append( c.getState().toString() + ": " + c.getPath() + ": " + c.getItem() + "\n" ); } return sb.toString(); } /** * Stores a single change. */ public static final class Change { private ItemState m_state; private ItemImpl m_item; private Path m_path; private ValueContainer m_valueContainer; /** * Create a new Change for the given ItemState and item. If the * Item is a property, also the Value is copied internally. * * @param newState The new state * @param item The item */ public Change( ItemState newState, ItemImpl item ) { m_state = newState; m_item = item; m_path = item.getInternalPath(); if( !item.isNode() ) { m_valueContainer = ((PropertyImpl)item).getValueContainer(); - if( m_valueContainer.isEmpty() ) throw new IllegalArgumentException("Null value in valuecontainer for "+m_path); + if( m_valueContainer.isEmpty() && newState != ItemState.REMOVED ) throw new IllegalArgumentException("Null value in valuecontainer for "+m_path); } } /** * Returns the Item for this Change. * * @return The Item. */ public final ItemImpl getItem() { return m_item; } /** * Returns the ItemState for this Change. * * @return The ItemState. */ public final ItemState getState() { return m_state; } /** * Returns the Path for this Change. * * @return The Path. */ public final Path getPath() { return m_path; } /** * Return the ValueContainer for the Change. * * @return The ValueContainer, or null, if the Change concerned a Node. */ public final ValueContainer getValue() { return m_valueContainer; } } } diff --git a/src/java/org/priha/version/VersionHistoryImpl.java b/src/java/org/priha/version/VersionHistoryImpl.java index a65fafa..14a8016 100644 --- a/src/java/org/priha/version/VersionHistoryImpl.java +++ b/src/java/org/priha/version/VersionHistoryImpl.java @@ -1,206 +1,305 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.version; import java.util.ArrayList; import java.util.List; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionIterator; import org.priha.core.JCRConstants; import org.priha.core.SessionImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.path.Path; public class VersionHistoryImpl extends AbstractVersion implements VersionHistory { + private static final String JCR_VERSIONLABELS = "jcr:versionLabels"; + public static VersionHistoryImpl getInstance( SessionImpl session, Path path ) throws RepositoryException { QNodeTypeManager nt = QNodeTypeManager.getInstance(); QNodeType versionType = nt.getNodeType(JCRConstants.Q_NT_VERSIONHISTORY); QNodeDefinition nDef = versionType.findNodeDefinition( path.getLastComponent() ); return new VersionHistoryImpl( session, path, versionType, nDef, true ); } public VersionHistoryImpl(SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean initDefaults) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super(session, path, primaryType, nDef, initDefaults); } - public void addVersionLabel(String arg0, String arg1, boolean arg2) throws VersionException, RepositoryException + /** + * Adds a Version Label. The labels are stored as Properties of the VersionHistory's "jcr:versionLabels" Node. + * Each Property is named + */ + public void addVersionLabel(String versionName, String label, boolean moveLabel) throws VersionException, RepositoryException { - throw new UnsupportedRepositoryOperationException("addVersionLabel()"); + SessionImpl session = m_session.getRepository().superUserLogin( m_session.getWorkspace().getName() ); + + try + { + VersionHistory me = (VersionHistory)session.getItem(getInternalPath()); + + if( me.hasVersionLabel(label) && !moveLabel ) + { + throw new VersionException("Attempted to add a new label to a versionhistory, but it already existed."); + } + + Node labels; + + try + { + labels = me.getNode(JCR_VERSIONLABELS); + } + catch( PathNotFoundException e ) + { + labels = me.addNode(JCR_VERSIONLABELS); + } + + String uuid = me.getVersion(versionName).getUUID(); + + labels.setProperty( label, uuid ); + + session.save(); + } + finally + { + session.logout(); + } } public VersionIterator getAllVersions() throws RepositoryException { ArrayList<Version> allVersions = new ArrayList<Version>(); Version v = getRootVersion(); while( v != null ) { allVersions.add( v ); Version[] succs = v.getSuccessors(); if( succs.length == 0 ) break; v = succs[0]; // Priha does not support multiple successors. } return new VersionIteratorImpl(allVersions); } public Version getRootVersion() throws RepositoryException { return getVersion("jcr:rootVersion"); } public Version getVersion(String versionName) throws VersionException, RepositoryException { Path p = VersionManager.getVersionStoragePath( getVersionableUUID() ).resolve(getSession(),versionName); if( m_session.itemExists(p) ) { return (Version) m_session.getItem( p ); } throw new VersionException("Node "+getPath()+" has no such version "+versionName); } public Version getVersionByLabel(String versionLabel) throws RepositoryException { - Node n = getNode("jcr:versionLabels"); + Node n = getNode(JCR_VERSIONLABELS); Property p = n.getProperty(versionLabel); String uuid = p.getString(); return (Version)m_session.getNodeByUUID(uuid); } public String[] getVersionLabels() throws RepositoryException { ArrayList<String> result = new ArrayList<String>(); - Node n = getNode("jcr:versionLabels"); - for( PropertyIterator pi = n.getProperties(); pi.hasNext(); ) + try { - Property p = pi.nextProperty(); + Node n = getNode(JCR_VERSIONLABELS); + + for( PropertyIterator pi = n.getProperties(); pi.hasNext(); ) + { + Property p = pi.nextProperty(); - result.add( p.getName() ); + if( p.getName().contains(":") ) continue; // Let's skip all namespaced beasts here. + + result.add( p.getName() ); + } } + catch( PathNotFoundException e ) {} return result.toArray(new String[result.size()]); } - public String[] getVersionLabels(Version arg0) throws VersionException, RepositoryException + public String[] getVersionLabels(Version v) throws VersionException, RepositoryException { - throw new UnsupportedRepositoryOperationException("getVersionLabels(Version)"); + ArrayList<String> res = new ArrayList<String>(); + + try + { + if( !v.getContainingHistory().getUUID().equals(getUUID()) ) + { + throw new VersionException("This version does not belong to this history."); + } + } + catch( UnsupportedRepositoryOperationException e ) + { + } + + try + { + String uuid = v.getUUID(); + + Node labels = getNode(JCR_VERSIONLABELS); + + for( PropertyIterator pi = labels.getProperties(); pi.hasNext(); ) + { + Property p = pi.nextProperty(); + + if( p.getName().contains(":") ) continue; // Let's skip all namespaced beasts here. + + if( p.getValue().getString().equals(uuid) ) + res.add( p.getName() ); + } + } + catch( PathNotFoundException e ) {} + + return res.toArray(new String[0]); } public String getVersionableUUID() throws RepositoryException { return getProperty("jcr:versionableUuid").getString(); } public boolean hasVersionLabel(String label) throws RepositoryException { String[] labels = getVersionLabels(); for( String s : labels ) { if( s.equals(label) ) return true; } return false; } public boolean hasVersionLabel(Version version, String label) throws VersionException, RepositoryException { String[] labels = getVersionLabels(version); for( String s : labels ) { if( s.equals(label) ) return true; } return false; } public void removeVersion(String arg0) throws ReferentialIntegrityException, AccessDeniedException, UnsupportedRepositoryOperationException, VersionException, RepositoryException { throw new UnsupportedRepositoryOperationException("removeVersion(String)"); } @Override public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { System.out.println("VersionHistory.remove("+getPath()+")"); // First, we'll remove all the children List<Version> toberemoved = new ArrayList<Version>(); VersionIterator i = getAllVersions(); while( i.hasNext() ) { Version v = i.nextVersion(); toberemoved.add( v ); } for( Version v : toberemoved ) { System.out.println(" Removing version "+v.getName()); try { v.remove(); } catch(Exception ex) { ex.printStackTrace(); } } System.out.println("Remove version history "+this); // Then we remove the Node itself. super.remove(); } - public void removeVersionLabel(String arg0) throws VersionException, RepositoryException + public void removeVersionLabel(String label) throws VersionException, RepositoryException { - throw new UnsupportedRepositoryOperationException("removeVersionLabel(String)"); + SessionImpl session = m_session.getRepository().superUserLogin(m_session.getWorkspace().getName()); + + try + { + // + // Any PathNotFoundException from these gets turned into a VersionException + // + VersionHistory me = (VersionHistory) session.getItem(getInternalPath()); + + Node labels = me.getNode(JCR_VERSIONLABELS); + + Property p = labels.getProperty(label); + + p.remove(); + + session.save(); + } + catch( PathNotFoundException e ) + { + throw new VersionException("Label "+label+" does not exist for this version history."); + } + finally + { + session.logout(); + } } }
jalkanen/Priha
750f3d097833b4d387f97e17d264feb63b25e923
Introduced AbstractVersion; slight improvements in versioning code.
diff --git a/.checkstyle b/.checkstyle index a9a018b..b1d67dc 100644 --- a/.checkstyle +++ b/.checkstyle @@ -1,24 +1,24 @@ <?xml version="1.0" encoding="UTF-8"?> <fileset-config file-format-version="1.2.0" simple-config="true"> <local-check-config name="Priha checkstyle configuration" location="internal_config__1261654928515.xml" type="internal" description=""/> - <fileset name="all" enabled="true" check-config-name="Priha checkstyle configuration" local="true"> + <fileset name="all" enabled="true" check-config-name="Janne's coding style" local="false"> <file-match-pattern match-pattern="." include-pattern="true"/> </fileset> <filter name="FilesFromPackage" enabled="true"> <filter-data value="src/java/org/priha/query/aqt"/> <filter-data value="src/java/org/priha/query/aqt/xpath"/> <filter-data value="tests/java"/> <filter-data value="tests/java/org"/> <filter-data value="tests/java/org/priha"/> <filter-data value="tests/java/org/priha/core"/> <filter-data value="tests/java/org/priha/nodetype"/> <filter-data value="tests/java/org/priha/providers"/> <filter-data value="tests/java/org/priha/query"/> <filter-data value="tests/java/org/priha/util"/> <filter-data value="tests/java/org/priha/xml"/> <filter-data value="tests/tck"/> <filter-data value="tests/tck/org"/> <filter-data value="tests/tck/org/apache"/> <filter-data value="src/generated-sources"/> </filter> </fileset-config> diff --git a/.project b/.project index 0b6b75b..22915b3 100644 --- a/.project +++ b/.project @@ -1,23 +1,17 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>priha</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> - <buildCommand> - <name>com.atlassw.tools.eclipse.checkstyle.CheckstyleBuilder</name> - <arguments> - </arguments> - </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> - <nature>com.atlassw.tools.eclipse.checkstyle.CheckstyleNature</nature> </natures> </projectDescription> diff --git a/ChangeLog b/ChangeLog index aeeda30..31df3f2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,518 @@ +2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> + + * Minor changes in the versioning code; introduced AbstractVersion + to catch a bunch of unmodifiable methods. As versioning is + still disabled, no version bump here. + 2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.7.0 * Optimized itemExists() by changing RepositoryProvider interface to allow checking for Properties too. * Optimized ChangeStore by allowing filtering by parent path as well. This greatly improves the efficiency of listing changes to a Node's children or properties. * 0.6.7 * Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 763795a..2024e23 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -426,1905 +426,1913 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public LazyPropertyIteratorImpl getProperties() throws RepositoryException { List<Path> ls = new ArrayList<Path>(); ls.addAll(m_session.m_provider.listProperties(getInternalPath())); return new LazyPropertyIteratorImpl( getSession(), ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); m_cachedUUID = uuid.toString(); pi.loadValue( vfi.createValue( m_cachedUUID ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.enterState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } /** * Returns the UUID for this node. Utilizes an internal cache for the UUID, * so is fast after the first call. */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { if( NO_UUID.equals(m_cachedUUID) && !hasProperty(JCR_UUID) ) throw new UnsupportedRepositoryOperationException(); if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { // OK, so let's fallthrough to the exception throwing part. } } m_cachedUUID = NO_UUID; throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } /** * Returns true, if this Node has a child with the given QName. * * @param name A QName. * @return True, if there is a child by this name. * @throws RepositoryException */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { m_lockManager.removeLock( lock ); } // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { if( srcChildRelPath.indexOf('[') != -1 || hasNode(srcChildRelPath+"[2]" ) ) { // Yes, we are moving a SNS so this needs reordering. Path tmpPath = getInternalPath().resolve( m_session, "priha:tmpmove" ); // First, store the old version m_session.internalMove( srcPath, tmpPath, false ); String childName = srcChildRelPath.replaceAll( "\\[\\d+\\]", "" ); // FIXME: Hackish trick. boolean last = false; if( dstPath == null ) { NodeIterator ni = getNodes(childName); dstPath = getInternalPath().resolve( m_session, childName+"["+ni.getSize()+"]" ); last = true; } int dir; int startIdx; int endIdx; if( srcPath.getLastComponent().getIndex() < dstPath.getLastComponent().getIndex() ) { // When moving forward, the dstPath is not actually the correct index; // we want to place it _before_ the given index. if( !last ) { int idx = dstPath.getLastComponent().getIndex() - 1; // Real last one dstPath = dstPath.getParentPath().resolve( new Path.Component(dstPath.getLastComponent().getQName(),idx) ); } // Moving stuff forwards dir = -1; startIdx = srcPath.getLastComponent().getIndex()+1; endIdx = dstPath.getLastComponent().getIndex()+1; } else { dir = 1; startIdx = srcPath.getLastComponent().getIndex()-1; endIdx = dstPath.getLastComponent().getIndex()-1; } for( int i = startIdx; i != endIdx; i -= dir ) { String oldName = childName + "[" + i + "]"; String newName = childName + "[" + (i + dir) + "]"; System.out.println("Reordering SNS : "+oldName+" to "+newName); Path path1 = getInternalPath().resolve(m_session,oldName); Path newPath = getInternalPath().resolve(m_session,newName); m_session.internalMove( path1, newPath, false ); } m_session.internalMove( tmpPath, dstPath, false ); } else { // // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. // Path p = newOrder.remove(srcIndex); if( dstIndex != -1 ) newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); else newOrder.add(p); } } finally { m_session.setSuper(isSuper); } // // Lock back up // if( lock != null ) { m_lockManager.moveLock( lock, dstPath ); } // // Finish. // enterState( ItemState.UPDATED ); m_childOrder = newOrder; } - private PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException + protected PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ - private PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException + protected PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } if( value == null ) { removeProperty(prop); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); } // FIXME: No rollback support public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { if( getState() == ItemState.NEW ) throw new InvalidItemStateException("Cannot call save on newly added node "+getInternalPath()); internalSave(); } public int compareTo(Node nd) { try { return getPath().compareTo(nd.getPath()); } catch( RepositoryException e ) { return 0; } // FIXME: This should never occur } public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { remove(false); } /** * If isRemoving = true, will remove subnodes without question. */ private void remove(boolean isRemoving) throws VersionException, LockException, ConstraintViolationException, RepositoryException { if( getState() == ItemState.REMOVED ) { // System.out.println(getPath()+" has already been removed"); return; // Die nicely } Path path = getInternalPath(); if( !m_session.m_provider.nodeExistsInRepository( path ) && m_session.m_provider.m_changedItems.getLatestItem(path) == null ) { m_session.m_provider.m_changedItems.dump(); throw new InvalidItemStateException("Item has already been removed by another Session "+getPath()); } if( path.isRoot() || path.equals( JCRConstants.Q_JCR_SYSTEM_PATH ) ) { return; // Refuse to remove } NodeImpl parent = getParent(); NodeType parentType = parent.getPrimaryNodeType(); if( !getSession().isSuper() ) { // Anything from under /jcr:system cannot be deleted by the user if( JCRConstants.Q_JCR_SYSTEM_PATH.isParentOf( path )) return; if( getParent().isLockedWithoutToken() ) throw new LockException("The parent is locked, so you cannot remove it."); if( !parentType.canRemoveItem(getName()) && getParent().getState() != ItemState.REMOVED && !isRemoving ) { throw new ConstraintViolationException("Attempted to delete a mandatory child node:"+getInternalPath()); } } QLock li = m_lockManager.getLock( path ); if( li != null ) m_lockManager.removeLock( li ); // // Remove version history // if( isNodeType( "mix:versionable" ) ) { // // Version histories cannot be removed unless you have a // superuser session. // boolean isSuper = m_session.setSuper(true); try { getVersionHistory().remove(); } catch( UnsupportedRepositoryOperationException e ) { // This may happen if you've just created a Node, then hit remove() on it immediately, since // in that case, we do not have an UUID yet. } finally { m_session.setSuper( isSuper ); } } // // Removal happens in a depth-first manner. // // // Remove children. We do this in a reverse order in order // not to force annoying moves for same-name siblings. It's just faster. // LazyNodeIteratorImpl ndi = (LazyNodeIteratorImpl) getNodes(); ndi.skip( ndi.getSize() ); while( ndi.hasPrevious() ) { NodeImpl nd = ndi.previousNode(); // System.out.println("REMOVING "+nd.getPath()); nd.remove(true); } boolean isSuper = m_session.setSuper(true); // // Remove properties // for( PropertyIterator pit = getProperties(); pit.hasNext(); ) { pit.nextProperty().remove(); } // This is a hack which just resets the state and then adds this to the remove queue. FIXME! // m_state = ItemState.UPDATED; enterState( ItemState.REMOVED ); // // Fix same name siblings, but don't bother if the parent is already removed. // Again, we go for the super session. // try { int myIndex = getInternalPath().getLastComponent().getIndex(); if( !isRemoving ) { for( NodeIterator ni = getParent().getNodes( getName() ); ni.hasNext(); ) { NodeImpl n = (NodeImpl)ni.nextNode(); int siblingIndex = n.getInternalPath().getLastComponent().getIndex(); if( myIndex >= siblingIndex ) continue; Path destPath = new Path(n.getParent().getInternalPath(), new Path.Component(getQName(),siblingIndex-1) ); // System.out.println("Moving "+n+" to "+destPath); // m_session.m_provider.m_changedItems.dump(); getSession().move( n.getInternalPath().toString( m_session ), destPath.toString( m_session ) ); } } } finally { m_session.setSuper(isSuper); } log.finer("Removed "+getPath()); } /** * Locates a PropertyDefinition for the given property name from the array of * the mixintypes and the primary type for this Node. * * @param propertyName The QName of the property to look for * @param multiple Is this a multiproperty or a single property? * @return A valid PropertyDefinition, or null, if it cannot be located. * @throws RepositoryException If mixin node types cannot be determined. */ public QPropertyDefinition findPropertyDefinition(QName propertyName,boolean multiple) throws RepositoryException { QPropertyDefinition qp; // // Mixin types can override the primary type; especially since the // primary type can contain a wildcard. // for( NodeType nt : getMixinNodeTypes() ) { QNodeType qnt = ((QNodeType.Impl)nt).getQNodeType(); qp = qnt.findPropertyDefinition(propertyName, multiple); if( qp != null ) return qp; } return getPrimaryQNodeType().findPropertyDefinition(propertyName, multiple); } /** * Assumes nothing, goes through the properties, makes sure all things are correct. */ public void sanitize() throws RepositoryException { // log.finest("Sanitizing node "+getInternalPath()); if( m_definition == null ) { try { @SuppressWarnings("unused") PropertyImpl primarytype = getProperty( Q_JCR_PRIMARYTYPE ); } catch( Exception e ) { if( getInternalPath().isRoot() ) { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, "nt:unstructured", PropertyType.NAME ); pix.enterState(ItemState.NEW); } else { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, assignChildType( getInternalPath().getLastComponent() ).toString(), PropertyType.NAME ); pix.enterState(ItemState.NEW); } } if( getParent() != null ) { QNodeType mytype = getPrimaryQNodeType(); m_definition = getParent().getPrimaryQNodeType().findNodeDefinition( mytype.getQName() ); } else { // FIXME: Not correct m_definition = QNodeTypeManager.getInstance().findNodeDefinition( Q_NT_UNSTRUCTURED ); } if( m_definition == null ) { throw new RepositoryException("Cannot assign a node definition for "+getInternalPath()); } } // autoCreateProperties(); QNodeType mytype = getPrimaryQNodeType(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl pi = (PropertyImpl)i.next(); if( pi.getDefinition() == null ) { QPropertyDefinition pd = mytype.findPropertyDefinition( pi.getQName(), false ); // FIXME: Really? pi.m_definition = pd.new Impl(m_session); // FIXME: Inoptimal } } } /** * We consider nodes to be equal if they have the exact same path, and * all the properties are equal too. */ @Override public boolean equals(Object obj) { if( obj == this ) return true; if( obj instanceof NodeImpl ) { NodeImpl ni = (NodeImpl) obj; if( !ni.getInternalPath().equals(getInternalPath()) ) return false; if( !ni.m_session.getWorkspace().getName().equals(m_session.getWorkspace().getName()) ) return false; // All tests have succeeded return true; } return false; } @Override protected void preSave() throws RepositoryException { super.preSave(); } /** * Checks the mandatory properties for this Nodetype and throws a ConstraintViolationException * if it's not existing. * * @param nt * @throws RepositoryException */ void checkMandatoryProperties(QNodeType nt) throws RepositoryException { for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isMandatory() && !hasProperty(pd.getQName()) ) { throw new ConstraintViolationException("Node "+getInternalPath()+" is missing property "+pd.getQName()); } } } /* ============================================================ * * Mixins * */ public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { ValueFactory vf = m_session.getValueFactory(); NodeType mixin = getNodeTypeManager().getNodeType(mixinName); if( !mixin.isMixin() ) throw new NoSuchNodeTypeException("Type "+mixinName+" is not a mixin type!"); if( isLockedWithoutToken() ) throw new LockException( "Node is locked, so cannot add new mixin types." ); if( !isCheckedOut() ) throw new VersionException( "Node is not checked out, so cannot add new mixin types."); boolean oldsuper = m_session.setSuper( true ); try { Property p; p = getProperty(Q_JCR_MIXINTYPES); Value[] v = p.getValues(); Value[] newval = new Value[v.length+1]; for( int i = 0; i < v.length; i++ ) { newval[i] = v[i]; } newval[newval.length-1] = vf.createValue(mixinName,PropertyType.NAME); PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, newval, PropertyType.NAME ); pi.enterState(ItemState.UPDATED); } catch( PathNotFoundException e ) { Value[] values = new Value[] { vf.createValue(mixinName,PropertyType.NAME) }; PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, values, PropertyType.NAME ); pi.enterState(ItemState.NEW); } finally { m_session.setSuper( oldsuper ); } //autoCreateProperties(); } public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException { if( isLocked() ) return false; NodeType nt = getNodeTypeManager().getNodeType( mixinName ); if( !nt.isMixin() ) { throw new NoSuchNodeTypeException(mixinName+" is not a mixin type!"); } if( hasMixinType(nt.getName()) ) { return false; } if( !isCheckedOut() ) return false; // FIXME: This is a bit complicated and slow. if( mixinName.equals("mix:versionable") && m_session.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false") ) return false; return true; } boolean hasMixinType(String mixinType) { try { Property pi = getProperty( Q_JCR_MIXINTYPES ); for( Value v : pi.getValues() ) { String mixin = v.getString(); if( mixin.equals(mixinType) ) return true; } } catch( RepositoryException e ) {} return false; } public NodeType[] getMixinNodeTypes() throws RepositoryException { ArrayList<NodeType> mixinTypes = new ArrayList<NodeType>(); // // If there are no mixin types, then let's just return an empty array. // try { Property p = getProperty( Q_JCR_MIXINTYPES ); for( Value v : p.getValues() ) { NodeType nt = m_session.getWorkspace().getNodeTypeManager().getNodeType( v.getString() ); mixinTypes.add( nt ); } } catch( RepositoryException e ) {} return mixinTypes.toArray( new NodeType[0] ); } public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( isLocked() ) throw new LockException("Node locked, cannot remove mixin"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); Property mixinTypes = getProperty("jcr:mixinTypes"); Value[] vals = mixinTypes.getValues(); boolean found = false; for( int i = 0; i < vals.length; i++ ) { if( vals[i].getString().equals(mixinName) ) { vals[i] = null; found = true; } } if( found ) { mixinTypes.setValue( vals ); } else { throw new NoSuchNodeTypeException("No such mixin type to remove: "+mixinName); } } /*============================================================================== * * Locking * */ LockManager m_lockManager = LockManager.getInstance(getSession().getWorkspace()); public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { if( !hasMixinType("mix:lockable") ) throw new UnsupportedRepositoryOperationException("This node is not lockable: "+getInternalPath()); if( getState() == ItemState.NEW ) throw new LockException("This node has no persistent state"); if( isModified() ) throw new InvalidItemStateException("You may only lock Nodes which are not currently modified"); if( isDeep && m_lockManager.hasChildLock(getInternalPath()) ) { throw new LockException("A child of this node already holds a lock, so you cannot deep lock this node."); } if( isLocked() ) { throw new LockException("This Node is already locked."); } QLock lock = new QLock( this, isDeep, isSessionScoped ); m_session.addLockToken( lock.getToken() ); - setProperty("jcr:lockOwner", lock.getLockOwner()); - setProperty("jcr:lockIsDeep", isDeep); + boolean isSuper = m_session.setSuper(true); + try + { + setProperty("jcr:lockOwner", lock.getLockOwner()); + setProperty("jcr:lockIsDeep", isDeep); + } + finally + { + m_session.setSuper(isSuper); + } save(); m_lockManager.addLock( lock ); return lock.getLockInstance(m_session); } public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { QLock lock = m_lockManager.getLock( getInternalPath() ); if( lock == null ) throw new LockException("This Node has not been locked."); if( lock.getLockToken(m_session) == null ) throw new LockException("This Session does not own this Lock, so it cannot be unlocked."); if( isModified() ) throw new InvalidItemStateException("This Node must not be modified prior to unlocking"); Property p = getProperty("jcr:lockOwner"); p.remove(); p = getProperty("jcr:lockIsDeep"); p.remove(); m_session.removeLockToken( lock.getLockToken(m_session) ); m_lockManager.removeLock( lock ); lock.invalidate(); save(); } public QLock.Impl getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); // // Must return a clone of the Lock which is particular to this session. // if( li != null ) return li.getLockInstance(m_session); return null; } public boolean holdsLock() throws RepositoryException { QLock li = m_lockManager.getLock( getInternalPath() ); return li != null; } public boolean isLocked() throws RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); return li != null; } /** * Returns true, if this Node is locked (that is, it or it's parents are locked) * but the Session which owns this Session does not hold a token to modify it. * * @return True, if you cannot modify this Node due to missing token. */ protected boolean isLockedWithoutToken() { if( !getInternalPath().isRoot() ) { QLock li = m_lockManager.findLock(getInternalPath()); if( li != null && li.getLockToken(m_session) == null ) { return true; } } return false; } /* ==================================================== * * Versioning * */ public boolean isCheckedOut() throws RepositoryException { try { PropertyImpl p = getProperty(Q_JCR_ISCHECKEDOUT); return p.getBoolean(); } catch(PathNotFoundException e) { // Fine; no property exists. } // // Check if this is a versionable node in the first place. // if( isNodeType( "mix:versionable" ) && !isNew() ) return false; return true; } public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.cancelMerge()"); } public VersionImpl checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException { if( !hasMixinType("mix:versionable") ) { throw new UnsupportedRepositoryOperationException("Node is not mix:versionable (8.2.5)"); } if( !isCheckedOut() ) { return getBaseVersion(); } if( isModified() ) { throw new InvalidItemStateException("Node has unsaved changes (8.2.5)"); } if( hasProperty("jcr:mergeFailed") ) { throw new VersionException("Node has failed merges (8.2.5)"); } // // Phew! Preconditions have been checked. Now, let's get to real business. // boolean isSuper = getSession().setSuper(true); try { VersionHistoryImpl vh = getVersionHistory(); int version = 0; if( !getBaseVersion().getName().equals("jcr:rootVersion") ) version = Integer.parseInt( getBaseVersion().getName() ); VersionImpl v = (VersionImpl) vh.addNode( Integer.toString( ++version ), "nt:version" ); if(!hasProperty("nt:versionHistory")) setProperty( "nt:versionHistory", vh ); v.setProperty( JCR_PREDECESSORS, getProperty(JCR_PREDECESSORS).getValues() ); - v.addMixin( "mix:referenceable" ); + //v.addMixin( "mix:referenceable" ); v.setProperty( "jcr:uuid", UUID.randomUUID().toString() ); v.setProperty( JCR_SUCCESSORS, new Value[0], PropertyType.REFERENCE ); setProperty( JCR_PREDECESSORS, new Value[0], PropertyType.REFERENCE ); PropertyImpl preds = v.getProperty(JCR_PREDECESSORS); for( Value val : preds.getValues() ) { String uuid = val.getString(); Node pred = m_session.getNodeByUUID(uuid); Value[] s = pred.getProperty( JCR_SUCCESSORS ).getValues(); List<Value> successorList = new ArrayList<Value>(); successorList.addAll( Arrays.asList(s) ); successorList.add( m_session.getValueFactory().createValue(v) ); pred.setProperty( JCR_SUCCESSORS, successorList.toArray(s) ); } setProperty( "jcr:baseVersion", v ); setProperty( "jcr:isCheckedOut", false ); // // Store the contents into the frozen node of the Version node. // NodeImpl fn = v.addNode("jcr:frozenNode","nt:frozenNode"); for( LazyPropertyIteratorImpl pi = getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE ) ) { fn.setProperty( "jcr:frozenPrimaryType", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_UUID ) ) { fn.setProperty( "jcr:frozenUuid", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_MIXINTYPES ) ) { fn.setProperty( "jcr:frozenMixinTypes", p.getValues() ); } else if( p.getDefinition().getOnParentVersion() == OnParentVersionAction.COPY ) { // FIXME: SHould probably deal with the others as well. if( p.getDefinition().isMultiple() ) { fn.setProperty( p.getName(), p.getValues() ); } else { fn.setProperty( p.getName(), p.getValue() ); } } } vh.save(); save(); // FIXME: Here. return v; } finally { getSession().setSuper( isSuper ); } } public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException { if( isCheckedOut() ) return; // Nothing happens if( !isNodeType( "mix:versionable" ) ) throw new UnsupportedRepositoryOperationException("Not versionable (8.2.6)"); boolean isSuper = getSession().setSuper( true ); try { setProperty( "jcr:isCheckedOut", true ); // // We don't support multiple predecessors, so this is okay, I think. // setProperty( JCR_PREDECESSORS, new ValueImpl[] { getSession().getValueFactory().createValue( getBaseVersion() ) } ); setProperty( JCR_SUCCESSORS, new ValueImpl[0] ); // // Persist immediately. // save(); } finally { getSession().setSuper( isSuper ); } } public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.doneMerge()"); } public VersionImpl getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException { String bvUuid = getProperty( Q_JCR_BASEVERSION ).getString(); return (VersionImpl) getSession().getNodeByUUID( bvUuid ); } public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restore(Version version, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restore(Version version, String relPath, boolean removeExisting) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restoreByLabel(String versionLabel, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws NoSuchWorkspaceException, AccessDeniedException, MergeException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } } diff --git a/src/java/org/priha/core/ProviderManager.java b/src/java/org/priha/core/ProviderManager.java index cd23c8a..6cec6cc 100644 --- a/src/java/org/priha/core/ProviderManager.java +++ b/src/java/org/priha/core/ProviderManager.java @@ -1,671 +1,671 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009' Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import javax.jcr.version.VersionException; import org.priha.core.values.QNameValue; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.RepositoryProvider; import org.priha.providers.StoreTransaction; import org.priha.providers.ValueContainer; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * This is a front-end class for managing multiple providers * for a single repository. * <p> * The ProviderManager is a singleton per Repository. */ public class ProviderManager implements ItemStore { private HashMap<String,ProviderInfo> m_workspaceAccess; private ProviderInfo[] m_providers; private RepositoryImpl m_repository; private Logger log = Logger.getLogger(ProviderManager.class.getName()); private String m_defaultWorkspaceName; public ProviderManager( RepositoryImpl repository ) throws ConfigurationException { m_repository = repository; initialize(); } public static final String PROP_PRIHA_PROVIDERS = "priha.providers"; public static final String PROP_PRIHA_PROVIDER_PREFIX = "priha.provider."; public static final String DEFAULT_PROVIDERLIST = "defaultProvider"; /** * Initializes all the Providers defined in the property file. * * @throws ConfigurationException If the properties would define an illegal configuration. */ private void initialize() throws ConfigurationException { m_workspaceAccess = new HashMap<String,ProviderInfo>(); String providerList = m_repository.getProperty( PROP_PRIHA_PROVIDERS ); if( providerList == null ) throw new ConfigurationException("Required property missing",PROP_PRIHA_PROVIDERS); String[] providers = providerList.split("\\s"); if( providers.length == 0 ) throw new ConfigurationException("Empty property",PROP_PRIHA_PROVIDERS); m_providers = new ProviderInfo[providers.length]; for( int i = 0; i < providers.length; i++ ) { Properties props = filterProperties(m_repository,providers[i]); String className = props.getProperty("class"); if( className == null ) throw new ConfigurationException("Provider "+providers[i]+" does not declare a class name. "+ "There should be a property called '"+PROP_PRIHA_PROVIDER_PREFIX+providers[i]+".class' in your properties."); String workspaceList = props.getProperty("workspaces","default"); String[] workspaces = workspaceList.split("\\s"); if( m_defaultWorkspaceName == null ) { if( workspaces.length == 0 ) throw new ConfigurationException("The first provider ("+providers[i]+") MUST have at least one workspace defined!"); m_defaultWorkspaceName = workspaces[0]; log.fine("Default workspace is set to '"+m_defaultWorkspaceName+"'"); } log.fine("Provider "+i+": "+providers[i]+" is a "+className); RepositoryProvider p = instantiateProvider( m_repository, className, props ); m_providers[i] = new ProviderInfo(); m_providers[i].provider = p; m_providers[i].workspaces = workspaces; m_providers[i].lock = new ReentrantReadWriteLock(); for( String ws : workspaces ) { if( m_workspaceAccess.containsKey(ws) ) throw new ConfigurationException("Workspace "+ws+" is defined multiple times. Very likely you have forgotten to declare a workspace property for a Provider declaration."); m_workspaceAccess.put(ws, m_providers[i]); } } } /** * [0] = /largefiles/ * [1] = / * * "/" => 1 * "/largefiles" => 0 * "/largefiles2" => 1 * "/largefiles/foo" => 0 * * @param p * @return * @throws ConfigurationException */ private final ProviderInfo getProviderInfo(WorkspaceImpl wi, Path p) throws ConfigurationException { ProviderInfo pi = m_workspaceAccess.get(wi.getName()); if( pi != null ) return pi; throw new ConfigurationException("Nonexistant workspace: "+wi.getName()); } /** * Filters the properties set when the Repository was created to find * the property set for a provider. * <p> * Essentially returns a property set where all instances of * <code>priha.provider.[providerName].property = value</code> * are replaced with <code>property = value</code>. * * @param repository The repository from which the properties are read * @param providerName The name to filter with * @return A valid set of Properties. It can also be empty, if there * were no properties defined for this providerName. * @see ProviderManager#instantiateProvider(RepositoryImpl, String, Properties) */ public static Properties filterProperties( RepositoryImpl repository, String providerName ) { Properties props = new Properties(); String prefix = PROP_PRIHA_PROVIDER_PREFIX + providerName + "."; for( Enumeration<String> e = repository.getPropertyNames(); e.hasMoreElements(); ) { String key = e.nextElement(); if( key.startsWith(prefix) ) { String val = repository.getProperty(key); key = key.substring(prefix.length()); props.setProperty(key, val); } } return props; } /** * Instantiates a RepositoryProvider using the given class name and * the properties, and calls its start() method. * * @param rep The RepositoryImpl who will own this RepositoryProvider * @param className The FQN of the class. * @param props A filtered set of Properties * @return A started RepositoryProvider. * * @throws ConfigurationException If the provider cannot be instantiated or the configuration * is faulty. * * @see ProviderManager#filterProperties(RepositoryImpl, String) */ public static RepositoryProvider instantiateProvider(RepositoryImpl rep, String className, Properties props) throws ConfigurationException { Class<?> cl; RepositoryProvider provider; try { cl = Class.forName( className ); provider = (RepositoryProvider) cl.newInstance(); provider.start( rep, props ); } catch (ClassNotFoundException e) { throw new ConfigurationException("Could not find provider class",className); } catch (InstantiationException e) { throw new ConfigurationException("Could not instantiate provider class",className); } catch (IllegalAccessException e) { throw new ConfigurationException("Could not access provider class",className); } return provider; } public void open(Credentials credentials, String workspaceName) throws NoSuchWorkspaceException, RepositoryException { ProviderInfo pi = m_workspaceAccess.get(workspaceName); if( pi == null ) throw new NoSuchWorkspaceException("No such workspace: '"+workspaceName+"'"); try { pi.lock.writeLock().lock(); pi.provider.open( m_repository, credentials, workspaceName ); } finally { pi.lock.writeLock().unlock(); } } private ValueContainer getPropertyValue(WorkspaceImpl impl, Path ptPath) throws RepositoryException { ProviderInfo pi = getProviderInfo(impl,ptPath); try { pi.lock.readLock().lock(); ValueContainer stored = pi.provider.getPropertyValue( impl, ptPath ); return stored; } finally { pi.lock.readLock().unlock(); } } /** * Returns the set of workspaces declared in the config file. * * @throws ConfigurationException */ public Collection<String> listWorkspaces() throws ConfigurationException { return m_workspaceAccess.keySet(); } public List<Path>listNodes(WorkspaceImpl impl, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( impl, path ); try { pi.lock.readLock().lock(); return pi.provider.listNodes( impl, path ); } finally { pi.lock.readLock().unlock(); } } public void close(WorkspaceImpl impl) { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.close( impl ); } finally { pi.lock.writeLock().unlock(); } } } /** * Removes the item at the end of the path. * * @param impl * @param path * @throws RepositoryException */ public void remove(StoreTransaction tx, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); try { pi.lock.writeLock().lock(); pi.provider.remove( tx, path ); } finally { pi.lock.writeLock().unlock(); } } /** * Loads the state of a node from the repository. * * @param ws TODO * @param path * @return A brand new NodeImpl. * * @throws RepositoryException */ public NodeImpl loadNode( WorkspaceImpl ws, Path path ) throws RepositoryException { NodeImpl ni = null; Path ptPath = path.resolve( JCRConstants.Q_JCR_PRIMARYTYPE ); PropertyImpl primaryType = ws.createPropertyImpl( ptPath ); ValueContainer v = getPropertyValue( ws, ptPath ); if( v == null ) throw new RepositoryException("Repository did not return a primary type for path "+path); primaryType.loadValue( v.getValue() ); QName pt = ((QNameValue.Impl)v.getValue()).getQValue().getValue(); QNodeTypeManager ntm = QNodeTypeManager.getInstance(); QNodeType type = ntm.getNodeType( pt ); QNodeDefinition nd = type.findNodeDefinition( pt ); ni = ws.getSession().createNode( path, type, nd, false ); return ni; } /** * LOad the state of a single property from the repository. * * @param ws * @param ni * @param ptPath * @param name * @return * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private PropertyImpl loadProperty(WorkspaceImpl ws, NodeImpl ni, Path ptPath, QName name) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueContainer values = getPropertyValue( ws, ptPath ); PropertyImpl p = ws.createPropertyImpl( ptPath ); // // Find the proper property definition. // QPropertyDefinition pd = ni.getPrimaryQNodeType().findPropertyDefinition(name,values.isMultiple()); if( pd == null ) { for( NodeType mixin : ni.getMixinNodeTypes() ) { pd = ((QNodeType.Impl)mixin).getQNodeType().findPropertyDefinition( name, values.isMultiple() ); if( pd != null ) break; } if( pd == null ) throw new RepositoryException("Unable to locate property definition for nodetype "+ni.getPrimaryNodeType()+", name="+name); } p.setDefinition( pd.new Impl(ws.getSession()) ); // FIXME: Inoptimal if( values.isMultiple() ) p.loadValue( values.getValues(), values.getType() ); else p.loadValue( values.getValue() ); return p; } public void addNode(StoreTransaction tx, NodeImpl ni) throws RepositoryException { Path path = ni.getInternalPath(); if( !path.isRoot() && !itemExists(tx.getWorkspace(), path.getParentPath(), ItemType.NODE) ) throw new ConstraintViolationException("Parent path is missing for path "+path); ProviderInfo pi = getProviderInfo(tx.getWorkspace(),path); try { pi.lock.writeLock().lock(); pi.provider.addNode(tx, path, ni.getQDefinition()); } finally { pi.lock.writeLock().unlock(); } } public void copy(WorkspaceImpl m_workspace, Path srcpath, Path destpath) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } public NodeImpl findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); Path path = pi.provider.findByUUID(ws, uuid); return loadNode(ws, path); } catch(ItemNotFoundException e) {} finally { pi.lock.readLock().unlock(); } } - throw new ItemNotFoundException("Could not locate a node by this UUID"); + throw new ItemNotFoundException("Could not locate a node by this UUID: "+uuid); } public ItemImpl getItem(WorkspaceImpl ws, Path path) throws InvalidPathException, RepositoryException { try { NodeImpl ni = loadNode( ws, path ); return ni; } catch( RepositoryException e ) { if( path.isRoot() ) throw e; // Otherwise we just get a relatively unclear "root has no parent" NodeImpl ni = loadNode( ws, path.getParentPath() ); return loadProperty( ws, ni, path, path.getLastComponent() ); } } public boolean itemExists(WorkspaceImpl ws, Path path, ItemType type) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.itemExists(ws, path, type); } finally { pi.lock.readLock().unlock(); } } public void putProperty(StoreTransaction tx, Path path, ValueContainer value ) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); ValueContainer vc = value.deepClone(tx.getWorkspace().getSession()); try { pi.lock.writeLock().lock(); pi.provider.putPropertyValue( tx, path, vc ); } finally { pi.lock.writeLock().unlock(); } } public void stop() { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.stop(m_repository); } finally { pi.lock.writeLock().unlock(); } } } public Collection<? extends PropertyImpl> getReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { ArrayList<PropertyImpl> result = new ArrayList<PropertyImpl>(); List<Path> paths = new ArrayList<Path>(); for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); paths.addAll(pi.provider.findReferences( ws, uuid )); } finally { pi.lock.readLock().unlock(); } } for( Path path : paths ) { NodeImpl nd = loadNode( ws, path.getParentPath() ); result.add( nd.getProperty(ws.getSession().fromQName(path.getLastComponent())) ); } return result; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.listProperties(ws, path); } finally { pi.lock.readLock().unlock(); } } public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( ws.getName() ); try { pi.lock.writeLock().lock(); return pi.provider.storeStarted( ws ); } finally { pi.lock.writeLock().unlock(); } } public void storeFinished(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeFinished( tx ); } finally { pi.lock.writeLock().unlock(); } } public void storeCancelled(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeCancelled( tx ); } finally { pi.lock.writeLock().unlock(); } } /** * Stores information about a provider. */ private class ProviderInfo { public String[] workspaces; public RepositoryProvider provider; public ReadWriteLock lock; } /** * Returns the name of the default workspace. This is usually "default", but * it may change depending on how you configure Priha. * * @return */ public String getDefaultWorkspace() { return m_defaultWorkspaceName; } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.reorderNodes( tx, internalPath, childOrder ); } finally { pi.lock.writeLock().unlock(); } } } diff --git a/src/java/org/priha/version/AbstractVersion.java b/src/java/org/priha/version/AbstractVersion.java new file mode 100644 index 0000000..a266684 --- /dev/null +++ b/src/java/org/priha/version/AbstractVersion.java @@ -0,0 +1,207 @@ +package org.priha.version; + +import javax.jcr.*; +import javax.jcr.lock.Lock; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.version.Version; +import javax.jcr.version.VersionException; + +import org.priha.core.NodeImpl; +import org.priha.core.PropertyImpl; +import org.priha.core.SessionImpl; +import org.priha.core.locks.QLock.Impl; +import org.priha.nodetype.QNodeDefinition; +import org.priha.nodetype.QNodeType; +import org.priha.path.Path; +import org.priha.util.QName; + +/** + * Provides a common base class for both Version and VersionHistory and disable + * a number of write-methods. + */ +public class AbstractVersion extends NodeImpl +{ + + public AbstractVersion(SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition def, boolean initDefaults) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException + { + super(session,path,primaryType,def,initDefaults); + } + + // TODO: I can't find the JCR spec which states this should occur. + @Override + public void addMixin(String mixinName) + throws NoSuchNodeTypeException, + VersionException, + ConstraintViolationException, + LockException, + RepositoryException + { + throw new ConstraintViolationException("Versions cannot add mixin types."); + } + + @Override + public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException + { + return false; + } + + @Override + public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException + { + throw new UnsupportedRepositoryOperationException("A Version node cannot be checked out."); + } + + @Override + public Impl getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException + { + throw new LockException("A Version node cannot be locked."); + } + + @Override + public Lock lock(boolean isDeep, boolean isSessionScoped) + throws UnsupportedRepositoryOperationException, + LockException, + AccessDeniedException, + InvalidItemStateException, + RepositoryException + { + throw new LockException("A Version node cannot be locked."); + } + + @Override + public NodeIterator merge(String srcWorkspace, boolean bestEffort) + throws NoSuchWorkspaceException, + AccessDeniedException, + MergeException, + LockException, + InvalidItemStateException, + RepositoryException + { + throw new ConstraintViolationException("A Version node cannot be merged."); + } +/* + @Override + public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException + { + if( m_session.isSuper() ) + super.remove(); + + throw new ConstraintViolationException("A Version node cannot be removed."); + } +*/ + @Override + public void removeMixin(String mixinName) + throws NoSuchNodeTypeException, + VersionException, + ConstraintViolationException, + LockException, + RepositoryException + { + if( m_session.isSuper() ) + { + super.removeMixin(mixinName); + return; + } + + throw new ConstraintViolationException("A Version node cannot remove mixins."); + } + + @Override + public void restore(String versionName, boolean removeExisting) + throws VersionException, + ItemExistsException, + UnsupportedRepositoryOperationException, + LockException, + InvalidItemStateException, + RepositoryException + { + throw new UnsupportedRepositoryOperationException("A Version node cannot be restored."); + } + + @Override + public void restore(Version version, String relPath, boolean removeExisting) + throws PathNotFoundException, + ItemExistsException, + VersionException, + ConstraintViolationException, + UnsupportedRepositoryOperationException, + LockException, + InvalidItemStateException, + RepositoryException + { + throw new ConstraintViolationException("A Version node does not support restore()."); + } + + + @Override + public void update(String srcWorkspaceName) + throws NoSuchWorkspaceException, + AccessDeniedException, + LockException, + InvalidItemStateException, + RepositoryException + { + throw new ConstraintViolationException("A Version node cannot be updated."); + } + + @Override + protected PropertyImpl prepareProperty(QName name, Object value) throws PathNotFoundException, RepositoryException + { + if( m_session.isSuper() ) + return super.prepareProperty(name, value); + + throw new ConstraintViolationException("A Version node does not support setProperty()."); + } + + @Override + protected PropertyImpl prepareProperty(String name, Object value) throws PathNotFoundException, RepositoryException + { + if( m_session.isSuper() ) + return super.prepareProperty(name, value); + + throw new ConstraintViolationException("A Version node does not support setProperty()."); + } + + @Override + public VersionImpl getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException + { + if( m_session.isSuper() ) + return super.getBaseVersion(); + + throw new UnsupportedRepositoryOperationException("Version nodes do not support getBaseVersion()"); + } + + @Override + public NodeImpl addNode(String relPath, String primaryNodeTypeName) + throws ItemExistsException, + PathNotFoundException, + VersionException, + ConstraintViolationException, + LockException, + RepositoryException + { + if(m_session.isSuper()) + return super.addNode(relPath,primaryNodeTypeName); + + throw new ConstraintViolationException(); + } + + @Override + public NodeImpl addNode(String relPath) + throws ItemExistsException, + PathNotFoundException, + NoSuchNodeTypeException, + LockException, + VersionException, + ConstraintViolationException, + RepositoryException + { + if(m_session.isSuper()) + return super.addNode(relPath); + + throw new ConstraintViolationException(); + } + +} diff --git a/src/java/org/priha/version/VersionHistoryImpl.java b/src/java/org/priha/version/VersionHistoryImpl.java index 76d5e9c..a65fafa 100644 --- a/src/java/org/priha/version/VersionHistoryImpl.java +++ b/src/java/org/priha/version/VersionHistoryImpl.java @@ -1,207 +1,206 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.version; import java.util.ArrayList; import java.util.List; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionIterator; import org.priha.core.JCRConstants; -import org.priha.core.NodeImpl; import org.priha.core.SessionImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.path.Path; -public class VersionHistoryImpl extends NodeImpl implements VersionHistory +public class VersionHistoryImpl extends AbstractVersion implements VersionHistory { public static VersionHistoryImpl getInstance( SessionImpl session, Path path ) throws RepositoryException { QNodeTypeManager nt = QNodeTypeManager.getInstance(); QNodeType versionType = nt.getNodeType(JCRConstants.Q_NT_VERSIONHISTORY); QNodeDefinition nDef = versionType.findNodeDefinition( path.getLastComponent() ); return new VersionHistoryImpl( session, path, versionType, nDef, true ); } public VersionHistoryImpl(SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean initDefaults) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super(session, path, primaryType, nDef, initDefaults); } public void addVersionLabel(String arg0, String arg1, boolean arg2) throws VersionException, RepositoryException { throw new UnsupportedRepositoryOperationException("addVersionLabel()"); } public VersionIterator getAllVersions() throws RepositoryException { ArrayList<Version> allVersions = new ArrayList<Version>(); Version v = getRootVersion(); while( v != null ) { allVersions.add( v ); Version[] succs = v.getSuccessors(); if( succs.length == 0 ) break; v = succs[0]; // Priha does not support multiple successors. } return new VersionIteratorImpl(allVersions); } public Version getRootVersion() throws RepositoryException { return getVersion("jcr:rootVersion"); } public Version getVersion(String versionName) throws VersionException, RepositoryException { Path p = VersionManager.getVersionStoragePath( getVersionableUUID() ).resolve(getSession(),versionName); if( m_session.itemExists(p) ) { return (Version) m_session.getItem( p ); } throw new VersionException("Node "+getPath()+" has no such version "+versionName); } public Version getVersionByLabel(String versionLabel) throws RepositoryException { Node n = getNode("jcr:versionLabels"); Property p = n.getProperty(versionLabel); String uuid = p.getString(); return (Version)m_session.getNodeByUUID(uuid); } public String[] getVersionLabels() throws RepositoryException { ArrayList<String> result = new ArrayList<String>(); Node n = getNode("jcr:versionLabels"); for( PropertyIterator pi = n.getProperties(); pi.hasNext(); ) { Property p = pi.nextProperty(); result.add( p.getName() ); } return result.toArray(new String[result.size()]); } public String[] getVersionLabels(Version arg0) throws VersionException, RepositoryException { throw new UnsupportedRepositoryOperationException("getVersionLabels(Version)"); } public String getVersionableUUID() throws RepositoryException { return getProperty("jcr:versionableUuid").getString(); } public boolean hasVersionLabel(String label) throws RepositoryException { String[] labels = getVersionLabels(); for( String s : labels ) { if( s.equals(label) ) return true; } return false; } public boolean hasVersionLabel(Version version, String label) throws VersionException, RepositoryException { String[] labels = getVersionLabels(version); for( String s : labels ) { if( s.equals(label) ) return true; } return false; } public void removeVersion(String arg0) throws ReferentialIntegrityException, AccessDeniedException, UnsupportedRepositoryOperationException, VersionException, RepositoryException { throw new UnsupportedRepositoryOperationException("removeVersion(String)"); } @Override public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { System.out.println("VersionHistory.remove("+getPath()+")"); // First, we'll remove all the children List<Version> toberemoved = new ArrayList<Version>(); VersionIterator i = getAllVersions(); while( i.hasNext() ) { Version v = i.nextVersion(); toberemoved.add( v ); } for( Version v : toberemoved ) { System.out.println(" Removing version "+v.getName()); try { v.remove(); } catch(Exception ex) { ex.printStackTrace(); } } System.out.println("Remove version history "+this); // Then we remove the Node itself. super.remove(); } public void removeVersionLabel(String arg0) throws VersionException, RepositoryException { throw new UnsupportedRepositoryOperationException("removeVersionLabel(String)"); } } diff --git a/src/java/org/priha/version/VersionImpl.java b/src/java/org/priha/version/VersionImpl.java index 48207b1..b9db820 100644 --- a/src/java/org/priha/version/VersionImpl.java +++ b/src/java/org/priha/version/VersionImpl.java @@ -1,138 +1,143 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.version; import java.util.Calendar; import javax.jcr.*; +import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.jcr.version.VersionHistory; -import org.priha.core.NodeImpl; +import org.priha.core.PropertyImpl; import org.priha.core.SessionImpl; +import org.priha.core.locks.QLock.Impl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.path.Path; +import org.priha.util.QName; /** * Implements a JCR Version. The JCR specification is slightly ambiguous on * whether a Version with no predecessors/successors should return an empty * array, but we will return an empty array if no such beast exists. */ public class VersionImpl - extends NodeImpl + extends AbstractVersion implements Version { public VersionImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean initDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path, primaryType, nDef, initDefaults ); } /** * {@inheritDoc} */ public VersionHistory getContainingHistory() throws RepositoryException { return (VersionHistory)getParent(); } /** * {@inheritDoc} */ public Calendar getCreated() throws RepositoryException { Property p = getProperty("jcr:created"); return p.getDate(); } /** * Priha returns a valid array unless there was something weird * going on. If there are no predecessors, an empty array is returned. */ public Version[] getPredecessors() throws RepositoryException { try { Property p = getProperty("jcr:predecessors"); return collateVersions( p ); } catch( PathNotFoundException e ) { return new Version[0]; } } /** * Priha returns a valid array unless there was something weird * going on. If there are no successors, an empty array is returned. */ public Version[] getSuccessors() throws RepositoryException { try { Property p = getProperty("jcr:successors"); Version[] result = collateVersions(p); return result; } catch( PathNotFoundException e ) { return new Version[0]; } } /** * Creates a Version array based on the UUIDs stored in the Property. * * @param p Multi-valued property to iterate over. Must contain UUIDs. * @return An array of Versions. * @throws ValueFormatException If the contents of p are not UUIDs. * @throws RepositoryException If something goes wrong * @throws ItemNotFoundException If an Version object based on the UUID cannot be found. */ private Version[] collateVersions(Property p) throws ValueFormatException, RepositoryException, ItemNotFoundException { Value[] vals = p.getValues(); Version[] result = new Version[vals.length]; int i = 0; for( Value v : vals ) { String uuid = v.getString(); Version vers = (Version) getSession().getNodeByUUID( uuid ); result[i++] = vers; } return result; } + } diff --git a/tests/etc/repositoryStubImpl.properties b/tests/etc/repositoryStubImpl.properties index 435b29f..c5c3822 100644 --- a/tests/etc/repositoryStubImpl.properties +++ b/tests/etc/repositoryStubImpl.properties @@ -1,138 +1,140 @@ javax.jcr.tck.repository_stub_impl=org.apache.jackrabbit.test.PrihaRepositoryStub testroot = /testroot javax.jcr.tck.testroot=/testroot javax.jcr.tck.nodename1=TestNode javax.jcr.tck.nodename2=TestNode2 javax.jcr.tck.nodename3=TestNode3 javax.jcr.tck.nodename4=TestNode4 javax.jcr.tck.propertyname1=aaa javax.jcr.tck.propertyname2=bbb javax.jcr.tck.propertyname3=ccc javax.jcr.tck.workspacename=testworkspace javax.jcr.tck.nodetype=nt:unstructured javax.jcr.tck.nodetypenochildren=nt:base +javax.jcr.tck.versionableNodeType=nt:unstructured + javax.jcr.tck.sameNameSibsTrueNodeType=nt:unstructured javax.jcr.tck.sameNameSibsFalseNodeType=test:sameNameSibsFalseChildNodeDefinition javax.jcr.tck.SessionTest.testSaveContstraintViolationException.nodetype2=nt:linkedFile javax.jcr.tck.NodeTest.testSaveContstraintViolationException.nodetype2=nt:linkedFile javax.jcr.tck.versionableNodeType=nt:unstructured javax.jcr.tck.propertyValue=Gobble # A nodetype with mandatory referenceability javax.jcr.tck.SetPropertyNodeTest.nodetype=priha:referenceable # A nodetype with a mandatory child node javax.jcr.tck.NodeTest.testRemoveMandatoryNode.nodetype2=nt:file # The child of the previous javax.jcr.tck.NodeTest.testRemoveMandatoryNode.nodetype3=nt:unstructured # The name of the previous javax.jcr.tck.NodeTest.testRemoveMandatoryNode.nodename3=jcr:content # Not allowing same name sibs javax.jcr.tck.NodeTest.testAddNodeItemExistsException.nodetype=test:sameNameSibsFalseChildNodeDefinition #javax.jcr.tck.NodeTest.nodetype=priha:referenceable # javax.jcr.tck.NodeUUIDTest.nodetype=priha:referenceable javax.jcr.tck.NodeUUIDTest.propertyname1=ref javax.jcr.tck.NodeUUIDTest.nodetype2=priha:referenceable # Configuration settings for the serialization. # Note that the serialization test tries to use as many features of the repository # as possible, but fails silently if a feature is not available. You have to # specify all of the following configuration entries, even if your repository does # not support the feature that is associated with them. # Root node for the example tree javax.jcr.tck.SerializationTest.testroot=/testdata/serialization # Node type to use for the example tree. Specify a node type that allows complex trees and all property types if possible javax.jcr.tck.SerializationTest.nodetype=nt:unstructured # Name of the nodes for source and target tree javax.jcr.tck.SerializationTest.sourceFolderName=source javax.jcr.tck.SerializationTest.targetFolderName=target javax.jcr.tck.SerializationTest.rootNodeName=test # List the properties whose values may change during serialization/deserialization. For example, # the UUID of a node is unique in the repository, so it will have to change when you re-import # a tree at a different location. javax.jcr.tck.SerializationTest.propertyValueMayChange= jcr:created jcr:uuid jcr:versionHistory jcr:baseVersion jcr:predecessors P_Reference # List all properties which are skipped during xml import according specification chapter 7.3.3 javax.jcr.tck.SerializationTest.propertySkipped=jcr:baseVersion # The name of the test node types. For easier diagnostics, the node types have names # that tell you the kind of information they store javax.jcr.tck.SerializationTest.nodeTypesTestNode=NodeTypes javax.jcr.tck.SerializationTest.mixinTypeTestNode=MixinTypes javax.jcr.tck.SerializationTest.propertyTypesTestNode=PropertyTypes javax.jcr.tck.SerializationTest.sameNameChildrenTestNode=SameNameChildren javax.jcr.tck.SerializationTest.multiValuePropertiesTestNode=MultiValueProperties javax.jcr.tck.SerializationTest.referenceableNodeTestNode=ReferenceableNode javax.jcr.tck.SerializationTest.orderChildrenTestNode=OrderChildren javax.jcr.tck.SerializationTest.namespaceTestNode=Namespace # The name of the test property types. javax.jcr.tck.SerializationTest.stringTestProperty=P_String javax.jcr.tck.SerializationTest.binaryTestProperty=P_Binary javax.jcr.tck.SerializationTest.dateTestProperty=P_Date javax.jcr.tck.SerializationTest.longTestProperty=P_Long javax.jcr.tck.SerializationTest.doubleTestProperty=P_Double javax.jcr.tck.SerializationTest.booleanTestProperty=P_Boolean javax.jcr.tck.SerializationTest.nameTestProperty=P_Name javax.jcr.tck.SerializationTest.pathTestProperty=P_Path javax.jcr.tck.SerializationTest.referenceTestProperty=P_Reference javax.jcr.tck.SerializationTest.multiValueTestProperty=P_MultiValue # node type not allowing same name sibs javax.jcr.tck.SerializationTest.sameNameSibsFalseChildNodeDefinition=test:sameNameSibsFalseChildNodeDefinition # Test method: testVersioningExceptionSessionFileChild # specified nodetype must be versionable and allow child nodes of the same type. javax.jcr.tck.SerializationTest.testVersioningExceptionSessionFileChild.nodetype=test:versionable # Test method: testVersioningExceptionSessionFileParent # specified nodetype must be versionable and allow child nodes of the same type. javax.jcr.tck.SerializationTest.testVersioningExceptionSessionFileParent.nodetype=test:versionable # Test method: testSessionImportXmlOverwriteException # requires a node type that does not allow same name siblings javax.jcr.tck.SerializationTest.testSessionImportXmlOverwriteException.nodetype=nt:folder # The name of the test node types. For easier diagnostics, the node types have names # that tell you the kind of information they store javax.jcr.tck.SerializationTest.nodeTypesTestNode=NodeTypes javax.jcr.tck.SerializationTest.mixinTypeTestNode=MixinTypes javax.jcr.tck.SerializationTest.propertyTypesTestNode=PropertyTypes javax.jcr.tck.SerializationTest.sameNameChildrenTestNode=SameNameChildren javax.jcr.tck.SerializationTest.multiValuePropertiesTestNode=MultiValueProperties javax.jcr.tck.SerializationTest.referenceableNodeTestNode=ReferenceableNode javax.jcr.tck.SerializationTest.orderChildrenTestNode=OrderChildren javax.jcr.tck.SerializationTest.namespaceTestNode=Namespace # Test class: ExportSysViewTest javax.jcr.tck.ExportSysViewTest.testroot=/testdata # Priha does not support orderable child nodes, so we give just a nodetype javax.jcr.tck.NodeOrderableChildNodesTest.nodetype2=priha:referenceable # XPathDocOrderTest javax.jcr.tck.XPathDocOrderTest.testroot=/querytest # XPathOrderByTest javax.jcr.tck.XPathOrderByTest.testroot=/querytest javax.jcr.tck.NodeOrderableChildNodesTest.nodetype2=nt:unstructured javax.jcr.tck.NodeOrderableChildNodesTest.nodetype3=nt:unstructured javax.jcr.tck.NodeOrderableChildNodesTest.testOrderBeforeUnsupportedRepositoryOperationException.nodetype2=nt:folder javax.jcr.tck.NodeOrderableChildNodesTest.testOrderBeforeUnsupportedRepositoryOperationException.nodetype3=nt:folder diff --git a/tests/tck/org/apache/jackrabbit/test/api/version/AbstractVersionTest.java b/tests/tck/org/apache/jackrabbit/test/api/version/AbstractVersionTest.java index cdd8e2f..f936670 100644 --- a/tests/tck/org/apache/jackrabbit/test/api/version/AbstractVersionTest.java +++ b/tests/tck/org/apache/jackrabbit/test/api/version/AbstractVersionTest.java @@ -1,149 +1,150 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.test.api.version; import org.apache.jackrabbit.test.AbstractJCRTest; import org.apache.jackrabbit.test.NotExecutableException; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeType; import javax.jcr.Node; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.version.VersionHistory; /** * <code>AbstractVersionTest</code> is the abstract base class for all * versioning related test classes. */ public class AbstractVersionTest extends AbstractJCRTest { protected NodeType versionableNodeType; protected NodeType nonVersionableNodeType; protected Node versionableNode; protected Node nonVersionableNode; protected String propertyValue; protected void setUp() throws Exception { super.setUp(); if(superuser.getRepository().getDescriptor( Repository.OPTION_VERSIONING_SUPPORTED ).equals( "false" )) throw new NotExecutableException("Versioning not supported"); NodeTypeManager ntMgr = superuser.getWorkspace().getNodeTypeManager(); // assert that this repository support versioning try { NodeType versionableNt = ntMgr.getNodeType(mixVersionable); if (versionableNt == null) { fail("Repository does not support Versioning: mixin nodetype 'mix:versionable' is missing."); } } catch (NoSuchNodeTypeException e) { fail("Repository does not support Versioning: mixin nodetype 'mix:versionable' is missing."); } // retrieve versionable nodetype String versionableNodeTypeName = getProperty("versionableNodeType"); try { versionableNodeType = ntMgr.getNodeType(versionableNodeTypeName); if (versionableNodeType == null) { fail("Property 'versionableNodeType' does not define a valid nodetype: '"+versionableNodeTypeName+"'"); } } catch (NoSuchNodeTypeException e) { fail("Property 'versionableNodeType' does not define an existing nodetype: '"+versionableNodeTypeName+"'"); } // make sure 'non-versionable' nodetype is properly defined try { nonVersionableNodeType = ntMgr.getNodeType(testNodeType); if (nonVersionableNodeType == null || nonVersionableNodeType.isNodeType(mixVersionable)) { fail("Property 'testNodeType' does define a versionable nodetype: '"+testNodeType+"'"); } } catch (NoSuchNodeTypeException e) { fail("Property 'testNodeType' does not define an existing nodetype: '"+testNodeType+"'"); } // build persistent versionable and non-versionable nodes try { versionableNode = createVersionableNode(testRootNode, nodeName1, versionableNodeType); } catch (RepositoryException e) { + e.printStackTrace(); fail("Failed to create versionable test node." + e.getMessage()); } try { nonVersionableNode = testRootNode.addNode(nodeName3, nonVersionableNodeType.getName()); testRootNode.save(); } catch (RepositoryException e) { fail("Failed to create non-versionable test node." + e.getMessage()); } propertyValue = getProperty("propertyValue"); if (propertyValue == null) { fail("Property 'propertyValue' is not defined."); } } protected void tearDown() throws Exception { // remove versionable nodes try { versionableNode.remove(); testRootNode.save(); } catch (Exception e) { log.println("Exception in tearDown: " + e.toString()); } finally { versionableNodeType = null; nonVersionableNodeType = null; versionableNode = null; nonVersionableNode = null; super.tearDown(); } } /** * Retrieve the number of versions present in the given version history. * * @param vHistory * @return number of versions * @throws RepositoryException */ protected long getNumberOfVersions(VersionHistory vHistory) throws RepositoryException { return getSize(vHistory.getAllVersions()); } /** * Create a versionable node below the given parent node. If the specified * nodetype name is not mix:versionable an attempt is made to add the * mix:versionable mixin type to the created child node. * * @param parent * @param name * @param nodetype * @return versionable node. * @throws RepositoryException */ protected Node createVersionableNode(Node parent, String name, NodeType nodetype) throws RepositoryException { Node versionableNode = parent.addNode(name, nodetype.getName()); if (!nodetype.isNodeType(mixVersionable)) { versionableNode.addMixin(mixVersionable); } parent.save(); return versionableNode; } } \ No newline at end of file
jalkanen/Priha
5c65d5122b50eee5790c0ef26f62ecb030985969
Correcting depends info for dist-install.
diff --git a/build.xml b/build.xml index 3b1aec1..db0edca 100644 --- a/build.xml +++ b/build.xml @@ -1,364 +1,364 @@ <?xml version="1.0"?> <!-- Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project name="Priha" default="jar"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> <include name="*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> <!-- Jackrabbit is only included if it has been installed with maven --> <fileset dir="${user.home}"> <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> <include name=".m2/repository/commons-collections/**/*3.2.jar"/> <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> </fileset> </path> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> <src path="src/java"/> <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> <src path="tests/java"/> <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> <delete dir="tests/build"/> </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> <!-- ***************************************************************** --> <!-- Distribution package building. Use "ant dist" to build the distro package, and "ant srczip" to create a source tarball. --> <target name="srczip" depends="compile"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-src.zip"> <zipfileset dir="." excludes="build/** tests/build/** repository*/** tests/reports/** *.log doc/javadoc/**" prefix="priha-${version}"/> </zip> </target> <target name="dist" depends="jar,javadoc"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-bin.zip"> <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> <zipfileset dir="." includes="ChangeLog README LICENSE NOTICE doc/**" prefix="priha-${version}"/> <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> <zipfileset dir="lib" includes="ehcache-*.jar hsqldb-*.jar" prefix="priha-${version}/extras-lib"/> </zip> </target> <!-- Installs the distribution archives by checking out the SVN project. Needs svn and gpg binaries in the shell path. --> - <target name="dist-install" depends=""> + <target name="dist-install" depends="srczip,dist"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <!-- Check out code --> <exec executable="svn"> <arg value="co"/> <arg value="https://svn.ecyrd.com/repos/priha/site"/> <arg value="build/priha-site"/> </exec> <!-- Install archives --> <property name="destdir" value="build/priha-site/WebContent/download/priha-${version}"/> <delete dir="${destdir}"/> <mkdir dir="${destdir}"/> <copy file="build/priha-${version}-bin.zip" todir="${destdir}"/> <copy file="build/priha-${version}-src.zip" todir="${destdir}"/> <exec executable="gpg"> <arg value="-sba"/> <arg value="${destdir}/priha-${version}-src.zip"/> </exec> <exec executable="gpg"> <arg value="-sba"/> <arg value="${destdir}/priha-${version}-bin.zip"/> </exec> <!-- Figure out file lengths. We need a bit of Javascript to build the sizes in megabytes --> <length file="build/priha-${version}-bin.zip" property="binsize"/> <length file="build/priha-${version}-src.zip" property="srcsize"/> <script language="javascript"> <![CDATA[ var binsize = project.getProperty("binsize"); var srcsize = project.getProperty("srcsize"); var binmegas = Math.round((binsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); var srcmegas = Math.round((srcsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); project.setNewProperty("binsizemegs", binmegas); project.setNewProperty("srcsizemegs", srcmegas); ]]> </script> <!-- Modify page --> <loadfile property="message" srcFile="build/priha-site/downloadmessage.html"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens"> <param type="token" name="srcurl" value="download/priha-${version}/priha-${version}-src.zip"/> <param type="token" name="binurl" value="download/priha-${version}/priha-${version}-bin.zip"/> <param type="token" name="version" value="${version}"/> <param type="token" name="srcsize" value="${srcsizemegs}"/> <param type="token" name="binsize" value="${binsizemegs}"/> </filterreader> </filterchain> </loadfile> <replaceregexp file="build/priha-site/WebContent/download.html" flags="gs" match="&lt;!-- STARTMAGIC -->(.*)&lt;!-- ENDMAGIC -->" replace="&lt;!-- STARTMAGIC -->${message}&lt;!-- ENDMAGIC -->"/> <echo> OK, I'm done. Please examine the contents of build/priha-site/WebContent/download.html prior to checking in the code with "svn commit". </echo> </target> </project>
jalkanen/Priha
111440161fadf173a442b4e79da401cd0ec96ba6
Dang, forgot to clear children also in the ForwardIterator.remove()
diff --git a/src/java/org/priha/util/ChangeStore.java b/src/java/org/priha/util/ChangeStore.java index 3136342..5bbb56a 100644 --- a/src/java/org/priha/util/ChangeStore.java +++ b/src/java/org/priha/util/ChangeStore.java @@ -1,415 +1,437 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.util.*; import org.priha.core.ItemImpl; import org.priha.core.ItemState; import org.priha.core.PropertyImpl; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.ValueContainer; /** * Provides a list of changes, which can be both played back * one by one, as well as searched rapidly. * <p> * Internally, this class stores both a List of Change objects, * as well as a HashMap pointing at the latest change. It can be * iterated both forwards (using peek() and remove() and iterator()) as well * as backwards (using values()). * <p> * In addition, it stores a separate reference to all the changes relating * to a particular parent path (making it fairly fast to filter based on a path). */ public class ChangeStore implements Iterable<ChangeStore.Change> { private ArrayList<Change> m_changes = new ArrayList<Change>(); private HashMap<Path,Change> m_latest = new HashMap<Path,Change>(); private HashMap<Path,List<Change>> m_childChanges = new HashMap<Path,List<Change>>(); /** * Create a ChangeStore without the HashMap. */ public ChangeStore() {} /** * Returns the newest ItemImpl that corresponds to the Path given. * * @param path Path to search for * @return Newest Item or null, if no such thing is found. */ public ItemImpl getLatestItem( Path path ) { Change c = getLatestChange( path ); if( c != null ) return c.getItem(); return null; } /** * Finds the latest change. * * @param path Path to search for * @return The Change or null, if no such thing found. */ public Change getLatestChange( Path path ) { Change c = m_latest.get( path ); return c; } /** * Get all the latest changes, ignoring any duplicate changes. * * @return A list of latest changes. */ public List<Change> getLatestChanges() { ArrayList<Change> changes = new ArrayList<Change>(); changes.addAll( m_latest.values() ); return changes; } /** * Returns a list of Changes filtered by a parent path. * * @param parent The path to filter against * @return A list of Changes. */ public List<Change> getLatestChangesForParent( Path parent ) { ArrayList<Change> changes = new ArrayList<Change>(); List<Change> c = m_childChanges.get(parent); if( c != null ) changes.addAll( c ); return changes; } /** * Adds a new Item with given ItemState to the end of the Change List. * * @param newState New state * @param ii The Item */ public void add( ItemState newState, ItemImpl ii ) { Change c = new Change( newState, ii ); add( c ); } /** * Adds a whole Change object at the end of the Change List. * * @param c The Change to add * @return True, at the moment. */ public boolean add( Change c ) { if( c.getState() == ItemState.UNDEFINED ) { dump(); throw new IllegalStateException("You cannot add an UNDEFINED Item "+c.getItem().getInternalPath()); } m_changes.add(c); m_latest.put( c.getPath(), c ); if( !c.getPath().isRoot() ) { try { List<Change> pc = m_childChanges.get( c.getPath().getParentPath() ); if( pc == null ) { pc = new ArrayList<Change>(); m_childChanges.put( c.getPath().getParentPath(), pc ); } pc.add( c ); } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot add path "+c.getPath()); } } return true; } /** * Gets the first change from the change list. Returns null, if there are no more * changes. * * @return The first change from the list, or null, if the list was empty. */ public Change peek() { if( m_changes.size() > 0 ) return m_changes.get(0); return null; } /** * Removes the first change from the change list. * * @return The first change from the list, or null, if the list was empty. */ public Change remove() { Change c = null; if( m_changes.size() > 0 ) { c = m_changes.remove(0); m_latest.remove( c.getPath() ); if( !c.getPath().isRoot() ) { try { Path parent = c.getPath().getParentPath(); List<Change> pc = m_childChanges.get( parent ); pc.remove( c ); // FIXME: SLow. if( pc.isEmpty() ) { m_childChanges.remove( parent ); } } catch( InvalidPathException e ) { throw new IllegalStateException("Cannot remove "+c.getPath()); } } } return c; } /** * Clears the changes. * * @return The number of changes removed from the queue. */ public int clear() { int numChanges = m_changes.size(); m_changes.clear(); m_latest.clear(); m_childChanges.clear(); return numChanges; } /** * Returns a forward iterator for the Changes. * * @return A forward iterator for the Changes. */ public Iterator<Change> iterator() { return new ForwardIterator(); } /** * Returns a <b>backward</b> iterator for the Items in the change list. The first * value you get is the newest value on the stack. This means * that the iteration order for iterator() and values() is reversed. * * @return A reverse iterator for the values. */ public Iterator<ItemImpl> values() { return new ItemIterator(); } /** * Returns true, if there are no changes. * * @return True, if there are no changes. */ public final boolean isEmpty() { return m_changes.isEmpty(); } /** * Implements a backwards iterator through the Items in the list. */ private class ItemIterator implements Iterator<ItemImpl> { int m_position; protected ItemIterator() { m_position = m_changes.size()-1; } public final boolean hasNext() { return m_position > 0; } public final ItemImpl next() { return m_changes.get(m_position--).getItem(); } public void remove() { throw new UnsupportedOperationException(); } } private class ForwardIterator implements Iterator<Change> { int m_position; protected ForwardIterator() { m_position = 0; } public final boolean hasNext() { return m_position < m_changes.size(); } public final Change next() { return m_changes.get(m_position++); } public void remove() { if( m_position == 0 ) throw new IllegalStateException(); Change c = m_changes.remove( --m_position ); m_latest.remove( c.getPath() ); + + if( !c.getPath().isRoot() ) + { + try + { + Path parent = c.getPath().getParentPath(); + + List<Change> pc = m_childChanges.get( parent ); + + pc.remove( c ); // FIXME: SLow. + + if( pc.isEmpty() ) + { + m_childChanges.remove( parent ); + } + } + catch( InvalidPathException e ) + { + throw new IllegalStateException("Cannot remove "+c.getPath()); + } + } + } } /** * Dumps the store contents for debugging to System.out. */ public void dump() { System.out.println("DUMP OF CHANGESTORE @"+Integer.toHexString(this.hashCode())); System.out.println(this); } /** * Outputs a human-readable description of the contents of the ChangeStore. * * @return Somethign human-readable. */ public String toString() { StringBuilder sb = new StringBuilder(); for( Change c : this ) { sb.append( c.getState().toString() + ": " + c.getPath() + ": " + c.getItem() + "\n" ); } return sb.toString(); } /** * Stores a single change. */ public static final class Change { private ItemState m_state; private ItemImpl m_item; private Path m_path; private ValueContainer m_valueContainer; /** * Create a new Change for the given ItemState and item. If the * Item is a property, also the Value is copied internally. * * @param newState The new state * @param item The item */ public Change( ItemState newState, ItemImpl item ) { m_state = newState; m_item = item; m_path = item.getInternalPath(); if( !item.isNode() ) { m_valueContainer = ((PropertyImpl)item).getValueContainer(); if( m_valueContainer.isEmpty() ) throw new IllegalArgumentException("Null value in valuecontainer for "+m_path); } } /** * Returns the Item for this Change. * * @return The Item. */ public final ItemImpl getItem() { return m_item; } /** * Returns the ItemState for this Change. * * @return The ItemState. */ public final ItemState getState() { return m_state; } /** * Returns the Path for this Change. * * @return The Path. */ public final Path getPath() { return m_path; } /** * Return the ValueContainer for the Change. * * @return The ValueContainer, or null, if the Change concerned a Node. */ public final ValueContainer getValue() { return m_valueContainer; } } }
jalkanen/Priha
b950df27209fb682e383117e7155b8c5e9d32d2a
Increased max cache size so that tests actually fit in it.
diff --git a/tests/etc/jdbcehcache.properties b/tests/etc/jdbcehcache.properties index 507294a..544ad4f 100644 --- a/tests/etc/jdbcehcache.properties +++ b/tests/etc/jdbcehcache.properties @@ -1,28 +1,28 @@ # # This test assumes that a hsqldb.jar is available in the class path. # # The database is started as an in-process instance. You may test the # connection against an existing database by changing the connection # string, but for testing this is not necessary. # priha.providers = ehcache priha.provider.ehcache.class = org.priha.providers.EhCachingProvider priha.provider.ehcache.realProvider = jdbc -priha.provider.ehcache.size = 5000 +priha.provider.ehcache.size = 25000 priha.provider.ehcache.workspaces = default testworkspace priha.provider.ehcache.cacheName = jdbc.ehcache priha.provider.jdbc.class = org.priha.providers.JdbcProvider priha.provider.jdbc.connectionUrl = jdbc:hsqldb:file:/tmp/testdb priha.provider.jdbc.driverClass = org.hsqldb.jdbcDriver #priha.provider.jdbc.connectionUrl = jdbc:h2:file:/tmp/h2db #priha.provider.jdbc.driverClass = org.h2.Driver #priha.provider.jdbc.connectionUrl = jdbc:mysql://localhost/test #priha.provider.jdbc.driverClass = com.mysql.jdbc.Driver priha.provider.jdbc.username = sa priha.provider.jdbc.password = #priha.provider.jdbc.workspaces = default testworkspace \ No newline at end of file
jalkanen/Priha
96163ec4c92fa33edf7d38d5843c5aec2a38759d
Oops, threw wrong exception in skip().
diff --git a/src/java/org/priha/util/GenericIterator.java b/src/java/org/priha/util/GenericIterator.java index 8e69cb9..07f5c8c 100644 --- a/src/java/org/priha/util/GenericIterator.java +++ b/src/java/org/priha/util/GenericIterator.java @@ -1,93 +1,96 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.util.Iterator; import java.util.List; import java.util.ListIterator; +import java.util.NoSuchElementException; /** * Provides a base class for the different Iterators that JCR defines. * * @author jalkanen */ public abstract class GenericIterator implements Iterator { protected ListIterator<?> m_iterator; protected int m_position; protected int m_size; protected List<?> m_list; public GenericIterator( List<?> list ) { m_iterator = list.listIterator(); m_position = 0; m_size = list.size(); m_list = list; } public long getPosition() { return m_position; } public long getSize() { return m_size; } public void skip(long skipNum) { + if( m_position+skipNum > m_size ) throw new NoSuchElementException(); + m_iterator = m_list.listIterator(m_position+(int)skipNum); m_position = m_position+(int)skipNum; } public boolean hasNext() { return m_iterator.hasNext(); } public boolean hasPrevious() { return m_iterator.hasPrevious(); } public Object next() { m_position++; return m_iterator.next(); } public Object previous() { m_position--; return m_iterator.previous(); } public void remove() { m_iterator.remove(); m_size--; if( m_size == m_position ) m_position = m_size-1; if( m_position < 0 ) m_position = 0; } }
jalkanen/Priha
8a31e46b2bfc1124a2178074d6300669c10b1565
Some additional speedups by removing inefficient code from GenericIterator.skip() and SessionProvider.listNodes() and switching to a lazy properties iterator.
diff --git a/ChangeLog b/ChangeLog index ce15a71..66e3da6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,520 @@ +2009-12-26 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.6.7 + + * Some additional speedups by removing inefficient code from + GenericIterator.skip() and SessionProvider.listNodes() and + switching to a lazy properties iterator. + 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. * Speeded up SessionProvider.listNodes(), causing a fairly nice boost to JdbcProvider. * Added dist-install target to build.xml. 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 92bbf26..ad34c6e 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ - public static final int MINORREVISION = 6; + public static final int MINORREVISION = 7; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index b97698d..ca59774 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,1012 +1,1009 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; import org.priha.core.locks.LockManager; import org.priha.core.locks.QLock; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; -import org.priha.util.LazyNodeIteratorImpl; -import org.priha.util.PropertyIteratorImpl; -import org.priha.util.QName; -import org.priha.util.TextUtil; +import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; /** * Implements a Node. This is one of the most heavy classes in Priha, with a lot * of stuff happening. The NodeImpl class does some basic caching for some state * objects, so keeping references can be faster in some cases. */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; /** * A compile-time flag for allowing/disallowing Same Name Sibling support. * addNode() will throw an exception if you disallow these. This is sometimes * useful for debugging. */ private static final boolean ALLOW_SNS = true; private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; private static final String NO_UUID = ""; // If there is no UUID for this Node. static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { enterState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.enterState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.enterState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } - public PropertyIteratorImpl getProperties() throws RepositoryException + public LazyPropertyIteratorImpl getProperties() throws RepositoryException { - List<PropertyImpl> ls = new ArrayList<PropertyImpl>(); + List<Path> ls = new ArrayList<Path>(); - ls.addAll( m_session.m_provider.getProperties(getInternalPath()) ); + ls.addAll(m_session.m_provider.getProperties(getInternalPath())); - return new PropertyIteratorImpl( ls ); + return new LazyPropertyIteratorImpl( getSession(), ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); m_cachedUUID = uuid.toString(); pi.loadValue( vfi.createValue( m_cachedUUID ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.enterState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } /** * Returns the UUID for this node. Utilizes an internal cache for the UUID, * so is fast after the first call. */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { if( NO_UUID.equals(m_cachedUUID) && !hasProperty(JCR_UUID) ) throw new UnsupportedRepositoryOperationException(); if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { // OK, so let's fallthrough to the exception throwing part. } } m_cachedUUID = NO_UUID; throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } /** * Returns true, if this Node has a child with the given QName. * * @param name A QName. * @return True, if there is a child by this name. * @throws RepositoryException */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { m_lockManager.removeLock( lock ); } // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { if( srcChildRelPath.indexOf('[') != -1 || hasNode(srcChildRelPath+"[2]" ) ) { // Yes, we are moving a SNS so this needs reordering. Path tmpPath = getInternalPath().resolve( m_session, "priha:tmpmove" ); // First, store the old version m_session.internalMove( srcPath, tmpPath, false ); String childName = srcChildRelPath.replaceAll( "\\[\\d+\\]", "" ); // FIXME: Hackish trick. boolean last = false; if( dstPath == null ) { NodeIterator ni = getNodes(childName); dstPath = getInternalPath().resolve( m_session, childName+"["+ni.getSize()+"]" ); last = true; } int dir; int startIdx; int endIdx; if( srcPath.getLastComponent().getIndex() < dstPath.getLastComponent().getIndex() ) { // When moving forward, the dstPath is not actually the correct index; // we want to place it _before_ the given index. if( !last ) { int idx = dstPath.getLastComponent().getIndex() - 1; // Real last one dstPath = dstPath.getParentPath().resolve( new Path.Component(dstPath.getLastComponent().getQName(),idx) ); } // Moving stuff forwards dir = -1; startIdx = srcPath.getLastComponent().getIndex()+1; endIdx = dstPath.getLastComponent().getIndex()+1; } else { dir = 1; startIdx = srcPath.getLastComponent().getIndex()-1; endIdx = dstPath.getLastComponent().getIndex()-1; } for( int i = startIdx; i != endIdx; i -= dir ) { String oldName = childName + "[" + i + "]"; String newName = childName + "[" + (i + dir) + "]"; System.out.println("Reordering SNS : "+oldName+" to "+newName); Path path1 = getInternalPath().resolve(m_session,oldName); Path newPath = getInternalPath().resolve(m_session,newName); m_session.internalMove( path1, newPath, false ); } m_session.internalMove( tmpPath, dstPath, false ); } else { // // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. // Path p = newOrder.remove(srcIndex); if( dstIndex != -1 ) newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); else newOrder.add(p); } } finally { m_session.setSuper(isSuper); } // // Lock back up // if( lock != null ) { m_lockManager.moveLock( lock, dstPath ); } // // Finish. // enterState( ItemState.UPDATED ); m_childOrder = newOrder; } private PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ private PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); @@ -1662,672 +1659,672 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> catch( Exception e ) { if( getInternalPath().isRoot() ) { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, "nt:unstructured", PropertyType.NAME ); pix.enterState(ItemState.NEW); } else { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, assignChildType( getInternalPath().getLastComponent() ).toString(), PropertyType.NAME ); pix.enterState(ItemState.NEW); } } if( getParent() != null ) { QNodeType mytype = getPrimaryQNodeType(); m_definition = getParent().getPrimaryQNodeType().findNodeDefinition( mytype.getQName() ); } else { // FIXME: Not correct m_definition = QNodeTypeManager.getInstance().findNodeDefinition( Q_NT_UNSTRUCTURED ); } if( m_definition == null ) { throw new RepositoryException("Cannot assign a node definition for "+getInternalPath()); } } // autoCreateProperties(); QNodeType mytype = getPrimaryQNodeType(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl pi = (PropertyImpl)i.next(); if( pi.getDefinition() == null ) { QPropertyDefinition pd = mytype.findPropertyDefinition( pi.getQName(), false ); // FIXME: Really? pi.m_definition = pd.new Impl(m_session); // FIXME: Inoptimal } } } /** * We consider nodes to be equal if they have the exact same path, and * all the properties are equal too. */ @Override public boolean equals(Object obj) { if( obj == this ) return true; if( obj instanceof NodeImpl ) { NodeImpl ni = (NodeImpl) obj; if( !ni.getInternalPath().equals(getInternalPath()) ) return false; if( !ni.m_session.getWorkspace().getName().equals(m_session.getWorkspace().getName()) ) return false; // All tests have succeeded return true; } return false; } @Override protected void preSave() throws RepositoryException { super.preSave(); } /** * Checks the mandatory properties for this Nodetype and throws a ConstraintViolationException * if it's not existing. * * @param nt * @throws RepositoryException */ void checkMandatoryProperties(QNodeType nt) throws RepositoryException { for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isMandatory() && !hasProperty(pd.getQName()) ) { throw new ConstraintViolationException("Node "+getInternalPath()+" is missing property "+pd.getQName()); } } } /* ============================================================ * * Mixins * */ public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { ValueFactory vf = m_session.getValueFactory(); NodeType mixin = getNodeTypeManager().getNodeType(mixinName); if( !mixin.isMixin() ) throw new NoSuchNodeTypeException("Type "+mixinName+" is not a mixin type!"); if( isLockedWithoutToken() ) throw new LockException( "Node is locked, so cannot add new mixin types." ); if( !isCheckedOut() ) throw new VersionException( "Node is not checked out, so cannot add new mixin types."); boolean oldsuper = m_session.setSuper( true ); try { Property p; p = getProperty(Q_JCR_MIXINTYPES); Value[] v = p.getValues(); Value[] newval = new Value[v.length+1]; for( int i = 0; i < v.length; i++ ) { newval[i] = v[i]; } newval[newval.length-1] = vf.createValue(mixinName,PropertyType.NAME); PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, newval, PropertyType.NAME ); pi.enterState(ItemState.UPDATED); } catch( PathNotFoundException e ) { Value[] values = new Value[] { vf.createValue(mixinName,PropertyType.NAME) }; PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, values, PropertyType.NAME ); pi.enterState(ItemState.NEW); } finally { m_session.setSuper( oldsuper ); } //autoCreateProperties(); } public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException { if( isLocked() ) return false; NodeType nt = getNodeTypeManager().getNodeType( mixinName ); if( !nt.isMixin() ) { throw new NoSuchNodeTypeException(mixinName+" is not a mixin type!"); } if( hasMixinType(nt.getName()) ) { return false; } if( !isCheckedOut() ) return false; // FIXME: This is a bit complicated and slow. if( mixinName.equals("mix:versionable") && m_session.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false") ) return false; return true; } boolean hasMixinType(String mixinType) { try { Property pi = getProperty( Q_JCR_MIXINTYPES ); for( Value v : pi.getValues() ) { String mixin = v.getString(); if( mixin.equals(mixinType) ) return true; } } catch( RepositoryException e ) {} return false; } public NodeType[] getMixinNodeTypes() throws RepositoryException { ArrayList<NodeType> mixinTypes = new ArrayList<NodeType>(); // // If there are no mixin types, then let's just return an empty array. // try { Property p = getProperty( Q_JCR_MIXINTYPES ); for( Value v : p.getValues() ) { NodeType nt = m_session.getWorkspace().getNodeTypeManager().getNodeType( v.getString() ); mixinTypes.add( nt ); } } catch( RepositoryException e ) {} return mixinTypes.toArray( new NodeType[0] ); } public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( isLocked() ) throw new LockException("Node locked, cannot remove mixin"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); Property mixinTypes = getProperty("jcr:mixinTypes"); Value[] vals = mixinTypes.getValues(); boolean found = false; for( int i = 0; i < vals.length; i++ ) { if( vals[i].getString().equals(mixinName) ) { vals[i] = null; found = true; } } if( found ) { mixinTypes.setValue( vals ); } else { throw new NoSuchNodeTypeException("No such mixin type to remove: "+mixinName); } } /*============================================================================== * * Locking * */ LockManager m_lockManager = LockManager.getInstance(getSession().getWorkspace()); public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { if( !hasMixinType("mix:lockable") ) throw new UnsupportedRepositoryOperationException("This node is not lockable: "+getInternalPath()); if( getState() == ItemState.NEW ) throw new LockException("This node has no persistent state"); if( isModified() ) throw new InvalidItemStateException("You may only lock Nodes which are not currently modified"); if( isDeep && m_lockManager.hasChildLock(getInternalPath()) ) { throw new LockException("A child of this node already holds a lock, so you cannot deep lock this node."); } if( isLocked() ) { throw new LockException("This Node is already locked."); } QLock lock = new QLock( this, isDeep, isSessionScoped ); m_session.addLockToken( lock.getToken() ); setProperty("jcr:lockOwner", lock.getLockOwner()); setProperty("jcr:lockIsDeep", isDeep); save(); m_lockManager.addLock( lock ); return lock.getLockInstance(m_session); } public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { QLock lock = m_lockManager.getLock( getInternalPath() ); if( lock == null ) throw new LockException("This Node has not been locked."); if( lock.getLockToken(m_session) == null ) throw new LockException("This Session does not own this Lock, so it cannot be unlocked."); if( isModified() ) throw new InvalidItemStateException("This Node must not be modified prior to unlocking"); Property p = getProperty("jcr:lockOwner"); p.remove(); p = getProperty("jcr:lockIsDeep"); p.remove(); m_session.removeLockToken( lock.getLockToken(m_session) ); m_lockManager.removeLock( lock ); lock.invalidate(); save(); } public QLock.Impl getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); // // Must return a clone of the Lock which is particular to this session. // if( li != null ) return li.getLockInstance(m_session); return null; } public boolean holdsLock() throws RepositoryException { QLock li = m_lockManager.getLock( getInternalPath() ); return li != null; } public boolean isLocked() throws RepositoryException { QLock li = m_lockManager.findLock( getInternalPath() ); return li != null; } /** * Returns true, if this Node is locked (that is, it or it's parents are locked) * but the Session which owns this Session does not hold a token to modify it. * * @return True, if you cannot modify this Node due to missing token. */ protected boolean isLockedWithoutToken() { if( !getInternalPath().isRoot() ) { QLock li = m_lockManager.findLock(getInternalPath()); if( li != null && li.getLockToken(m_session) == null ) { return true; } } return false; } /* ==================================================== * * Versioning * */ public boolean isCheckedOut() throws RepositoryException { try { PropertyImpl p = getProperty(Q_JCR_ISCHECKEDOUT); return p.getBoolean(); } catch(PathNotFoundException e) { // Fine; no property exists. } // // Check if this is a versionable node in the first place. // if( isNodeType( "mix:versionable" ) && !isNew() ) return false; return true; } public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.cancelMerge()"); } public VersionImpl checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException { if( !hasMixinType("mix:versionable") ) { throw new UnsupportedRepositoryOperationException("Node is not mix:versionable (8.2.5)"); } if( !isCheckedOut() ) { return getBaseVersion(); } if( isModified() ) { throw new InvalidItemStateException("Node has unsaved changes (8.2.5)"); } if( hasProperty("jcr:mergeFailed") ) { throw new VersionException("Node has failed merges (8.2.5)"); } // // Phew! Preconditions have been checked. Now, let's get to real business. // boolean isSuper = getSession().setSuper(true); try { VersionHistoryImpl vh = getVersionHistory(); int version = 0; if( !getBaseVersion().getName().equals("jcr:rootVersion") ) version = Integer.parseInt( getBaseVersion().getName() ); VersionImpl v = (VersionImpl) vh.addNode( Integer.toString( ++version ), "nt:version" ); if(!hasProperty("nt:versionHistory")) setProperty( "nt:versionHistory", vh ); v.setProperty( JCR_PREDECESSORS, getProperty(JCR_PREDECESSORS).getValues() ); v.addMixin( "mix:referenceable" ); v.setProperty( "jcr:uuid", UUID.randomUUID().toString() ); v.setProperty( JCR_SUCCESSORS, new Value[0], PropertyType.REFERENCE ); setProperty( JCR_PREDECESSORS, new Value[0], PropertyType.REFERENCE ); PropertyImpl preds = v.getProperty(JCR_PREDECESSORS); for( Value val : preds.getValues() ) { String uuid = val.getString(); Node pred = m_session.getNodeByUUID(uuid); Value[] s = pred.getProperty( JCR_SUCCESSORS ).getValues(); List<Value> successorList = new ArrayList<Value>(); successorList.addAll( Arrays.asList(s) ); successorList.add( m_session.getValueFactory().createValue(v) ); pred.setProperty( JCR_SUCCESSORS, successorList.toArray(s) ); } setProperty( "jcr:baseVersion", v ); setProperty( "jcr:isCheckedOut", false ); // // Store the contents into the frozen node of the Version node. // NodeImpl fn = v.addNode("jcr:frozenNode","nt:frozenNode"); - for( PropertyIteratorImpl pi = getProperties(); pi.hasNext(); ) + for( LazyPropertyIteratorImpl pi = getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE ) ) { fn.setProperty( "jcr:frozenPrimaryType", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_UUID ) ) { fn.setProperty( "jcr:frozenUuid", p.getValue() ); } else if( p.getQName().equals( JCRConstants.Q_JCR_MIXINTYPES ) ) { fn.setProperty( "jcr:frozenMixinTypes", p.getValues() ); } else if( p.getDefinition().getOnParentVersion() == OnParentVersionAction.COPY ) { // FIXME: SHould probably deal with the others as well. if( p.getDefinition().isMultiple() ) { fn.setProperty( p.getName(), p.getValues() ); } else { fn.setProperty( p.getName(), p.getValue() ); } } } vh.save(); save(); // FIXME: Here. return v; } finally { getSession().setSuper( isSuper ); } } public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException { if( isCheckedOut() ) return; // Nothing happens if( !isNodeType( "mix:versionable" ) ) throw new UnsupportedRepositoryOperationException("Not versionable (8.2.6)"); boolean isSuper = getSession().setSuper( true ); try { setProperty( "jcr:isCheckedOut", true ); // // We don't support multiple predecessors, so this is okay, I think. // setProperty( JCR_PREDECESSORS, new ValueImpl[] { getSession().getValueFactory().createValue( getBaseVersion() ) } ); setProperty( JCR_SUCCESSORS, new ValueImpl[0] ); // // Persist immediately. // save(); } finally { getSession().setSuper( isSuper ); } } public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Node.doneMerge()"); } public VersionImpl getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException { String bvUuid = getProperty( Q_JCR_BASEVERSION ).getString(); return (VersionImpl) getSession().getNodeByUUID( bvUuid ); } public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restore(Version version, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restore(Version version, String relPath, boolean removeExisting) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public void restoreByLabel(String versionLabel, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws NoSuchWorkspaceException, AccessDeniedException, MergeException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException(); } } diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index c9cb355..6fde59e 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,835 +1,839 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.*; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); private static final int DEFAULT_CACHESIZE = 1000; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(true); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { // // It's faster to use a LinkedHashSet here, then copy to an ArrayList // when exiting. // Set<Path> res = new LinkedHashSet<Path>(); for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); - if( parentpath.isParentOf(ni.getInternalPath()) && ni.isNode() && !res.contains(ni.getInternalPath()) ) + if( ni.isNode() ) { - res.add( ni.getInternalPath() ); + Path path = ni.getInternalPath(); + if( parentpath.isParentOf(path) && !res.contains(path) ) + { + res.add( path ); + } } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } ArrayList<Path> ls = new ArrayList<Path>(res.size()); ls.addAll( res ); return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean nodeExists(Path path) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && c.getItem().isNode() ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.nodeExists(m_workspace, path); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.nodeExists( m_workspace, change.getPath() ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } - public Collection<? extends PropertyImpl> getProperties(Path path) throws RepositoryException + public Collection<? extends Path> getProperties(Path path) throws RepositoryException { - HashMap<QName,PropertyImpl> result = new HashMap<QName,PropertyImpl>(); + LinkedHashSet<Path> result = new LinkedHashSet<Path>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { - result.put( pName, (PropertyImpl)m_source.getItem( m_workspace, path.resolve(pName) ) ); + result.add( path.resolve(pName) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been changed. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Iterator<ItemImpl> i = m_changedItems.values(); i.hasNext(); ) { ItemImpl ii = i.next(); if( ii.isNode() == false && ii.getInternalPath().getParentPath().equals(path) ) { - result.put( ii.getInternalPath().getLastComponent(), (PropertyImpl) ii ); + result.add( ii.getInternalPath() ); } } - return result.values(); + return result; } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.nodeExists( m_workspace, path ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { super(); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { super(); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { return c_sessionPathManager.getPath( p ); } public PathManager getPathManager() { return c_sessionPathManager; } public ItemState getState( PathRef m_path ) throws PathNotFoundException { Change c = m_changedItems.getLatestChange( getPath(m_path) ); return c != null ? c.getState() : null; } } diff --git a/src/java/org/priha/core/WorkspaceImpl.java b/src/java/org/priha/core/WorkspaceImpl.java index afd4fd4..311fd08 100644 --- a/src/java/org/priha/core/WorkspaceImpl.java +++ b/src/java/org/priha/core/WorkspaceImpl.java @@ -1,523 +1,521 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.UUID; -import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.observation.ObservationManager; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceRegistryImpl; import org.priha.nodetype.QNodeTypeManager; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.query.PrihaQueryManager; -import org.priha.util.PropertyIteratorImpl; -import org.priha.version.VersionManager; +import org.priha.util.LazyPropertyIteratorImpl; import org.priha.xml.XMLImport; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Implements a JCR Workspace. This class mostly functions as a facade for * ProviderManager, which takes care of the actual repository management. */ public class WorkspaceImpl implements Workspace { private SessionImpl m_session; private String m_name; private ProviderManager m_providerManager; private QNodeTypeManager.Impl m_nodeTypeManager; private Logger log = Logger.getLogger(WorkspaceImpl.class.getName()); /** * Create a new Workspace instance. * * @param session The SessionImpl to which this Workspace is tied to * @param name The name of the Workspace * @param mgr The ProviderManager instance which owns the repository. * @throws RepositoryException If a NodeTypeManager cannot be instantiated. */ public WorkspaceImpl( SessionImpl session, String name, ProviderManager mgr ) throws RepositoryException { m_session = session; m_name = name; m_providerManager = mgr; m_nodeTypeManager = QNodeTypeManager.getManager(this); } /** * Creates a new property implementation without a property definition. * This is meant for providers to create an "empty" property definition, * which the WorkspaceImpl will then update later on. * * @param path * @return * @throws RepositoryException */ public PropertyImpl createPropertyImpl( Path path ) throws RepositoryException { // String name = path.getLastComponent(); //NodeImpl nd = (NodeImpl) m_session.getItem(p); //PropertyDefinition pd = ((GenericNodeType)nd.getPrimaryNodeType()).findPropertyDefinition(name); PropertyImpl pi = new PropertyImpl( m_session, path, null ); return pi; } /** * If removeExisting is true, removes Nodes with conflicting UUIDs. If it's false, * this exists with a ItemExistsException. * * Does not save the Session. * * @param srcNode * @param removeExisting * @throws RepositoryException */ private void checkUUIDs( NodeImpl srcNode, boolean removeExisting ) throws RepositoryException { try { String uuid = srcNode.getUUID(); Node n = getSession().getNodeByUUID( uuid ); if( removeExisting ) { System.out.println("Removing node due to UUID conflict "+n); n.remove(); } else { throw new ItemExistsException("There already exists a Node by UUID "+uuid+" in the destination workspace! "+n.getPath()); } } catch( UnsupportedRepositoryOperationException e ) { // Fine, this node just does not have an UUID. } catch( ItemNotFoundException e ) { // Fine, expected as well. } for( NodeIterator ni = srcNode.getNodes(); ni.hasNext(); ) { checkUUIDs( (NodeImpl)ni.nextNode(), removeExisting ); } } /** * {@inheritDoc} */ public void clone(String srcWorkspace, String srcAbsPath, String destAbsPath, boolean removeExisting) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { checkLock(destAbsPath); getSession().checkWritePermission(); SessionImpl srcSession = getSession().getRepository().login(srcWorkspace); boolean isSuper = m_session.setSuper( true ); try { // // Do the check here, since once we're in super mode, addNode() will happily // allow adding to an indexed path. // if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot clone to a path which ends with an index."); if( removeExisting && getSession().itemExists( destAbsPath ) ) { // getSession().getItem( destAbsPath ).remove(); //getSession().save(); } checkUUIDs( (NodeImpl)srcSession.getItem( srcAbsPath ), removeExisting ); //getSession().save(); copy( srcSession, srcAbsPath, destAbsPath, true ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * {@inheritDoc} */ public void copy(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { copy( getName(), srcAbsPath, destAbsPath ); } /** * Throws a LockException if the given absolute path or any of its child nodes * is locked. */ private void checkLock( String abspath ) throws LockException, RepositoryException { LockManager lm = LockManager.getInstance( this ); if( lm.findLock( PathFactory.getPath( m_session, abspath ) ) != null ) throw new LockException("Destination path "+abspath+" is locked and cannot be modified."); } /** * {@inheritDoc} */ public void copy(String srcWorkspace, String srcAbsPath, String destAbsPath) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Destination path must not end with an index."); SessionImpl srcSession = getSession().getRepository().login( srcWorkspace ); // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); boolean isSuper = m_session.setSuper( true ); try { copy( srcSession, srcAbsPath, destAbsPath, false ); m_session.save(); } finally { m_session.setSuper( isSuper ); srcSession.logout(); } } /** * Checks if the node or any of its parents are checked in. * * @param n * @return * @throws RepositoryException */ protected boolean isCheckedIn( NodeImpl n ) throws RepositoryException { if( !n.isCheckedOut() ) return true; if( n.getInternalPath().isRoot() ) return false; return isCheckedIn( n.getParent() ); } /** * Performs the actual copy, but does not save. * * @param srcSession * @param srcAbsPath * @param destAbsPath * @throws NoSuchWorkspaceException * @throws ConstraintViolationException * @throws VersionException * @throws AccessDeniedException * @throws PathNotFoundException * @throws ItemExistsException * @throws LockException * @throws RepositoryException */ protected void copy(SessionImpl srcSession, String srcAbsPath, String destAbsPath, boolean preserveUUIDs ) throws NoSuchWorkspaceException, ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { Path path = PathFactory.getPath( getSession(), destAbsPath ); if( isCheckedIn( (NodeImpl)m_session.getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( m_session.hasNode( destAbsPath ) ) { NodeImpl nx = getSession().getRootNode().getNode(destAbsPath); if( !nx.getDefinition().allowsSameNameSiblings() ) throw new ItemExistsException("Destination node "+destAbsPath+" already exists, and does not allow same name siblings!"); } NodeImpl srcnode = srcSession.getRootNode().getNode(srcAbsPath); // System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( srcSession.getWorkspace() ); if( lm.hasChildLock( srcnode.getInternalPath() ) ) throw new LockException( "Lock on source path prevents copy" ); NodeImpl destnode = m_session.getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); if( isCheckedIn( destnode ) ) { throw new VersionException("Destination node "+destnode.getPath()+" (or one of its parent nodes) is checked in, and therefore unmodifiable."); } for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); copy( srcSession, child.getPath(), destAbsPath + "/" + relPath, preserveUUIDs ); } - for( PropertyIteratorImpl pi = srcnode.getProperties(); pi.hasNext(); ) + for( LazyPropertyIteratorImpl pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> // "+newDestPath // ); // // The primary type is already set above upon the creation of the Node. // if( p.getQName().equals( JCRConstants.Q_JCR_PRIMARYTYPE )) continue; // // Section 7.1.7; the new node must get a new UUID when copying; // but we allow UUIDs to be preserved for e.g. clone. // if( p.getQName().equals( JCRConstants.Q_JCR_UUID) && !preserveUUIDs ) { destnode.setProperty( p.getName(), UUID.randomUUID().toString() ); } else { // // Copy the property // if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } } } /** * {@inheritDoc} */ public String[] getAccessibleWorkspaceNames() throws RepositoryException { Collection<String> list = m_providerManager.listWorkspaces(); return list.toArray(new String[0]); } /** * {@inheritDoc} */ // FIXME: SuperUserSession leaks. public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession,true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); return importer; } /** * {@inheritDoc} */ public String getName() { return m_name; } /** * {@inheritDoc} */ public NamespaceRegistryImpl getNamespaceRegistry() throws RepositoryException { return RepositoryImpl.getGlobalNamespaceRegistry(); } /** * {@inheritDoc} */ public QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_nodeTypeManager; } /** * Unsupported at the moment. */ public ObservationManager getObservationManager() throws UnsupportedRepositoryOperationException, RepositoryException { throw new UnsupportedRepositoryOperationException("Workspace.getObservationManager()"); // TODO Auto-generated method stub } /** * {@inheritDoc} */ public PrihaQueryManager getQueryManager() throws RepositoryException { return new PrihaQueryManager(getSession()); } /** * {@inheritDoc} */ public SessionImpl getSession() { return m_session; } /** * {@inheritDoc} */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, InvalidSerializedDataException, LockException, AccessDeniedException, RepositoryException { SessionImpl suSession = m_session.getRepository().superUserLogin( m_name ); XMLImport importer = new XMLImport( suSession, true, PathFactory.getPath(m_session,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { throw new RepositoryException("Could not get SAX parser!",e); } catch (SAXException e) { if( e.getException() != null && (e.getException() instanceof RepositoryException) ) { throw (RepositoryException) e.getException(); } throw new InvalidSerializedDataException("Importing failed",e); } finally { suSession.logout(); } } /** * Implemented simply by starting a new Session, which then performs the copy, * and then calling save() on it. */ public void move(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, LockException, RepositoryException { // Superuser does not care about locking, so we'll check it separately. checkLock(destAbsPath); getSession().checkWritePermission(); if( destAbsPath.endsWith("]") ) throw new ConstraintViolationException("Cannot move to a path with an index in the name"); SessionImpl s = m_session.getRepository().superUserLogin( getName() ); try { s.move( srcAbsPath, destAbsPath ); s.save(); } finally { s.logout(); } } /** * Unsupported at the moment. */ public void restore(Version[] versions, boolean removeExisting) throws ItemExistsException, UnsupportedRepositoryOperationException, VersionException, LockException, InvalidItemStateException, RepositoryException { // TODO Auto-generated method stub throw new UnsupportedRepositoryOperationException("Workspace.restore()"); } /** * Performs a logout; to be called by SessionImpl only. */ public void logout() { m_providerManager.close(this); } /** * Checks directly from the repository if an item exists. * * @param path * @return * @throws InvalidPathException */ public boolean nodeExists(Path path) throws RepositoryException { return m_providerManager.nodeExists(this, path); } } diff --git a/src/java/org/priha/util/LazyPropertyIteratorImpl.java b/src/java/org/priha/util/LazyPropertyIteratorImpl.java new file mode 100644 index 0000000..168c73d --- /dev/null +++ b/src/java/org/priha/util/LazyPropertyIteratorImpl.java @@ -0,0 +1,70 @@ +package org.priha.util; + +import java.util.List; +import java.util.NoSuchElementException; + +import javax.jcr.PathNotFoundException; +import javax.jcr.PropertyIterator; +import javax.jcr.RepositoryException; + +import org.priha.core.PropertyImpl; +import org.priha.core.SessionImpl; +import org.priha.path.Path; + +public class LazyPropertyIteratorImpl extends GenericIterator implements PropertyIterator +{ + private SessionImpl m_session; + + public LazyPropertyIteratorImpl( SessionImpl session, List<Path> paths ) + { + super( paths ); + m_session = session; + } + + public PropertyImpl nextProperty() + { + Path p = (Path)super.next(); + + try + { + return (PropertyImpl)m_session.getItem( p ); + } + catch( RepositoryException e ) + { + e.printStackTrace(); + throw new NoSuchElementException("No next property is available: "+e.getMessage()); + } + } + + + public PropertyImpl previousProperty() + { + Path p = (Path)super.previous(); + + try + { + return (PropertyImpl)m_session.getItem( p ); + } + catch( RepositoryException e ) + { + e.printStackTrace(); + throw new NoSuchElementException("No previous property is available: "+e.getMessage()); + } + } + + public PropertyImpl next() + { + return nextProperty(); + } + + public PropertyImpl previous() + { + return previousProperty(); + } + + public PropertyImpl get( int index ) throws PathNotFoundException, RepositoryException + { + return (PropertyImpl) m_session.getItem( (Path) m_list.get(index) ); + } + +} diff --git a/tests/java/org/priha/core/PerformanceTest.java b/tests/java/org/priha/core/PerformanceTest.java index fbff7ab..851159c 100644 --- a/tests/java/org/priha/core/PerformanceTest.java +++ b/tests/java/org/priha/core/PerformanceTest.java @@ -1,782 +1,782 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.ByteArrayInputStream; import java.util.*; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.Release; import org.priha.RepositoryManager; import org.priha.TestUtil; public class PerformanceTest extends TestCase { /** The size of a million can be configured here. ;-) */ - private static final int DEFAULT_ITERATIONS = 100; + private static final int DEFAULT_ITERATIONS = 2000; private int m_iterations = DEFAULT_ITERATIONS; - private static final int BLOB_SIZE = 1024*100; + private static final int BLOB_SIZE = 1024*10; private int m_blobsize = BLOB_SIZE; private static final int NODENAMELEN = 16; private static final int PROPERTYLEN = 16; private Credentials m_creds = new SimpleCredentials("username","password".toCharArray()); private boolean m_memoryProviderTest = true; private boolean m_jackrabbitTest = true; private boolean m_jdbcProviderTest = true; private boolean m_jdbcProviderEhTest = true; private boolean m_fileProviderTest = true; private boolean m_fileProviderEhTest = true; private boolean m_largeTests = true; public void setUp() { String iters = System.getProperty("perftest.iterations"); if( iters != null ) m_iterations = Integer.parseInt(iters); String blobsize = System.getProperty("perftest.blobsize"); if( blobsize != null ) m_blobsize = Integer.parseInt(blobsize)*1024; } public void testMemoryProvider() throws Exception { if( !m_memoryProviderTest ) return; Perf.setTestable("MemoryProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("memorynocache.properties"); millionIterationsTest( rep, m_creds , m_iterations ); } public void testFileProvider() throws Exception { if( !m_fileProviderTest ) return; Perf.setTestable("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("filenocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testFileEhcacheProvider() throws Exception { if( !m_fileProviderEhTest ) return; Perf.setTestable("FileProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("fileehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcProvider() throws Exception { if( !m_jdbcProviderTest ) return; Perf.setTestable("JdbcProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcEhcacheProvider() throws Exception { if( !m_jdbcProviderEhTest ) return; Perf.setTestable("JdbcProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public static Repository getJackrabbitRepository() { try { Class<?> cc = Class.forName("org.apache.jackrabbit.core.TransientRepository"); return (Repository) cc.newInstance(); } catch( Exception e ) { return null; } } public void testJackrabbit() throws Exception { if( !m_jackrabbitTest ) return; Perf.setTestable("Jackrabbit"); Repository rep = getJackrabbitRepository(); if( rep != null ) { millionIterationsTest(rep, m_creds, m_iterations); } else { System.out.println("Skipping Jackrabbit comparison tests; classes not found in classpath"); } } /** Just a dummy test which is executed last and it will print out the * test result. */ public void testPrint() { Perf.print(this); } public static class TesterClass { private Repository m_repository; private Credentials m_creds; private int m_numNodes; private int m_readIters; private byte[] m_blob; ArrayList<String> propertyPaths = new ArrayList<String>(); ArrayList<String> uuids = new ArrayList<String>(); private boolean m_testNewSession = true; private boolean m_testSeqRead = true; private boolean m_testRandRead = true; private boolean m_testUUIDRead = true; private boolean m_testLargeRead = true; private boolean m_testCachedNode = true; private boolean m_testUpdate = true; private boolean m_testExists = true; public TesterClass(Repository rep, Credentials creds, int numIters, byte[] blob) { m_repository = rep; m_creds = creds; m_numNodes = numIters; m_readIters = numIters * 10; m_blob = blob; } public void testNewSession() throws LoginException, RepositoryException { if( !m_testNewSession ) return; // We want to make sure that we don't get the penalty of the first // session here. Session prime = m_repository.login(m_creds); try { // // Test how quickly subsequent sessions can be acquired. // Perf.start("NewSession"); for( int i = 0; i < m_numNodes; i++ ) { Session s2 = m_repository.login(m_creds); s2.logout(); } Perf.stop(m_numNodes); } finally { prime.logout(); } } public void testSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("Save"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID(NODENAMELEN); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); n.addMixin("mix:referenceable"); Property p = n.setProperty( "test", TestUtil.getUniqueID(PROPERTYLEN) ); propertyPaths.add( p.getPath() ); nd.save(); uuids.add( n.getProperty("jcr:uuid").getString() ); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testLargeSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("LargeSave"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID( NODENAMELEN ); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); Property p = n.setProperty( "test", new ByteArrayInputStream(m_blob) ); propertyPaths.add( p.getPath() ); nd.save(); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testSeqRead() throws LoginException, RepositoryException { if( !m_testSeqRead ) return; Session s = m_repository.login(m_creds); try { // // Test how quickly we can read all the properties // of a single node using getNodes(). // Perf.start("SeqRead"); Node nd = s.getRootNode(); for( NodeIterator i = nd.getNodes(); i.hasNext(); ) { Node n = i.nextNode(); // Skip nodes which weren't created in this test. if( n.getName().startsWith("x-") ) { for( NodeIterator i2 = n.getNodes(); i2.hasNext(); ) { Node n2 = i2.nextNode(); Property p = n2.getProperty("test"); assertEquals( p.getName(), PROPERTYLEN, p.getString().length() ); } } } Perf.stop(m_numNodes); } finally { s.logout(); } } public void testRandRead() throws LoginException, RepositoryException { if( !m_testRandRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("RandRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), PROPERTYLEN, ((Property)ii).getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } /** * Tests existing/non-existing nodes in a 50:50 ratio. * * @throws Exception */ public void testExists() throws Exception { if( !m_testExists ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); Perf.start("exists"); - for( int i = 0; i < m_readIters*10; i++ ) + for( int i = 0; i < m_readIters; i++ ) { if( i % 2 == 0 ) { int item = rand.nextInt(propertyPaths.size()); String p = propertyPaths.get( item ); assertTrue( p, s.itemExists( p ) ); } else { String p = "/nonexisting/path"; assertFalse( p, s.itemExists(p) ); } } - Perf.stop(m_readIters*10); + Perf.stop(m_readIters); } finally { s.logout(); } } public void testUUIDRead() throws LoginException, RepositoryException { if( !m_testUUIDRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("UUID"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( uuids.size() ); Node ni = s.getNodeByUUID( uuids.get(item) ); assertEquals( ni.getName(), PROPERTYLEN, ni.getProperty("test").getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testLargeRead() throws LoginException, RepositoryException { if( !m_testLargeRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("LargeRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), m_blob.length, ((Property)ii).getLength()); } Perf.stop(m_readIters); } finally { s.logout(); } } /** * Produces two figures: getProperty and getItem. The same item * is fetched through both methods, and the performance is measured. */ public void testCachedNode() throws RepositoryException { if( !m_testCachedNode ) return; Session s = m_repository.login(m_creds); try { String ss = propertyPaths.get( 0 ); Item ii = s.getItem(ss); Node nd = ii.getParent(); String propName = ii.getName(); // // First, access directly with getProperty() // Perf.start("getProperty"); for( int i = 0; i < m_readIters; i++ ) { Property prop = nd.getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // // Then, with getItem() // Perf.start("getItem"); for( int i = 0; i < m_readIters; i++ ) { Property prop = (Property) s.getItem( ss ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // Finally, with getByUUID() String uuid = uuids.get(0); Perf.start("propUUID"); for( int i = 0; i < m_readIters; i++ ) { Property prop = s.getNodeByUUID( uuid ).getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testUpdate() throws RepositoryException { if( !m_testUpdate ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and updated // Perf.start("Update"); for( int i = 0; i < m_numNodes; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Property ii = (Property)s.getItem( propertyPaths.get(item) ); ii.setValue( "modified result" ); s.save(); } Perf.stop(m_numNodes); } finally { s.logout(); } } } public void millionIterationsTest( Repository rep, Credentials creds, int numIters ) throws Exception { TesterClass tc = new TesterClass( rep, creds, numIters, getBlob() ); try { // // Test how quickly the first session can be opened. // Perf.start("FirstSess"); Session s = rep.login(creds); Perf.stop(1); s.logout(); TestUtil.emptyRepo(rep); tc.testNewSession(); tc.testSave(); tc.testSeqRead(); tc.testRandRead(); tc.testExists(); tc.testUUIDRead(); tc.testUpdate(); tc.testCachedNode(); // // Test how quickly we can then empty the repository. // Perf.start("Remove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); if( m_largeTests ) { // // Large objects // getBlob(); tc.testLargeSave(); tc.testLargeRead(); Perf.start("LargeRemove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); } } catch( Exception t ) { t.printStackTrace(); throw t; } finally { TestUtil.emptyRepo(rep); } } private static byte[] blob; private final byte[] getBlob() { if( blob == null) { blob = new byte[m_blobsize]; // 1 Meg for( int i = 0; i < m_blobsize; i++ ) blob[i] = (byte) (i % 255); } return blob; } public static Test suite() { return new TestSuite( PerformanceTest.class ); } /** * This class stores all results to a local hashmap, which can then be pretty-printed. * */ public static class Perf { private static HashMap<String, HashMap<String, Double>> results = new LinkedHashMap<String,HashMap<String,Double>>(); private static long startTime; private static String currTest; private static String currTestable; public static void setTestable(String p) { currTestable = p; } public static void start( String test ) { currTest = test; startTime = System.nanoTime(); } public static void stop( int iters ) { long stop = System.nanoTime(); long time = stop-startTime; double itersSec = iters/(time/1e9); HashMap<String,Double> hm; hm = results.get(currTestable); if( hm == null ) { hm = new HashMap<String,Double>(); results.put(currTestable, hm); } hm.put(currTest, itersSec); //TestUtil.printSpeed(currProvider+": "+currTest, iters, startTime, stop); } public static void print(PerformanceTest test) { System.out.println("Test results. The number is operations/seconds - larger means faster."); System.out.println("Blob size "+test.m_blobsize/1024+" kB"); System.out.println("Repository size "+test.m_iterations+" nodes"); System.out.println("Priha version "+Release.VERSTR); Repository jr = getJackrabbitRepository(); if( jr != null ) System.out.println("Jackrabbit version "+jr.getDescriptor( Repository.REP_VERSION_DESC )); print(); } public static void print() { ArrayList<String> keys = new ArrayList<String>(); keys.addAll( results.values().iterator().next().keySet() ); Collections.sort(keys); Map.Entry<String, HashMap<String,Double>>[] array = new Map.Entry[0]; array = results.entrySet().toArray(array); int startIdx = 0; int numColumns = 8; while( startIdx < keys.size() ) { System.out.printf("%-30s",""); // Column titles for( int i = startIdx; i < keys.size() && i < startIdx+numColumns; i++ ) { System.out.printf("%12s",keys.get( i )); } System.out.print("\n"); // Values for a single test for( int j = 0; j < array.length; j++ ) { System.out.printf( "%-30s", array[j].getKey() ); for( int i = startIdx; i < keys.size() && i < startIdx+numColumns; i++ ) { String key = keys.get( i ); Double val = array[j].getValue().get(key); if( val != null && val < 1 ) System.out.printf("%12.2f",val); else System.out.printf("%12.0f", val != null ? val : Double.NaN ); } System.out.print("\n"); } startIdx += numColumns; System.out.print( "\n\n" ); } } } }
jalkanen/Priha
ff9ff60c3cfa1aa7d20fcbc6a53f9b265f727f8e
Sped up skip() by getting rid of the looped next().
diff --git a/src/java/org/priha/util/GenericIterator.java b/src/java/org/priha/util/GenericIterator.java index c0e3793..8e69cb9 100644 --- a/src/java/org/priha/util/GenericIterator.java +++ b/src/java/org/priha/util/GenericIterator.java @@ -1,100 +1,93 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import java.util.Iterator; import java.util.List; import java.util.ListIterator; -import java.util.Set; /** * Provides a base class for the different Iterators that JCR defines. * * @author jalkanen */ public abstract class GenericIterator implements Iterator { protected ListIterator<?> m_iterator; protected int m_position; protected int m_size; protected List<?> m_list; public GenericIterator( List<?> list ) { m_iterator = list.listIterator(); m_position = 0; m_size = list.size(); m_list = list; } - public GenericIterator( Set<?> set ) - { - - } public long getPosition() { return m_position; } public long getSize() { return m_size; } public void skip(long skipNum) { - for( int i = 0; i < skipNum; i++ ) - { - next(); - } + m_iterator = m_list.listIterator(m_position+(int)skipNum); + m_position = m_position+(int)skipNum; } public boolean hasNext() { return m_iterator.hasNext(); } public boolean hasPrevious() { return m_iterator.hasPrevious(); } public Object next() { m_position++; return m_iterator.next(); } public Object previous() { m_position--; return m_iterator.previous(); } public void remove() { m_iterator.remove(); m_size--; if( m_size == m_position ) m_position = m_size-1; if( m_position < 0 ) m_position = 0; } }
jalkanen/Priha
8b852bad150cb175b63d0712b094478a8c8c472a
Adding a number of ideas which could be done.
diff --git a/doc/MissingOptimizations.txt b/doc/MissingOptimizations.txt new file mode 100644 index 0000000..039af5e --- /dev/null +++ b/doc/MissingOptimizations.txt @@ -0,0 +1,27 @@ +Optimizations that could be done: + +* FileProvider.mangleName() is called several times - should really call + just once per file name resolve +* itemExists() should really not call the provider twice; have an + Provider.itemExists(Workspace, Path, ItemType?) +* SessionProvider.getProperties() iterates way too much +* FileProvider.remove() should not be calling getPropertyInfo() +* NodeImpl.hasProperty() should use itemExists() and not load via + SessionImpl.hasProperty() +* ProviderManager.getItem() is calling loadNode() twice +* ProviderManager.loadNode() is slow, so it should be avoided when + getting property values +* Some new thinking is needed - a single getItem() needs four calls + into the repo in case of properties: one failed loadNode(), + then a loadNode() [which calls getPropertyValue()], then a + getPropertyValue() for the actual value. +* Since Node/PropertyDefinitions are really only needed at + setProperty()/addNode(), perhaps they could be loaded lazily? +* SessionProvider.listNodes() calls getInternalPath() way too + often + +Optimizations which have been done: +* GenericIterator.skip() is really slow; should actually use the + underlying iterator to do the skipping. DONE +* SessionProvider.getProperties() should really only get the item names, + not the items. DONE
jalkanen/Priha
560368491d1e02527cee5151ecdda09d7e5a6e7d
How about using a Set with a predictable iteration ordering? :-)
diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index d5d7c8c..c9cb355 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,751 +1,751 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.*; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); private static final int DEFAULT_CACHESIZE = 1000; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(true); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { // - // It's faster to use a TreeSet here, then copy to an ArrayList + // It's faster to use a LinkedHashSet here, then copy to an ArrayList // when exiting. // - TreeSet<Path> res = new TreeSet<Path>(); + Set<Path> res = new LinkedHashSet<Path>(); for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); if( parentpath.isParentOf(ni.getInternalPath()) && ni.isNode() && !res.contains(ni.getInternalPath()) ) { res.add( ni.getInternalPath() ); } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } ArrayList<Path> ls = new ArrayList<Path>(res.size()); ls.addAll( res ); return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean nodeExists(Path path) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && c.getItem().isNode() ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.nodeExists(m_workspace, path); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.nodeExists( m_workspace, change.getPath() ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends PropertyImpl> getProperties(Path path) throws RepositoryException { HashMap<QName,PropertyImpl> result = new HashMap<QName,PropertyImpl>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.put( pName, (PropertyImpl)m_source.getItem( m_workspace, path.resolve(pName) ) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been changed. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Iterator<ItemImpl> i = m_changedItems.values(); i.hasNext(); ) { ItemImpl ii = i.next(); if( ii.isNode() == false && ii.getInternalPath().getParentPath().equals(path) ) { result.put( ii.getInternalPath().getLastComponent(), (PropertyImpl) ii ); } } return result.values(); } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) )
jalkanen/Priha
579365c70cfa7f0eac8b02f8be52a3d82013c454
Nice speedups to listNodes() by using a TreeSet instead of ArrayList.
diff --git a/ChangeLog b/ChangeLog index 926fa76..ce15a71 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,522 +1,527 @@ 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.6 * Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations. + * Speeded up SessionProvider.listNodes(), causing a fairly nice + boost to JdbcProvider. + + * Added dist-install target to build.xml. + 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index b60a855..d5d7c8c 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,773 +1,779 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.*; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); private static final int DEFAULT_CACHESIZE = 1000; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); m_changedItems = new ChangeStore(true); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { - List<Path> res = new ArrayList<Path>(); + // + // It's faster to use a TreeSet here, then copy to an ArrayList + // when exiting. + // + TreeSet<Path> res = new TreeSet<Path>(); for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); if( parentpath.isParentOf(ni.getInternalPath()) && ni.isNode() && !res.contains(ni.getInternalPath()) ) { res.add( ni.getInternalPath() ); } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } - return res; + ArrayList<Path> ls = new ArrayList<Path>(res.size()); + ls.addAll( res ); + return ls; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean nodeExists(Path path) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && c.getItem().isNode() ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.nodeExists(m_workspace, path); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.nodeExists( m_workspace, change.getPath() ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends PropertyImpl> getProperties(Path path) throws RepositoryException { HashMap<QName,PropertyImpl> result = new HashMap<QName,PropertyImpl>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.put( pName, (PropertyImpl)m_source.getItem( m_workspace, path.resolve(pName) ) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been changed. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Iterator<ItemImpl> i = m_changedItems.values(); i.hasNext(); ) { ItemImpl ii = i.next(); if( ii.isNode() == false && ii.getInternalPath().getParentPath().equals(path) ) { result.put( ii.getInternalPath().getLastComponent(), (PropertyImpl) ii ); } } return result.values(); } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.nodeExists( m_workspace, path ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key.
jalkanen/Priha
796f25b55fb06e7f9753bdf96bba716af08db422
Added dist-install target with lots of Ant magic.
diff --git a/build.xml b/build.xml index 119f115..3b1aec1 100644 --- a/build.xml +++ b/build.xml @@ -1,289 +1,364 @@ <?xml version="1.0"?> <!-- Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project name="Priha" default="jar"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> <include name="*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> <!-- Jackrabbit is only included if it has been installed with maven --> <fileset dir="${user.home}"> <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> <include name=".m2/repository/commons-collections/**/*3.2.jar"/> <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> </fileset> </path> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> <src path="src/java"/> <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> <src path="tests/java"/> <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> <delete dir="tests/build"/> </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> <!-- ***************************************************************** --> <!-- Distribution package building. Use "ant dist" to build the distro package, and "ant srczip" to create a source tarball. --> <target name="srczip" depends="compile"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}-src.zip"> <zipfileset dir="." excludes="build/** tests/build/** repository*/** tests/reports/** *.log doc/javadoc/**" prefix="priha-${version}"/> </zip> </target> <target name="dist" depends="jar,javadoc"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> - <zip zipfile="build/priha-${version}.zip"> + <zip zipfile="build/priha-${version}-bin.zip"> <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> <zipfileset dir="." includes="ChangeLog README LICENSE NOTICE doc/**" prefix="priha-${version}"/> <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> <zipfileset dir="lib" includes="ehcache-*.jar hsqldb-*.jar" prefix="priha-${version}/extras-lib"/> </zip> </target> + <!-- + + Installs the distribution archives by checking out the SVN project. + + Needs svn and gpg binaries in the shell path. + + --> + <target name="dist-install" depends=""> + <java classpath="build" outputproperty="version" classname="org.priha.Release" + args="-versiononly"> + </java> + + <!-- Check out code --> + <exec executable="svn"> + <arg value="co"/> + <arg value="https://svn.ecyrd.com/repos/priha/site"/> + <arg value="build/priha-site"/> + </exec> + + <!-- Install archives --> + <property name="destdir" value="build/priha-site/WebContent/download/priha-${version}"/> + <delete dir="${destdir}"/> + <mkdir dir="${destdir}"/> + <copy file="build/priha-${version}-bin.zip" todir="${destdir}"/> + <copy file="build/priha-${version}-src.zip" todir="${destdir}"/> + + <exec executable="gpg"> + <arg value="-sba"/> + <arg value="${destdir}/priha-${version}-src.zip"/> + </exec> + + <exec executable="gpg"> + <arg value="-sba"/> + <arg value="${destdir}/priha-${version}-bin.zip"/> + </exec> + + <!-- Figure out file lengths. We need a bit of Javascript to build the + sizes in megabytes --> + <length file="build/priha-${version}-bin.zip" property="binsize"/> + <length file="build/priha-${version}-src.zip" property="srcsize"/> + + <script language="javascript"> + <![CDATA[ + var binsize = project.getProperty("binsize"); + var srcsize = project.getProperty("srcsize"); + var binmegas = Math.round((binsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); + var srcmegas = Math.round((srcsize / (1024*1024)) * Math.pow(10,2)) / Math.pow(10,2); + project.setNewProperty("binsizemegs", binmegas); + project.setNewProperty("srcsizemegs", srcmegas); + ]]> + </script> + + <!-- Modify page --> + <loadfile property="message" srcFile="build/priha-site/downloadmessage.html"> + <filterchain> + <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens"> + <param type="token" name="srcurl" value="download/priha-${version}/priha-${version}-src.zip"/> + <param type="token" name="binurl" value="download/priha-${version}/priha-${version}-bin.zip"/> + <param type="token" name="version" value="${version}"/> + <param type="token" name="srcsize" value="${srcsizemegs}"/> + <param type="token" name="binsize" value="${binsizemegs}"/> + </filterreader> + </filterchain> + </loadfile> + + <replaceregexp file="build/priha-site/WebContent/download.html" + flags="gs" + match="&lt;!-- STARTMAGIC -->(.*)&lt;!-- ENDMAGIC -->" + replace="&lt;!-- STARTMAGIC -->${message}&lt;!-- ENDMAGIC -->"/> + + <echo> + OK, I'm done. Please examine the contents of build/priha-site/WebContent/download.html + prior to checking in the code with "svn commit". + </echo> + </target> </project>
jalkanen/Priha
e303f887b92b66b071e3d266393e8e251967a602
Now has multi-column printing and a new test for itemExists().
diff --git a/tests/java/org/priha/core/PerformanceTest.java b/tests/java/org/priha/core/PerformanceTest.java index 446b8e4..fbff7ab 100644 --- a/tests/java/org/priha/core/PerformanceTest.java +++ b/tests/java/org/priha/core/PerformanceTest.java @@ -1,723 +1,782 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.ByteArrayInputStream; import java.util.*; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.Release; import org.priha.RepositoryManager; import org.priha.TestUtil; -import org.priha.core.RepositoryImpl; public class PerformanceTest extends TestCase { /** The size of a million can be configured here. ;-) */ - private static final int DEFAULT_ITERATIONS = 200; + private static final int DEFAULT_ITERATIONS = 100; private int m_iterations = DEFAULT_ITERATIONS; private static final int BLOB_SIZE = 1024*100; private int m_blobsize = BLOB_SIZE; private static final int NODENAMELEN = 16; private static final int PROPERTYLEN = 16; private Credentials m_creds = new SimpleCredentials("username","password".toCharArray()); private boolean m_memoryProviderTest = true; private boolean m_jackrabbitTest = true; private boolean m_jdbcProviderTest = true; private boolean m_jdbcProviderEhTest = true; private boolean m_fileProviderTest = true; private boolean m_fileProviderEhTest = true; private boolean m_largeTests = true; public void setUp() { String iters = System.getProperty("perftest.iterations"); if( iters != null ) m_iterations = Integer.parseInt(iters); String blobsize = System.getProperty("perftest.blobsize"); if( blobsize != null ) m_blobsize = Integer.parseInt(blobsize)*1024; } public void testMemoryProvider() throws Exception { if( !m_memoryProviderTest ) return; Perf.setTestable("MemoryProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("memorynocache.properties"); millionIterationsTest( rep, m_creds , m_iterations ); } public void testFileProvider() throws Exception { if( !m_fileProviderTest ) return; Perf.setTestable("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("filenocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testFileEhcacheProvider() throws Exception { if( !m_fileProviderEhTest ) return; Perf.setTestable("FileProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("fileehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcProvider() throws Exception { if( !m_jdbcProviderTest ) return; Perf.setTestable("JdbcProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcEhcacheProvider() throws Exception { if( !m_jdbcProviderEhTest ) return; Perf.setTestable("JdbcProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public static Repository getJackrabbitRepository() { try { Class<?> cc = Class.forName("org.apache.jackrabbit.core.TransientRepository"); return (Repository) cc.newInstance(); } catch( Exception e ) { return null; } } public void testJackrabbit() throws Exception { if( !m_jackrabbitTest ) return; Perf.setTestable("Jackrabbit"); Repository rep = getJackrabbitRepository(); if( rep != null ) { millionIterationsTest(rep, m_creds, m_iterations); } else { System.out.println("Skipping Jackrabbit comparison tests; classes not found in classpath"); } } /** Just a dummy test which is executed last and it will print out the * test result. */ public void testPrint() { Perf.print(this); } public static class TesterClass { private Repository m_repository; private Credentials m_creds; private int m_numNodes; private int m_readIters; private byte[] m_blob; ArrayList<String> propertyPaths = new ArrayList<String>(); ArrayList<String> uuids = new ArrayList<String>(); private boolean m_testNewSession = true; private boolean m_testSeqRead = true; private boolean m_testRandRead = true; private boolean m_testUUIDRead = true; private boolean m_testLargeRead = true; private boolean m_testCachedNode = true; private boolean m_testUpdate = true; - + private boolean m_testExists = true; + public TesterClass(Repository rep, Credentials creds, int numIters, byte[] blob) { m_repository = rep; m_creds = creds; m_numNodes = numIters; m_readIters = numIters * 10; m_blob = blob; } public void testNewSession() throws LoginException, RepositoryException { if( !m_testNewSession ) return; // We want to make sure that we don't get the penalty of the first // session here. Session prime = m_repository.login(m_creds); try { // // Test how quickly subsequent sessions can be acquired. // Perf.start("NewSession"); for( int i = 0; i < m_numNodes; i++ ) { Session s2 = m_repository.login(m_creds); s2.logout(); } Perf.stop(m_numNodes); } finally { prime.logout(); } } public void testSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("Save"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID(NODENAMELEN); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); n.addMixin("mix:referenceable"); Property p = n.setProperty( "test", TestUtil.getUniqueID(PROPERTYLEN) ); propertyPaths.add( p.getPath() ); nd.save(); uuids.add( n.getProperty("jcr:uuid").getString() ); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testLargeSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("LargeSave"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID( NODENAMELEN ); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); Property p = n.setProperty( "test", new ByteArrayInputStream(m_blob) ); propertyPaths.add( p.getPath() ); nd.save(); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testSeqRead() throws LoginException, RepositoryException { if( !m_testSeqRead ) return; Session s = m_repository.login(m_creds); try { // // Test how quickly we can read all the properties // of a single node using getNodes(). // Perf.start("SeqRead"); Node nd = s.getRootNode(); for( NodeIterator i = nd.getNodes(); i.hasNext(); ) { Node n = i.nextNode(); // Skip nodes which weren't created in this test. if( n.getName().startsWith("x-") ) { for( NodeIterator i2 = n.getNodes(); i2.hasNext(); ) { Node n2 = i2.nextNode(); Property p = n2.getProperty("test"); assertEquals( p.getName(), PROPERTYLEN, p.getString().length() ); } } } Perf.stop(m_numNodes); } finally { s.logout(); } } public void testRandRead() throws LoginException, RepositoryException { if( !m_testRandRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("RandRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), PROPERTYLEN, ((Property)ii).getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } + /** + * Tests existing/non-existing nodes in a 50:50 ratio. + * + * @throws Exception + */ + public void testExists() throws Exception + { + if( !m_testExists ) return; + + Session s = m_repository.login(m_creds); + + try + { + Random rand = new Random(); + + Perf.start("exists"); + + for( int i = 0; i < m_readIters*10; i++ ) + { + if( i % 2 == 0 ) + { + int item = rand.nextInt(propertyPaths.size()); + + String p = propertyPaths.get( item ); + assertTrue( p, s.itemExists( p ) ); + } + else + { + String p = "/nonexisting/path"; + assertFalse( p, s.itemExists(p) ); + } + } + + Perf.stop(m_readIters*10); + } + finally + { + s.logout(); + } + } public void testUUIDRead() throws LoginException, RepositoryException { if( !m_testUUIDRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("UUID"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( uuids.size() ); Node ni = s.getNodeByUUID( uuids.get(item) ); assertEquals( ni.getName(), PROPERTYLEN, ni.getProperty("test").getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testLargeRead() throws LoginException, RepositoryException { if( !m_testLargeRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("LargeRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), m_blob.length, ((Property)ii).getLength()); } Perf.stop(m_readIters); } finally { s.logout(); } } /** * Produces two figures: getProperty and getItem. The same item * is fetched through both methods, and the performance is measured. */ public void testCachedNode() throws RepositoryException { if( !m_testCachedNode ) return; Session s = m_repository.login(m_creds); try { String ss = propertyPaths.get( 0 ); Item ii = s.getItem(ss); Node nd = ii.getParent(); String propName = ii.getName(); // // First, access directly with getProperty() // Perf.start("getProperty"); for( int i = 0; i < m_readIters; i++ ) { Property prop = nd.getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // // Then, with getItem() // Perf.start("getItem"); for( int i = 0; i < m_readIters; i++ ) { Property prop = (Property) s.getItem( ss ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // Finally, with getByUUID() String uuid = uuids.get(0); Perf.start("propUUID"); for( int i = 0; i < m_readIters; i++ ) { Property prop = s.getNodeByUUID( uuid ).getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testUpdate() throws RepositoryException { if( !m_testUpdate ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and updated // Perf.start("Update"); for( int i = 0; i < m_numNodes; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Property ii = (Property)s.getItem( propertyPaths.get(item) ); ii.setValue( "modified result" ); s.save(); } Perf.stop(m_numNodes); } finally { s.logout(); } } } public void millionIterationsTest( Repository rep, Credentials creds, int numIters ) throws Exception { TesterClass tc = new TesterClass( rep, creds, numIters, getBlob() ); try { // // Test how quickly the first session can be opened. // Perf.start("FirstSess"); Session s = rep.login(creds); Perf.stop(1); s.logout(); TestUtil.emptyRepo(rep); tc.testNewSession(); tc.testSave(); tc.testSeqRead(); tc.testRandRead(); + tc.testExists(); + tc.testUUIDRead(); tc.testUpdate(); tc.testCachedNode(); // // Test how quickly we can then empty the repository. // Perf.start("Remove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); if( m_largeTests ) { // // Large objects // getBlob(); tc.testLargeSave(); tc.testLargeRead(); Perf.start("LargeRemove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); } } catch( Exception t ) { t.printStackTrace(); throw t; } finally { TestUtil.emptyRepo(rep); } } private static byte[] blob; private final byte[] getBlob() { if( blob == null) { blob = new byte[m_blobsize]; // 1 Meg for( int i = 0; i < m_blobsize; i++ ) blob[i] = (byte) (i % 255); } return blob; } public static Test suite() { return new TestSuite( PerformanceTest.class ); } /** * This class stores all results to a local hashmap, which can then be pretty-printed. * */ public static class Perf { private static HashMap<String, HashMap<String, Double>> results = new LinkedHashMap<String,HashMap<String,Double>>(); private static long startTime; private static String currTest; private static String currTestable; public static void setTestable(String p) { currTestable = p; } public static void start( String test ) { currTest = test; startTime = System.nanoTime(); } public static void stop( int iters ) { long stop = System.nanoTime(); long time = stop-startTime; double itersSec = iters/(time/1e9); HashMap<String,Double> hm; hm = results.get(currTestable); if( hm == null ) { hm = new HashMap<String,Double>(); results.put(currTestable, hm); } hm.put(currTest, itersSec); //TestUtil.printSpeed(currProvider+": "+currTest, iters, startTime, stop); } public static void print(PerformanceTest test) { System.out.println("Test results. The number is operations/seconds - larger means faster."); System.out.println("Blob size "+test.m_blobsize/1024+" kB"); System.out.println("Repository size "+test.m_iterations+" nodes"); System.out.println("Priha version "+Release.VERSTR); Repository jr = getJackrabbitRepository(); if( jr != null ) System.out.println("Jackrabbit version "+jr.getDescriptor( Repository.REP_VERSION_DESC )); print(); } public static void print() { ArrayList<String> keys = new ArrayList<String>(); keys.addAll( results.values().iterator().next().keySet() ); Collections.sort(keys); - - System.out.printf("%-30s",""); - for( String key : keys ) - { - System.out.printf("%12s",key); - } - System.out.print("\n"); - - for( Map.Entry<String,HashMap<String,Double>> e : results.entrySet() ) + + Map.Entry<String, HashMap<String,Double>>[] array = new Map.Entry[0]; + + array = results.entrySet().toArray(array); + + int startIdx = 0; + int numColumns = 8; + while( startIdx < keys.size() ) { - System.out.printf( "%-30s", e.getKey() ); + System.out.printf("%-30s",""); - for( String key : keys ) + // Column titles + for( int i = startIdx; i < keys.size() && i < startIdx+numColumns; i++ ) { - Double val = e.getValue().get(key); - - if( val != null && val < 1 ) System.out.printf("%12.2f",val); - else System.out.printf("%12.0f", val != null ? val : Double.NaN ); + System.out.printf("%12s",keys.get( i )); } System.out.print("\n"); + + // Values for a single test + for( int j = 0; j < array.length; j++ ) + { + System.out.printf( "%-30s", array[j].getKey() ); + + for( int i = startIdx; i < keys.size() && i < startIdx+numColumns; i++ ) + { + String key = keys.get( i ); + Double val = array[j].getValue().get(key); + + if( val != null && val < 1 ) System.out.printf("%12.2f",val); + else System.out.printf("%12.0f", val != null ? val : Double.NaN ); + } + System.out.print("\n"); + } + + startIdx += numColumns; + + System.out.print( "\n\n" ); } } } }
jalkanen/Priha
148a93541cbe5198b2b260645088c106c29a32ea
Slightly clarified exception message in some cases.
diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index 6f0611e..b60a855 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -100,730 +100,730 @@ public class SessionProvider * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { List<Path> res = new ArrayList<Path>(); for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); if( parentpath.isParentOf(ni.getInternalPath()) && ni.isNode() && !res.contains(ni.getInternalPath()) ) { res.add( ni.getInternalPath() ); } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } return res; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean nodeExists(Path path) throws RepositoryException { Change c = m_changedItems.getLatestChange(path); if( c != null && c.getItem().isNode() ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.nodeExists(m_workspace, path); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.nodeExists( m_workspace, change.getPath() ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { - throw new InvalidItemStateException("No parent available."); + throw new InvalidItemStateException("No parent available for "+ni.getPath()); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends PropertyImpl> getProperties(Path path) throws RepositoryException { HashMap<QName,PropertyImpl> result = new HashMap<QName,PropertyImpl>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.put( pName, (PropertyImpl)m_source.getItem( m_workspace, path.resolve(pName) ) ); } } catch( RepositoryException e ) { ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been changed. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Iterator<ItemImpl> i = m_changedItems.values(); i.hasNext(); ) { ItemImpl ii = i.next(); if( ii.isNode() == false && ii.getInternalPath().getParentPath().equals(path) ) { result.put( ii.getInternalPath().getLastComponent(), (PropertyImpl) ii ); } } return result.values(); } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.nodeExists( m_workspace, path ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { super(); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { super(); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { return c_sessionPathManager.getPath( p ); } public PathManager getPathManager() { return c_sessionPathManager; } public ItemState getState( PathRef m_path ) throws PathNotFoundException { Change c = m_changedItems.getLatestChange( getPath(m_path) ); return c != null ? c.getState() : null; } }
jalkanen/Priha
430e88323a3c7311f068b086777aff5f8b7b5e67
Added some speedups to ChangeStore, which now uses an internal HashMap to find the latest change. Also, changed the internal implementation from LinkedList to ArrayList which speeds up iteration performance. This gives approx four times the speed increase to very large remove() and save() operations.
diff --git a/ChangeLog b/ChangeLog index 65b31c5..926fa76 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,522 @@ +2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.6.6 + + * Added some speedups to ChangeStore, which now uses an internal + HashMap to find the latest change. Also, changed the internal + implementation from LinkedList to ArrayList which speeds up + iteration performance. This gives approx four times the speed + increase to very large remove() and save() operations. + 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 3229396..92bbf26 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,130 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ - public static final int MINORREVISION = 5; + public static final int MINORREVISION = 6; /** * E.g. "alpha" or "beta". */ public static final String POSTFIX = "svn"; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index fd1b95a..b97698d 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -973,1025 +973,1025 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } if( value == null ) { removeProperty(prop); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); } // FIXME: No rollback support public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { if( getState() == ItemState.NEW ) throw new InvalidItemStateException("Cannot call save on newly added node "+getInternalPath()); internalSave(); } public int compareTo(Node nd) { try { return getPath().compareTo(nd.getPath()); } catch( RepositoryException e ) { return 0; } // FIXME: This should never occur } public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { remove(false); } /** * If isRemoving = true, will remove subnodes without question. */ private void remove(boolean isRemoving) throws VersionException, LockException, ConstraintViolationException, RepositoryException { if( getState() == ItemState.REMOVED ) { // System.out.println(getPath()+" has already been removed"); return; // Die nicely } Path path = getInternalPath(); - if( !m_session.m_provider.nodeExistsInRepository( path ) && m_session.m_provider.m_changedItems.get(path) == null ) + if( !m_session.m_provider.nodeExistsInRepository( path ) && m_session.m_provider.m_changedItems.getLatestItem(path) == null ) { m_session.m_provider.m_changedItems.dump(); throw new InvalidItemStateException("Item has already been removed by another Session "+getPath()); } if( path.isRoot() || path.equals( JCRConstants.Q_JCR_SYSTEM_PATH ) ) { return; // Refuse to remove } NodeImpl parent = getParent(); NodeType parentType = parent.getPrimaryNodeType(); if( !getSession().isSuper() ) { // Anything from under /jcr:system cannot be deleted by the user if( JCRConstants.Q_JCR_SYSTEM_PATH.isParentOf( path )) return; if( getParent().isLockedWithoutToken() ) throw new LockException("The parent is locked, so you cannot remove it."); if( !parentType.canRemoveItem(getName()) && getParent().getState() != ItemState.REMOVED && !isRemoving ) { throw new ConstraintViolationException("Attempted to delete a mandatory child node:"+getInternalPath()); } } QLock li = m_lockManager.getLock( path ); if( li != null ) m_lockManager.removeLock( li ); // // Remove version history // if( isNodeType( "mix:versionable" ) ) { // // Version histories cannot be removed unless you have a // superuser session. // boolean isSuper = m_session.setSuper(true); try { getVersionHistory().remove(); } catch( UnsupportedRepositoryOperationException e ) { // This may happen if you've just created a Node, then hit remove() on it immediately, since // in that case, we do not have an UUID yet. } finally { m_session.setSuper( isSuper ); } } // // Removal happens in a depth-first manner. // // // Remove children. We do this in a reverse order in order // not to force annoying moves for same-name siblings. It's just faster. // LazyNodeIteratorImpl ndi = (LazyNodeIteratorImpl) getNodes(); ndi.skip( ndi.getSize() ); while( ndi.hasPrevious() ) { NodeImpl nd = ndi.previousNode(); // System.out.println("REMOVING "+nd.getPath()); nd.remove(true); } boolean isSuper = m_session.setSuper(true); // // Remove properties // for( PropertyIterator pit = getProperties(); pit.hasNext(); ) { pit.nextProperty().remove(); } // This is a hack which just resets the state and then adds this to the remove queue. FIXME! // m_state = ItemState.UPDATED; enterState( ItemState.REMOVED ); // // Fix same name siblings, but don't bother if the parent is already removed. // Again, we go for the super session. // try { int myIndex = getInternalPath().getLastComponent().getIndex(); if( !isRemoving ) { for( NodeIterator ni = getParent().getNodes( getName() ); ni.hasNext(); ) { NodeImpl n = (NodeImpl)ni.nextNode(); int siblingIndex = n.getInternalPath().getLastComponent().getIndex(); if( myIndex >= siblingIndex ) continue; Path destPath = new Path(n.getParent().getInternalPath(), new Path.Component(getQName(),siblingIndex-1) ); // System.out.println("Moving "+n+" to "+destPath); // m_session.m_provider.m_changedItems.dump(); getSession().move( n.getInternalPath().toString( m_session ), destPath.toString( m_session ) ); } } } finally { m_session.setSuper(isSuper); } log.finer("Removed "+getPath()); } /** * Locates a PropertyDefinition for the given property name from the array of * the mixintypes and the primary type for this Node. * * @param propertyName The QName of the property to look for * @param multiple Is this a multiproperty or a single property? * @return A valid PropertyDefinition, or null, if it cannot be located. * @throws RepositoryException If mixin node types cannot be determined. */ public QPropertyDefinition findPropertyDefinition(QName propertyName,boolean multiple) throws RepositoryException { QPropertyDefinition qp; // // Mixin types can override the primary type; especially since the // primary type can contain a wildcard. // for( NodeType nt : getMixinNodeTypes() ) { QNodeType qnt = ((QNodeType.Impl)nt).getQNodeType(); qp = qnt.findPropertyDefinition(propertyName, multiple); if( qp != null ) return qp; } return getPrimaryQNodeType().findPropertyDefinition(propertyName, multiple); } /** * Assumes nothing, goes through the properties, makes sure all things are correct. */ public void sanitize() throws RepositoryException { // log.finest("Sanitizing node "+getInternalPath()); if( m_definition == null ) { try { @SuppressWarnings("unused") PropertyImpl primarytype = getProperty( Q_JCR_PRIMARYTYPE ); } catch( Exception e ) { if( getInternalPath().isRoot() ) { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, "nt:unstructured", PropertyType.NAME ); pix.enterState(ItemState.NEW); } else { PropertyImpl pix = internalSetProperty( Q_JCR_PRIMARYTYPE, assignChildType( getInternalPath().getLastComponent() ).toString(), PropertyType.NAME ); pix.enterState(ItemState.NEW); } } if( getParent() != null ) { QNodeType mytype = getPrimaryQNodeType(); m_definition = getParent().getPrimaryQNodeType().findNodeDefinition( mytype.getQName() ); } else { // FIXME: Not correct m_definition = QNodeTypeManager.getInstance().findNodeDefinition( Q_NT_UNSTRUCTURED ); } if( m_definition == null ) { throw new RepositoryException("Cannot assign a node definition for "+getInternalPath()); } } // autoCreateProperties(); QNodeType mytype = getPrimaryQNodeType(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl pi = (PropertyImpl)i.next(); if( pi.getDefinition() == null ) { QPropertyDefinition pd = mytype.findPropertyDefinition( pi.getQName(), false ); // FIXME: Really? pi.m_definition = pd.new Impl(m_session); // FIXME: Inoptimal } } } /** * We consider nodes to be equal if they have the exact same path, and * all the properties are equal too. */ @Override public boolean equals(Object obj) { if( obj == this ) return true; if( obj instanceof NodeImpl ) { NodeImpl ni = (NodeImpl) obj; if( !ni.getInternalPath().equals(getInternalPath()) ) return false; if( !ni.m_session.getWorkspace().getName().equals(m_session.getWorkspace().getName()) ) return false; // All tests have succeeded return true; } return false; } @Override protected void preSave() throws RepositoryException { super.preSave(); } /** * Checks the mandatory properties for this Nodetype and throws a ConstraintViolationException * if it's not existing. * * @param nt * @throws RepositoryException */ void checkMandatoryProperties(QNodeType nt) throws RepositoryException { for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isMandatory() && !hasProperty(pd.getQName()) ) { throw new ConstraintViolationException("Node "+getInternalPath()+" is missing property "+pd.getQName()); } } } /* ============================================================ * * Mixins * */ public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { ValueFactory vf = m_session.getValueFactory(); NodeType mixin = getNodeTypeManager().getNodeType(mixinName); if( !mixin.isMixin() ) throw new NoSuchNodeTypeException("Type "+mixinName+" is not a mixin type!"); if( isLockedWithoutToken() ) throw new LockException( "Node is locked, so cannot add new mixin types." ); if( !isCheckedOut() ) throw new VersionException( "Node is not checked out, so cannot add new mixin types."); boolean oldsuper = m_session.setSuper( true ); try { Property p; p = getProperty(Q_JCR_MIXINTYPES); Value[] v = p.getValues(); Value[] newval = new Value[v.length+1]; for( int i = 0; i < v.length; i++ ) { newval[i] = v[i]; } newval[newval.length-1] = vf.createValue(mixinName,PropertyType.NAME); PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, newval, PropertyType.NAME ); pi.enterState(ItemState.UPDATED); } catch( PathNotFoundException e ) { Value[] values = new Value[] { vf.createValue(mixinName,PropertyType.NAME) }; PropertyImpl pi = internalSetProperty( Q_JCR_MIXINTYPES, values, PropertyType.NAME ); pi.enterState(ItemState.NEW); } finally { m_session.setSuper( oldsuper ); } //autoCreateProperties(); } public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException { if( isLocked() ) return false; NodeType nt = getNodeTypeManager().getNodeType( mixinName ); if( !nt.isMixin() ) { throw new NoSuchNodeTypeException(mixinName+" is not a mixin type!"); } if( hasMixinType(nt.getName()) ) { return false; } if( !isCheckedOut() ) return false; // FIXME: This is a bit complicated and slow. if( mixinName.equals("mix:versionable") && m_session.getRepository().getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED).equals("false") ) return false; return true; } boolean hasMixinType(String mixinType) { try { Property pi = getProperty( Q_JCR_MIXINTYPES ); for( Value v : pi.getValues() ) { String mixin = v.getString(); if( mixin.equals(mixinType) ) return true; } } catch( RepositoryException e ) {} return false; } public NodeType[] getMixinNodeTypes() throws RepositoryException { ArrayList<NodeType> mixinTypes = new ArrayList<NodeType>(); // // If there are no mixin types, then let's just return an empty array. // try { Property p = getProperty( Q_JCR_MIXINTYPES ); for( Value v : p.getValues() ) { NodeType nt = m_session.getWorkspace().getNodeTypeManager().getNodeType( v.getString() ); mixinTypes.add( nt ); } } catch( RepositoryException e ) {} return mixinTypes.toArray( new NodeType[0] ); } public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( isLocked() ) throw new LockException("Node locked, cannot remove mixin"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); Property mixinTypes = getProperty("jcr:mixinTypes"); Value[] vals = mixinTypes.getValues(); boolean found = false; for( int i = 0; i < vals.length; i++ ) { if( vals[i].getString().equals(mixinName) ) { vals[i] = null; found = true; } } if( found ) { mixinTypes.setValue( vals ); } else { throw new NoSuchNodeTypeException("No such mixin type to remove: "+mixinName); } } /*============================================================================== * * Locking * */ LockManager m_lockManager = LockManager.getInstance(getSession().getWorkspace()); public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { if( !hasMixinType("mix:lockable") ) throw new UnsupportedRepositoryOperationException("This node is not lockable: "+getInternalPath()); if( getState() == ItemState.NEW ) throw new LockException("This node has no persistent state"); if( isModified() ) throw new InvalidItemStateException("You may only lock Nodes which are not currently modified"); if( isDeep && m_lockManager.hasChildLock(getInternalPath()) ) { throw new LockException("A child of this node already holds a lock, so you cannot deep lock this node."); } if( isLocked() ) { throw new LockException("This Node is already locked."); } QLock lock = new QLock( this, isDeep, isSessionScoped ); m_session.addLockToken( lock.getToken() ); setProperty("jcr:lockOwner", lock.getLockOwner()); setProperty("jcr:lockIsDeep", isDeep); save(); m_lockManager.addLock( lock ); return lock.getLockInstance(m_session); } public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException { QLock lock = m_lockManager.getLock( getInternalPath() ); if( lock == null ) throw new LockException("This Node has not been locked."); if( lock.getLockToken(m_session) == null ) throw new LockException("This Session does not own this Lock, so it cannot be unlocked."); if( isModified() ) throw new InvalidItemStateException("This Node must not be modified prior to unlocking"); Property p = getProperty("jcr:lockOwner"); p.remove(); p = getProperty("jcr:lockIsDeep"); p.remove(); diff --git a/src/java/org/priha/core/SessionProvider.java b/src/java/org/priha/core/SessionProvider.java index 6ebf499..6f0611e 100644 --- a/src/java/org/priha/core/SessionProvider.java +++ b/src/java/org/priha/core/SessionProvider.java @@ -1,829 +1,829 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeType; import org.priha.nodetype.QNodeType; import org.priha.path.*; import org.priha.providers.StoreTransaction; import org.priha.util.*; import org.priha.util.ChangeStore.Change; import org.priha.version.VersionManager; /** * This is a special provider which stores the state of the Session. * <p> * At the moment this could be O(N) depending on the size of the unsaved items. * */ public class SessionProvider { private ItemStore m_source; private WorkspaceImpl m_workspace; ChangeStore m_changedItems; // TODO: Back to private // FIXME: Should probably be elsewhere private static PathManager c_sessionPathManager = new PathManager(); private static final int DEFAULT_CACHESIZE = 1000; private Map<PathRef,ItemImpl> m_fetchedItems; private Map<String,NodeImpl> m_uuidMap; private Logger log = Logger.getLogger(SessionProvider.class.getName()); public SessionProvider( SessionImpl session, ItemStore source ) { m_source = source; m_workspace = session.getWorkspace(); - m_changedItems = new ChangeStore(); + m_changedItems = new ChangeStore(true); m_fetchedItems = new SizeLimitedHashMap<PathRef,ItemImpl>(DEFAULT_CACHESIZE); m_uuidMap = new SizeLimitedHashMap<String,NodeImpl>(DEFAULT_CACHESIZE); } /** * Makes sure an item is cleared away from all internal session caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearSingleItem( final ItemImpl ii, final String uuid ) { if( ii != null ) m_fetchedItems.remove( ii.getPathReference() ); if( uuid != null ) m_uuidMap.remove( uuid ); } /** * Visits all Sessions from this particular Repository and clears local caches. * * @param ii Item to remove. May be null. * @param uuid UUID of an item to remove. May be null. */ private void clearAllCaches( final ItemImpl ii, final String uuid ) { m_workspace.getSession().getRepository().visit( new RepositoryImpl.SessionVisitor() { public void visit( SessionImpl session ) { session.m_provider.clearSingleItem( ii, uuid ); } }); } /** * Saves everything starting from root node. * * @throws RepositoryException If something goes wrong. */ public void save() throws RepositoryException { save( Path.ROOT ); } /** * Call when you wish to add a new Node in this Session. * * @param ni Node to add * @throws RepositoryException If the Path cannot be determined. */ public void addNode( NodeImpl ni ) throws RepositoryException { m_changedItems.add( ni.getState(), ni ); } public ItemImpl getItem( Path path ) throws InvalidPathException, RepositoryException { - ItemImpl ii = m_changedItems.get(path); + ItemImpl ii = m_changedItems.getLatestItem(path); if( ii != null ) { return ii; } ii = m_fetchedItems.get( getPathManager().getPathRef( path ) ); if( ii != null ) return ii; ii = m_source.getItem(m_workspace, path); if( ii != null ) m_fetchedItems.put( ii.getPathReference(), ii ); return ii; } public void close() { m_source.close( m_workspace ); } public void copy(Path srcpath, Path destpath) throws RepositoryException { m_source.copy( m_workspace, srcpath, destpath ); } public NodeImpl findByUUID(String uuid) throws RepositoryException { for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); try { // NEW items don't yet have an UUID if( ni.isNode() && ni.getState() != ItemState.NEW ) { String pid = ((NodeImpl)ni).getUUID(); if( uuid.equals(pid) ) return (NodeImpl)ni; } } catch(RepositoryException e) {} } NodeImpl ii = m_uuidMap.get( uuid ); if( ii == null ) { ii = m_source.findByUUID( m_workspace, uuid ); if( ii != null ) { m_fetchedItems.put( ii.getPathReference(), ii ); m_uuidMap.put( uuid, ii ); } } return ii; } /** * Finds all references to the given UUID. * * @param uuid * @return * @throws RepositoryException */ public List<PropertyImpl> getReferences( String uuid ) throws RepositoryException { TreeSet<PropertyImpl> response = new TreeSet<PropertyImpl>(); for (Change c : m_changedItems ) { ItemImpl ii = c.getItem(); if (!ii.isNode()) { PropertyImpl pi = (PropertyImpl) ii; if (pi.getType() == PropertyType.REFERENCE) { Value[] v; if (pi.getDefinition().isMultiple()) { v = pi.getValues(); } else { v = new Value[] { pi.getValue() }; } for (Value vv : v) { if (vv.getString().equals(uuid)) { response.add(pi); break; } } } } } response.addAll( m_source.getReferences(m_workspace,uuid) ); // FIXME: Kludge ArrayList<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( response ); return ls; } public List<Path> listNodes(Path parentpath) throws RepositoryException { List<Path> res = new ArrayList<Path>(); for( Change c : m_changedItems ) { ItemImpl ni = c.getItem(); if( parentpath.isParentOf(ni.getInternalPath()) && ni.isNode() && !res.contains(ni.getInternalPath()) ) { res.add( ni.getInternalPath() ); } } try { List<? extends Path> existingNodes = m_source.listNodes(m_workspace, parentpath); for( Path p : existingNodes ) { if( !res.contains( p ) ) res.add( p ); } } catch( PathNotFoundException e ) { // This is fine, because it could be that the node has not yet // been save()d. } return res; } public Collection<? extends String> listWorkspaces() throws RepositoryException { return m_source.listWorkspaces(); } public boolean nodeExists(Path path) throws RepositoryException { - Change c = m_changedItems.getChange(path); + Change c = m_changedItems.getLatestChange(path); if( c != null && c.getItem().isNode() ) { if( c.getState() == ItemState.REMOVED || c.getState() == ItemState.MOVED ) return false; return true; } return m_source.nodeExists(m_workspace, path); } /* public void open( Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_source.open(credentials, workspaceName); } */ public void remove(ItemImpl item) throws RepositoryException { m_changedItems.add( item.getState(), item ); } public void stop() { m_source.stop(); } public boolean hasPendingChanges() { return !m_changedItems.isEmpty(); } public void clear() { m_changedItems.clear(); } // @SuppressWarnings("fallthrough") public void save(Path path) throws RepositoryException { checkReferentialIntegrity(path); checkMoveConstraint(path); // m_changedItems.dump(); List<Path> toberemoved = new ArrayList<Path>(); ChangeStore unsaved = new ChangeStore(); // // Do the actual save. The way we do this is that we simply just take the // first one from the queue, and and attempt to save it. This allows // e.g. preSave() to create some additional properties before saving - // a basic Iterator over the Set would cause ConcurrentModificationExceptions. // // All unsaved items are stored in a particular list, and then added back // to the savequeue. // StoreTransaction tx = m_source.storeStarted( m_workspace ); boolean succeeded = false; try { Change change; while( (change = m_changedItems.peek()) != null ) { ItemImpl ii = change.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl) ii; checkSanity(change.getState(), change.getPath(), ni); switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case UPDATED: ni.preSave(); // Nodes which exist don't need to be added, but they might need to be reordered. // toberemoved.remove( change.getPath() ); // In case it's there List<Path> childOrder = ni.getChildOrder(); if( childOrder != null ) { System.out.println("Reordering children..."); m_source.reorderNodes( tx, change.getPath(), childOrder ); ni.setChildOrder(null); // Rely again on the repository order. } ni.postSave(); break; case NEW: ni.preSave(); toberemoved.remove( change.getPath() ); // In case it's there m_source.addNode( tx, ni ); ni.postSave(); m_fetchedItems.put( ni.getPathReference(), ni ); break; case REMOVED: if( !m_source.nodeExists( m_workspace, change.getPath() ) ) { throw new InvalidItemStateException("The item has been removed by some other Session "+ii.getInternalPath()); } String uuid = null; try { uuid = ni.getUUID(); } catch( UnsupportedRepositoryOperationException e ) {} // Fine, no uuid toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, uuid ); break; case MOVED: toberemoved.add( change.getPath() ); // m_source.remove(tx, change.getPath()); clearAllCaches( ni, null ); break; case UNDEFINED: throw new IllegalStateException("Node should not at this stage be UNDEFINED "+change.getPath()); } } else { PropertyImpl pi = (PropertyImpl)ii; switch( change.getState() ) { case EXISTS: // These guys shouldn't be here. break; case NEW: case UPDATED: // Do not save transient properties. if( pi.isTransient() ) { break; } pi.preSave(); m_source.putProperty( tx, change.getPath(), change.getValue() ); pi.postSave(); m_fetchedItems.put( pi.getPathReference(), pi ); toberemoved.remove( change.getPath() ); // In case it's there break; case REMOVED: if( !pi.isTransient() ) { toberemoved.add(change.getPath()); // m_source.remove(tx, change.getPath()); } clearAllCaches( pi, null ); break; case MOVED: throw new RepositoryException("Properties should never be marked as MOVED!"); case UNDEFINED: throw new IllegalStateException("A Property should not at this stage be UNDEFINED! "+change.getPath()); } } } else { unsaved.add( change ); } // // Remove from the queue so that we don't use it again. This must // be done here so that there never is an Item missing if any of the // intermediate calls do e.g. hasProperty(); // m_changedItems.remove(); } // // Finally, do the remove. First, sort all in a reverse // depth order (longest first). // Collections.sort( toberemoved, new Comparator<Path>() { public int compare(Path o1, Path o2) { return o2.depth() - o1.depth(); } }); for( Path p : toberemoved ) { log.finest("Removing "+p); m_source.remove(tx, p); // // Some accesses may trigger local cache hits, so we do remove any items at this // stage as well. // m_fetchedItems.remove( m_workspace.getSession().getPathManager().getPathRef(p) ); } // // Put the unsaved ones back into the queue // for( Change c : unsaved ) { m_changedItems.add( c ); } m_source.storeFinished( tx ); succeeded = true; } finally { if(!succeeded) m_source.storeCancelled( tx ); } } private void checkMoveConstraint(Path path) throws RepositoryException, ValueFormatException, PathNotFoundException, NamespaceException, ConstraintViolationException { // // Test MOVE_CONSTRAINT // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(c.getPath()) || path.equals( c.getPath() )) { if( ii.isNode() ) { NodeImpl ni = (NodeImpl)ii; if( ni.hasProperty(SessionImpl.MOVE_CONSTRAINT) ) { String tgtPath = ni.getProperty(SessionImpl.MOVE_CONSTRAINT).getString(); - NodeImpl tgt = (NodeImpl)m_changedItems.get(PathFactory.getPath(m_workspace.getSession(),tgtPath)); + NodeImpl tgt = (NodeImpl)m_changedItems.getLatestItem(PathFactory.getPath(m_workspace.getSession(),tgtPath)); if( tgt != null && path.isParentOf(tgt.getInternalPath()) ) { // Is okay; as it should be. We no longer need this. } else { throw new ConstraintViolationException("When moving, both source and target Nodes must be saved in one go."); } } } } } } private void checkReferentialIntegrity(Path path) throws RepositoryException, ReferentialIntegrityException { // // Test referential integrity. // for( Iterator<Change> i = m_changedItems.iterator(); i.hasNext(); ) { Change c = i.next(); ItemImpl ii = c.getItem(); if( path.isParentOf(ii.getInternalPath()) || path.equals( ii.getInternalPath() )) { if( ii.isNode() && ii.getState() == ItemState.REMOVED ) { try { Collection<PropertyImpl> refs = getReferences( ((NodeImpl)ii).getUUID() ); for( PropertyImpl pi : refs ) { if( pi.getState() != ItemState.REMOVED ) { throw new ReferentialIntegrityException("Attempted to remove a Node which still has references: "+ ii.getPath()+ " (the Property holding the reference is "+ pi.getPath()+ ")"); } } } catch( UnsupportedRepositoryOperationException e ) { // Does not have an UUID, so cannot be referenced. } } } } } /** * State checks the sanity of a Node before saving. * * @param state * @param ni * @throws RepositoryException */ private void checkSanity(ItemState state, Path path, NodeImpl ni) throws RepositoryException { WorkspaceImpl ws = ni.getSession().getWorkspace(); SessionImpl session = ni.getSession(); if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) ni.autoCreateProperties(); // // Check that parent still exists // if( !ni.getInternalPath().isRoot() ) { if( !ws.nodeExists(ni.getInternalPath().getParentPath()) ) { throw new InvalidItemStateException("No parent available."); } } // // Check if nobody has removed us if we were still supposed to exist. // if( state != ItemState.NEW && state != ItemState.REMOVED && state != ItemState.MOVED ) { if( !ws.nodeExists(path) ) { throw new InvalidItemStateException("Looks like this Node has been removed by another session: "+ni.getInternalPath().toString(session)); } try { String uuid = ni.getUUID(); NodeImpl currentNode = session.getNodeByUUID( uuid ); if( !currentNode.getInternalPath().equals(ni.getInternalPath()) ) throw new InvalidItemStateException("Page has been moved"); } catch( UnsupportedRepositoryOperationException e ){} // Not referenceable, so it's okay } // // Check mandatory properties // if( state != ItemState.REMOVED && state != ItemState.MOVED && ni.getState() != ItemState.REMOVED ) { // // If this node is versionable, then make sure there is a VersionHistory as well. // if( ni.hasMixinType("mix:versionable") ) { VersionManager.createVersionHistory( ni ); } ni.checkMandatoryProperties( ni.getPrimaryQNodeType() ); for( NodeType nt : ni.getMixinNodeTypes() ) { ni.checkMandatoryProperties( ((QNodeType.Impl)nt).getQNodeType() ); } } } public Collection<? extends PropertyImpl> getProperties(Path path) throws RepositoryException { HashMap<QName,PropertyImpl> result = new HashMap<QName,PropertyImpl>(); // // Find the node first // NodeImpl ni = null; try { ni = (NodeImpl) m_source.getItem( m_workspace, path ); List<QName> propertyNames = m_source.listProperties( m_workspace, path ); for( QName pName : propertyNames ) { result.put( pName, (PropertyImpl)m_source.getItem( m_workspace, path.resolve(pName) ) ); } } catch( RepositoryException e ) { - ItemImpl ii = m_changedItems.get( path ); + ItemImpl ii = m_changedItems.getLatestItem( path ); if( ii != null && ii.isNode() ) ni = (NodeImpl)ii; } if( ni == null ) { throw new ItemNotFoundException("There is no such Node: "+path); } // // Now, we need to collate the properties from the Node which was // found with the properties which have been changed. We put them all in the // same hashmap and rely on the fact that there can't be two items with // the same key. // for( Iterator<ItemImpl> i = m_changedItems.values(); i.hasNext(); ) { ItemImpl ii = i.next(); if( ii.isNode() == false && ii.getInternalPath().getParentPath().equals(path) ) { result.put( ii.getInternalPath().getLastComponent(), (PropertyImpl) ii ); } } return result.values(); } public void putProperty(NodeImpl impl, PropertyImpl property) throws RepositoryException { // addNode( impl ); m_changedItems.add( property.getState(), property ); } /** * Refreshes all the items within the given path. * * @param keepChanges If true, does nothing (Priha implements COPY-ON-WRITE). If false, * purges all changes from the path. * @param path The path from which to start refreshing. */ public void refresh(boolean keepChanges, Path path) { // // FIXME: Should notify the providers to refresh the caches, if caching // is implemented. // if( keepChanges ) return; if( path.isRoot() ) { m_changedItems.clear(); // Shortcut return; } for( Iterator<Change> c = m_changedItems.iterator(); c.hasNext(); ) { Change change = c.next(); if( path.isParentOf(change.getItem().getInternalPath()) ) { c.remove(); } } } /** * Goes directly into the repository, to find whether a Node exists currently. * It ignores the transient state; so any new node additions or removals are * ignored. * * @param path The path to check * @return True, if the backend holds a given Node. * @throws RepositoryException If something goes wrong. */ public boolean nodeExistsInRepository( Path path ) throws RepositoryException { return m_source.nodeExists( m_workspace, path ); } /** * Provides a HashMap which has a maximum size. If the HashMap * becomes full, it will start expelling the oldest entries. It can * be used to create a cache which does not grow bigger than limited. * * @param <K> Type of the key. * @param <V> Type of the value. */ private class SizeLimitedHashMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 1L; private static final int MAX_SIZE = 100; private int m_maxSize = MAX_SIZE; /** * Creates a SizeLimitedHashMap for a certain size. * * @param maxSize Maximum size. */ public SizeLimitedHashMap(int maxSize) { super(); m_maxSize = maxSize; } /** * Creates a SizeLimitedHashMap with the default size {@value SizeLimitedHashMap#MAX_SIZE}. */ public SizeLimitedHashMap() { super(); } /** * Returns true, making the underlying implementation remove the eldest item, * when the hashmap has grown bigger than the specified maximum size. */ @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > m_maxSize; } } public Path getPath( PathRef p ) throws PathNotFoundException { return c_sessionPathManager.getPath( p ); } public PathManager getPathManager() { return c_sessionPathManager; } public ItemState getState( PathRef m_path ) throws PathNotFoundException { - Change c = m_changedItems.getChange( getPath(m_path) ); + Change c = m_changedItems.getLatestChange( getPath(m_path) ); return c != null ? c.getState() : null; } } diff --git a/src/java/org/priha/util/ChangeStore.java b/src/java/org/priha/util/ChangeStore.java index 8b83f15..2d2baa7 100644 --- a/src/java/org/priha/util/ChangeStore.java +++ b/src/java/org/priha/util/ChangeStore.java @@ -1,229 +1,337 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; +import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; -import java.util.LinkedList; import java.util.ListIterator; import org.priha.core.ItemImpl; import org.priha.core.ItemState; import org.priha.core.PropertyImpl; import org.priha.path.Path; import org.priha.providers.ValueContainer; -// FIXME: This could be a lot faster when doing get()s for example. - +/** + * Provides a list of changes, which can be both played back + * one by one, as well as searched rapidly. + * <p> + * Internally, this class stores both a List of Change objects, + * as well as a HashMap pointing at the latest change. It can be + * iterated both forwards (using peek() and remove() and iterator()) as well + * as backwards (using values()). + */ public class ChangeStore implements Iterable<ChangeStore.Change> { - private LinkedList<Change> m_changes = new LinkedList<Change>(); + private ArrayList<Change> m_changes = new ArrayList<Change>(); + private boolean m_useHashMap; + private HashMap<Path,Change> m_latest = new HashMap<Path,Change>(); - public ItemImpl get( Path path ) + /** + * Create a ChangeStore. + * + * @param useHashMap If true, uses a HashMap to speed things up internally. + */ + public ChangeStore(boolean useHashMap) { - Change c = getChange( path ); + m_useHashMap = useHashMap; + } + + /** + * Create a ChangeStore without the HashMap. + */ + public ChangeStore() + {} + + /** + * Returns the newest ItemImpl that corresponds to the Path given. + * + * @param path Path to search for + * @return Newest Item or null, if no such thing is found. + */ + public ItemImpl getLatestItem( Path path ) + { + Change c = getLatestChange( path ); if( c != null ) return c.getItem(); return null; } /** * Finds the latest change. * - * @param path - * @return + * @param path Path to search for + * @return The Change or null, if no such thing found. */ - public Change getChange( Path path ) + public Change getLatestChange( Path path ) { + if( m_useHashMap ) + { + Change c = m_latest.get( path ); + return c; + } + for( ListIterator<Change> i = m_changes.listIterator(m_changes.size()); i.hasPrevious(); ) { Change c = i.previous(); if( c.getPath().equals(path) ) return c; } return null; } + /** + * Adds a new Item with given ItemState to the end of the Change List. + * + * @param newState New state + * @param ii The Item + */ public void add( ItemState newState, ItemImpl ii ) { Change c = new Change( newState, ii ); add( c ); } + /** + * Adds a whole Change object at the end of the Change List. + * + * @param c The Change to add + * @return True, at the moment. + */ public boolean add( Change c ) - { -// Change prev = getChange( c.getPath() ); - -// if( prev != null ) System.out.println("Adding to old: "+prev.getState()+", "+c.getState()); -// if( prev != null ) -// { -// if( prev.getState().equals(c.getState()) || (prev.getState().equals(ItemState.REMOVED) && c.getState().equals(ItemState.EXISTS) ) ) -// { -// // We are repeating what already happened. This happens because of setModified(), -// // so we're ignoring it here. -// return false; -// } -// } - + { if( c.getState() == ItemState.UNDEFINED ) { dump(); throw new IllegalStateException("You cannot add an UNDEFINED Item "+c.getItem().getInternalPath()); } m_changes.add(c); + if( m_useHashMap ) + m_latest.put( c.getPath(), c ); + return true; } /** * Gets the first change from the change list. Returns null, if there are no more * changes. * - * @return + * @return The first change from the list, or null, if the list was empty. */ public Change peek() { - return m_changes.peek(); + if( m_changes.size() > 0 ) + return m_changes.get(0); + + return null; } /** * Removes the first change from the change list. - * @return + * + * @return The first change from the list, or null, if the list was empty. */ public Change remove() { - return m_changes.poll(); + Change c = null; + if( m_changes.size() > 0 ) + { + c = m_changes.remove(0); + if( m_useHashMap ) + { + m_latest.remove( c.getPath() ); + } + } + return c; } /** * Clears the changes. * * @return The number of changes removed from the queue. */ public int clear() { int numChanges = m_changes.size(); m_changes.clear(); - + m_latest.clear(); return numChanges; } + /** + * Returns a forward iterator for the Changes. + * + * @return A forward iterator for the Changes. + */ public Iterator<Change> iterator() { return m_changes.iterator(); } + /** + * Returns a <b>backward</b> iterator for the Items in the change list. The first + * value you get is the newest value on the stack. This means + * that the iteration order for iterator() and values() is reversed. + * + * @return A reverse iterator for the values. + */ public Iterator<ItemImpl> values() { return new ItemIterator(); } + /** + * Returns true, if there are no changes. + * + * @return True, if there are no changes. + */ public boolean isEmpty() { return m_changes.isEmpty(); } + /** + * Implements a backwards iterator through the Items in the list. + */ private class ItemIterator implements Iterator<ItemImpl> { int m_position; protected ItemIterator() { m_position = m_changes.size()-1; } public boolean hasNext() { return m_position > 0; } public ItemImpl next() { return m_changes.get(m_position--).getItem(); } public void remove() { throw new UnsupportedOperationException(); } } + /** + * Dumps the store contents for debugging to System.out. + */ public void dump() { System.out.println("DUMP OF CHANGESTORE @"+Integer.toHexString(this.hashCode())); System.out.println(this); } + /** + * Outputs a human-readable description of the contents of the ChangeStore. + * + * @return Somethign human-readable. + */ public String toString() { StringBuilder sb = new StringBuilder(); for( Change c : this ) { sb.append( c.getState().toString() + ": " + c.getPath() + ": " + c.getItem() + "\n" ); } return sb.toString(); } /** * Stores a single change. */ public static class Change { private ItemState m_state; private ItemImpl m_item; private Path m_path; private ValueContainer m_valueContainer; + /** + * Create a new Change for the given ItemState and item. If the + * Item is a property, also the Value is copied internally. + * + * @param newState The new state + * @param item The item + */ public Change( ItemState newState, ItemImpl item ) { m_state = newState; m_item = item; m_path = item.getInternalPath(); if( !item.isNode() ) { m_valueContainer = ((PropertyImpl)item).getValueContainer(); if( m_valueContainer.isEmpty() ) throw new IllegalArgumentException("Null value in valuecontainer for "+m_path); } } + /** + * Returns the Item for this Change. + * + * @return The Item. + */ public ItemImpl getItem() { return m_item; } + /** + * Returns the ItemState for this Change. + * + * @return The ItemState. + */ public ItemState getState() { return m_state; } + /** + * Returns the Path for this Change. + * + * @return The Path. + */ public Path getPath() { return m_path; } + /** + * Return the ValueContainer for the Change. + * + * @return The ValueContainer, or null, if the Change concerned a Node. + */ public ValueContainer getValue() { return m_valueContainer; } } } diff --git a/tests/java/org/priha/core/PerformanceTest.java b/tests/java/org/priha/core/PerformanceTest.java index 6463db2..446b8e4 100644 --- a/tests/java/org/priha/core/PerformanceTest.java +++ b/tests/java/org/priha/core/PerformanceTest.java @@ -1,718 +1,723 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.ByteArrayInputStream; import java.util.*; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.Release; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.core.RepositoryImpl; public class PerformanceTest extends TestCase { /** The size of a million can be configured here. ;-) */ - private static final int DEFAULT_ITERATIONS = 100; + private static final int DEFAULT_ITERATIONS = 200; private int m_iterations = DEFAULT_ITERATIONS; private static final int BLOB_SIZE = 1024*100; private int m_blobsize = BLOB_SIZE; private static final int NODENAMELEN = 16; private static final int PROPERTYLEN = 16; private Credentials m_creds = new SimpleCredentials("username","password".toCharArray()); private boolean m_memoryProviderTest = true; private boolean m_jackrabbitTest = true; private boolean m_jdbcProviderTest = true; private boolean m_jdbcProviderEhTest = true; private boolean m_fileProviderTest = true; private boolean m_fileProviderEhTest = true; private boolean m_largeTests = true; public void setUp() { String iters = System.getProperty("perftest.iterations"); if( iters != null ) m_iterations = Integer.parseInt(iters); String blobsize = System.getProperty("perftest.blobsize"); if( blobsize != null ) m_blobsize = Integer.parseInt(blobsize)*1024; } public void testMemoryProvider() throws Exception { if( !m_memoryProviderTest ) return; - Perf.setProvider("MemoryProvider, no cache"); + Perf.setTestable("MemoryProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("memorynocache.properties"); millionIterationsTest( rep, m_creds , m_iterations ); } public void testFileProvider() throws Exception { if( !m_fileProviderTest ) return; - Perf.setProvider("FileProvider, no cache"); + Perf.setTestable("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("filenocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testFileEhcacheProvider() throws Exception { if( !m_fileProviderEhTest ) return; - Perf.setProvider("FileProvider, with Ehcache"); + Perf.setTestable("FileProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("fileehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcProvider() throws Exception { if( !m_jdbcProviderTest ) return; - Perf.setProvider("JdbcProvider, no cache"); + Perf.setTestable("JdbcProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcEhcacheProvider() throws Exception { if( !m_jdbcProviderEhTest ) return; - Perf.setProvider("JdbcProvider, with Ehcache"); + Perf.setTestable("JdbcProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public static Repository getJackrabbitRepository() { try { Class<?> cc = Class.forName("org.apache.jackrabbit.core.TransientRepository"); return (Repository) cc.newInstance(); } catch( Exception e ) { return null; } } public void testJackrabbit() throws Exception { if( !m_jackrabbitTest ) return; - Perf.setProvider("Jackrabbit"); + Perf.setTestable("Jackrabbit"); Repository rep = getJackrabbitRepository(); if( rep != null ) { millionIterationsTest(rep, m_creds, m_iterations); } else { System.out.println("Skipping Jackrabbit comparison tests; classes not found in classpath"); } } /** Just a dummy test which is executed last and it will print out the * test result. */ public void testPrint() { Perf.print(this); } public static class TesterClass { private Repository m_repository; private Credentials m_creds; private int m_numNodes; private int m_readIters; private byte[] m_blob; ArrayList<String> propertyPaths = new ArrayList<String>(); ArrayList<String> uuids = new ArrayList<String>(); private boolean m_testNewSession = true; private boolean m_testSeqRead = true; private boolean m_testRandRead = true; private boolean m_testUUIDRead = true; private boolean m_testLargeRead = true; private boolean m_testCachedNode = true; private boolean m_testUpdate = true; public TesterClass(Repository rep, Credentials creds, int numIters, byte[] blob) { m_repository = rep; m_creds = creds; m_numNodes = numIters; m_readIters = numIters * 10; m_blob = blob; } public void testNewSession() throws LoginException, RepositoryException { if( !m_testNewSession ) return; // We want to make sure that we don't get the penalty of the first // session here. Session prime = m_repository.login(m_creds); try { // // Test how quickly subsequent sessions can be acquired. // Perf.start("NewSession"); for( int i = 0; i < m_numNodes; i++ ) { Session s2 = m_repository.login(m_creds); s2.logout(); } Perf.stop(m_numNodes); } finally { prime.logout(); } } public void testSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("Save"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID(NODENAMELEN); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); n.addMixin("mix:referenceable"); Property p = n.setProperty( "test", TestUtil.getUniqueID(PROPERTYLEN) ); propertyPaths.add( p.getPath() ); nd.save(); uuids.add( n.getProperty("jcr:uuid").getString() ); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testLargeSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("LargeSave"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID( NODENAMELEN ); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); Property p = n.setProperty( "test", new ByteArrayInputStream(m_blob) ); propertyPaths.add( p.getPath() ); nd.save(); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testSeqRead() throws LoginException, RepositoryException { if( !m_testSeqRead ) return; Session s = m_repository.login(m_creds); try { // // Test how quickly we can read all the properties // of a single node using getNodes(). // Perf.start("SeqRead"); Node nd = s.getRootNode(); for( NodeIterator i = nd.getNodes(); i.hasNext(); ) { Node n = i.nextNode(); // Skip nodes which weren't created in this test. if( n.getName().startsWith("x-") ) { for( NodeIterator i2 = n.getNodes(); i2.hasNext(); ) { Node n2 = i2.nextNode(); Property p = n2.getProperty("test"); assertEquals( p.getName(), PROPERTYLEN, p.getString().length() ); } } } Perf.stop(m_numNodes); } finally { s.logout(); } } public void testRandRead() throws LoginException, RepositoryException { if( !m_testRandRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("RandRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), PROPERTYLEN, ((Property)ii).getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testUUIDRead() throws LoginException, RepositoryException { if( !m_testUUIDRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("UUID"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( uuids.size() ); Node ni = s.getNodeByUUID( uuids.get(item) ); assertEquals( ni.getName(), PROPERTYLEN, ni.getProperty("test").getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testLargeRead() throws LoginException, RepositoryException { if( !m_testLargeRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("LargeRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), m_blob.length, ((Property)ii).getLength()); } Perf.stop(m_readIters); } finally { s.logout(); } } /** * Produces two figures: getProperty and getItem. The same item * is fetched through both methods, and the performance is measured. */ public void testCachedNode() throws RepositoryException { if( !m_testCachedNode ) return; Session s = m_repository.login(m_creds); try { String ss = propertyPaths.get( 0 ); Item ii = s.getItem(ss); Node nd = ii.getParent(); String propName = ii.getName(); // // First, access directly with getProperty() // Perf.start("getProperty"); for( int i = 0; i < m_readIters; i++ ) { Property prop = nd.getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // // Then, with getItem() // Perf.start("getItem"); for( int i = 0; i < m_readIters; i++ ) { Property prop = (Property) s.getItem( ss ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // Finally, with getByUUID() String uuid = uuids.get(0); Perf.start("propUUID"); for( int i = 0; i < m_readIters; i++ ) { Property prop = s.getNodeByUUID( uuid ).getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testUpdate() throws RepositoryException { if( !m_testUpdate ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and updated // Perf.start("Update"); for( int i = 0; i < m_numNodes; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Property ii = (Property)s.getItem( propertyPaths.get(item) ); ii.setValue( "modified result" ); s.save(); } Perf.stop(m_numNodes); } finally { s.logout(); } } } public void millionIterationsTest( Repository rep, Credentials creds, int numIters ) throws Exception { TesterClass tc = new TesterClass( rep, creds, numIters, getBlob() ); try { // // Test how quickly the first session can be opened. // Perf.start("FirstSess"); Session s = rep.login(creds); Perf.stop(1); s.logout(); TestUtil.emptyRepo(rep); tc.testNewSession(); tc.testSave(); tc.testSeqRead(); tc.testRandRead(); tc.testUUIDRead(); tc.testUpdate(); tc.testCachedNode(); // // Test how quickly we can then empty the repository. // Perf.start("Remove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); if( m_largeTests ) { // // Large objects // getBlob(); tc.testLargeSave(); tc.testLargeRead(); Perf.start("LargeRemove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); } } catch( Exception t ) { t.printStackTrace(); throw t; } finally { TestUtil.emptyRepo(rep); } } private static byte[] blob; private final byte[] getBlob() { if( blob == null) { blob = new byte[m_blobsize]; // 1 Meg for( int i = 0; i < m_blobsize; i++ ) blob[i] = (byte) (i % 255); } return blob; } public static Test suite() { return new TestSuite( PerformanceTest.class ); } /** * This class stores all results to a local hashmap, which can then be pretty-printed. * */ public static class Perf { private static HashMap<String, HashMap<String, Double>> results = new LinkedHashMap<String,HashMap<String,Double>>(); private static long startTime; private static String currTest; - private static String currProvider; + private static String currTestable; - public static void setProvider(String p) + public static void setTestable(String p) { - currProvider = p; + currTestable = p; } public static void start( String test ) { currTest = test; startTime = System.nanoTime(); } public static void stop( int iters ) { long stop = System.nanoTime(); long time = stop-startTime; double itersSec = iters/(time/1e9); HashMap<String,Double> hm; - hm = results.get(currProvider); + hm = results.get(currTestable); if( hm == null ) { hm = new HashMap<String,Double>(); - results.put(currProvider, hm); + results.put(currTestable, hm); } hm.put(currTest, itersSec); //TestUtil.printSpeed(currProvider+": "+currTest, iters, startTime, stop); } public static void print(PerformanceTest test) { System.out.println("Test results. The number is operations/seconds - larger means faster."); System.out.println("Blob size "+test.m_blobsize/1024+" kB"); System.out.println("Repository size "+test.m_iterations+" nodes"); System.out.println("Priha version "+Release.VERSTR); Repository jr = getJackrabbitRepository(); if( jr != null ) System.out.println("Jackrabbit version "+jr.getDescriptor( Repository.REP_VERSION_DESC )); - + + print(); + } + + public static void print() + { ArrayList<String> keys = new ArrayList<String>(); keys.addAll( results.values().iterator().next().keySet() ); Collections.sort(keys); System.out.printf("%-30s",""); for( String key : keys ) { System.out.printf("%12s",key); } System.out.print("\n"); for( Map.Entry<String,HashMap<String,Double>> e : results.entrySet() ) { System.out.printf( "%-30s", e.getKey() ); for( String key : keys ) { Double val = e.getValue().get(key); if( val != null && val < 1 ) System.out.printf("%12.2f",val); else System.out.printf("%12.0f", val != null ? val : Double.NaN ); } System.out.print("\n"); } } } } diff --git a/tests/java/org/priha/util/AllTests.java b/tests/java/org/priha/util/AllTests.java index 711524b..93cd491 100644 --- a/tests/java/org/priha/util/AllTests.java +++ b/tests/java/org/priha/util/AllTests.java @@ -1,34 +1,35 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Util tests"); suite.addTest( PathTest.suite() ); suite.addTest( PathUtilTest.suite() ); suite.addTest( FastPropertyStoreTest.suite() ); + suite.addTest( ChangeStoreTest.suite() ); return suite; } } diff --git a/tests/java/org/priha/util/ChangeStoreTest.java b/tests/java/org/priha/util/ChangeStoreTest.java new file mode 100644 index 0000000..6c56990 --- /dev/null +++ b/tests/java/org/priha/util/ChangeStoreTest.java @@ -0,0 +1,167 @@ +package org.priha.util; + +import javax.jcr.*; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.version.VersionException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.priha.AbstractTest; +import org.priha.core.ItemImpl; +import org.priha.core.ItemState; +import org.priha.core.SessionImpl; +import org.priha.core.PerformanceTest.Perf; +import org.priha.path.Path; +import org.priha.util.ChangeStore.Change; + +public class ChangeStoreTest extends AbstractTest +{ + ChangeStore m_store = new ChangeStore(); + SessionImpl m_session; + + public void setUp() throws Exception + { + super.setUp(); + m_session = m_repository.login(); + } + + public void tearDown() throws Exception + { + m_session.logout(); + super.tearDown(); + } + + public void testGet() throws Exception + { + Path p = new Path( m_session, "/foo/bar/gobble" ); + ItemImpl ii1 = new DummyItem(m_session,p); + + m_store.add( new Change(ItemState.NEW,ii1) ); + m_store.add( new Change(ItemState.REMOVED,ii1) ); + + assertEquals( ItemState.REMOVED, m_store.getLatestChange( p ).getState() ); + } + + private void speedTest(ChangeStore cs) throws Exception + { + int numItems = 1000; + // + // Add one thousand items. + // + for( int i = 0; i < numItems; i++ ) + { + Path p = new Path( m_session, "/foo/bar/gobble"+i ); + ItemImpl ii = new DummyItem(m_session,p); + + cs.add( new Change(ItemState.NEW,ii) ); + } + + Perf.start( "readhead" ); + int iters = 10000; + + Path p = new Path(m_session, "/foo/bar/gobble"+0 ); + for( int i = 0; i < iters; i++ ) + { + ItemImpl ii = cs.getLatestItem( p ); + assertNotNull(ii); + } + + Perf.stop( iters ); + + Perf.start( "readmid" ); + + p = new Path(m_session, "/foo/bar/gobble"+numItems/2 ); + for( int i = 0; i < iters; i++ ) + { + ItemImpl ii = cs.getLatestItem( p ); + assertNotNull(ii); + } + + Perf.stop( iters ); + + Perf.start( "readtail" ); + + p = new Path(m_session, "/foo/bar/gobble"+(numItems-1) ); + for( int i = 0; i < iters; i++ ) + { + ItemImpl ii = cs.getLatestItem( p ); + assertNotNull(ii); + } + + Perf.stop( iters ); + + Perf.start( "readmiss" ); + + p = new Path(m_session, "/foo/bar/gobblexyzzy" ); + for( int i = 0; i < iters; i++ ) + { + ItemImpl ii = cs.getLatestItem( p ); + assertNull(ii); + } + + Perf.stop( iters ); + + Perf.start( "remove" ); + + for( int i = 0; i < numItems; i++ ) + { + Change c = cs.remove(); + assertNotNull(c); + } + + Perf.stop( numItems ); + + } + + public void testGetSpeed() throws Exception + { + Perf.setTestable( "noHashMap" ); + speedTest( new ChangeStore(false) ); + + Perf.setTestable( "HashMap" ); + speedTest( new ChangeStore(true) ); + + Perf.print(); + } + + public static Test suite() + { + return new TestSuite( ChangeStoreTest.class ); + } + + private class DummyItem extends ItemImpl + { + + public DummyItem( SessionImpl s, Path path ) + { + super( s, path ); + } + + @Override + public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException + { + } + + @Override + public void save() + throws AccessDeniedException, + ItemExistsException, + ConstraintViolationException, + InvalidItemStateException, + ReferentialIntegrityException, + VersionException, + LockException, + NoSuchNodeTypeException, + RepositoryException + { + } + + public boolean isNode() + { + return true; + } + } +}
jalkanen/Priha
ff25d4fb1ec28a7f5149146ff3d0cf6e7e1bc04e
Improved UUID cache speed when the Node did not have an UUID.
diff --git a/ChangeLog b/ChangeLog index d5337db..65b31c5 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,519 +1,521 @@ 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.5 * Fixed an off-by-one problem with SNS reordering; all internal unit tests run now too! + * Speeded up NodeImpl.getUUID() in case the UUID didn't exist. + * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 12c473d..fd1b95a 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,1564 +1,1563 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; import org.priha.core.locks.LockManager; import org.priha.core.locks.QLock; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.util.LazyNodeIteratorImpl; import org.priha.util.PropertyIteratorImpl; import org.priha.util.QName; import org.priha.util.TextUtil; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; /** * Implements a Node. This is one of the most heavy classes in Priha, with a lot * of stuff happening. The NodeImpl class does some basic caching for some state * objects, so keeping references can be faster in some cases. */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; /** * A compile-time flag for allowing/disallowing Same Name Sibling support. * addNode() will throw an exception if you disallow these. This is sometimes * useful for debugging. */ private static final boolean ALLOW_SNS = true; private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; + private static final String NO_UUID = ""; // If there is no UUID for this Node. + static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { enterState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.enterState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.enterState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public PropertyIteratorImpl getProperties() throws RepositoryException { List<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( m_session.m_provider.getProperties(getInternalPath()) ); return new PropertyIteratorImpl( ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); - pi.loadValue( vfi.createValue( uuid.toString() ) ); + m_cachedUUID = uuid.toString(); + + pi.loadValue( vfi.createValue( m_cachedUUID ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.enterState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } /** * Returns the UUID for this node. Utilizes an internal cache for the UUID, * so is fast after the first call. */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { + if( NO_UUID.equals(m_cachedUUID) && !hasProperty(JCR_UUID) ) + throw new UnsupportedRepositoryOperationException(); + if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { - // Fine, let's just fall through, and end up throwing an exception + // OK, so let's fallthrough to the exception throwing part. } } + m_cachedUUID = NO_UUID; + throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } /** * Returns true, if this Node has a child with the given QName. * * @param name A QName. * @return True, if there is a child by this name. * @throws RepositoryException */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { m_lockManager.removeLock( lock ); } // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { if( srcChildRelPath.indexOf('[') != -1 || hasNode(srcChildRelPath+"[2]" ) ) { // Yes, we are moving a SNS so this needs reordering. Path tmpPath = getInternalPath().resolve( m_session, "priha:tmpmove" ); // First, store the old version m_session.internalMove( srcPath, tmpPath, false ); String childName = srcChildRelPath.replaceAll( "\\[\\d+\\]", "" ); // FIXME: Hackish trick. boolean last = false; if( dstPath == null ) { NodeIterator ni = getNodes(childName); dstPath = getInternalPath().resolve( m_session, childName+"["+ni.getSize()+"]" ); last = true; } int dir; int startIdx; int endIdx; if( srcPath.getLastComponent().getIndex() < dstPath.getLastComponent().getIndex() ) { // When moving forward, the dstPath is not actually the correct index; // we want to place it _before_ the given index. if( !last ) { int idx = dstPath.getLastComponent().getIndex() - 1; // Real last one dstPath = dstPath.getParentPath().resolve( new Path.Component(dstPath.getLastComponent().getQName(),idx) ); } // Moving stuff forwards dir = -1; startIdx = srcPath.getLastComponent().getIndex()+1; endIdx = dstPath.getLastComponent().getIndex()+1; } else { dir = 1; startIdx = srcPath.getLastComponent().getIndex()-1; endIdx = dstPath.getLastComponent().getIndex()-1; } for( int i = startIdx; i != endIdx; i -= dir ) { String oldName = childName + "[" + i + "]"; String newName = childName + "[" + (i + dir) + "]"; System.out.println("Reordering SNS : "+oldName+" to "+newName); Path path1 = getInternalPath().resolve(m_session,oldName); Path newPath = getInternalPath().resolve(m_session,newName); m_session.internalMove( path1, newPath, false ); } m_session.internalMove( tmpPath, dstPath, false ); } else { // // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. // Path p = newOrder.remove(srcIndex); if( dstIndex != -1 ) newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); else newOrder.add(p); } } finally { m_session.setSuper(isSuper); } // // Lock back up // if( lock != null ) { m_lockManager.moveLock( lock, dstPath ); } // // Finish. // enterState( ItemState.UPDATED ); m_childOrder = newOrder; } private PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ private PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); -// prop.m_state = ItemState.NEW; -// addChildProperty( prop ); // Again, a special case. First add the property to the lists. return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; -// prop.setState( ItemState.NEW ); } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } - else - { -// prop.setState( ItemState.UPDATED ); - } if( value == null ) { removeProperty(prop); } - else - { - //addChildProperty( prop ); - } + return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); } // FIXME: No rollback support public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { if( getState() == ItemState.NEW ) throw new InvalidItemStateException("Cannot call save on newly added node "+getInternalPath()); internalSave(); } public int compareTo(Node nd) { try { return getPath().compareTo(nd.getPath()); } catch( RepositoryException e ) { return 0; } // FIXME: This should never occur } public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException { remove(false); } /** * If isRemoving = true, will remove subnodes without question. */ private void remove(boolean isRemoving) throws VersionException, LockException, ConstraintViolationException, RepositoryException { if( getState() == ItemState.REMOVED ) { // System.out.println(getPath()+" has already been removed"); return; // Die nicely } Path path = getInternalPath(); if( !m_session.m_provider.nodeExistsInRepository( path ) && m_session.m_provider.m_changedItems.get(path) == null ) { m_session.m_provider.m_changedItems.dump(); throw new InvalidItemStateException("Item has already been removed by another Session "+getPath()); } if( path.isRoot() || path.equals( JCRConstants.Q_JCR_SYSTEM_PATH ) ) { return; // Refuse to remove } NodeImpl parent = getParent(); NodeType parentType = parent.getPrimaryNodeType(); if( !getSession().isSuper() ) { // Anything from under /jcr:system cannot be deleted by the user if( JCRConstants.Q_JCR_SYSTEM_PATH.isParentOf( path )) return; if( getParent().isLockedWithoutToken() ) throw new LockException("The parent is locked, so you cannot remove it."); if( !parentType.canRemoveItem(getName()) && getParent().getState() != ItemState.REMOVED && !isRemoving ) { throw new ConstraintViolationException("Attempted to delete a mandatory child node:"+getInternalPath()); } } QLock li = m_lockManager.getLock( path ); if( li != null ) m_lockManager.removeLock( li ); // // Remove version history // if( isNodeType( "mix:versionable" ) ) { // // Version histories cannot be removed unless you have a // superuser session. // boolean isSuper = m_session.setSuper(true); try { getVersionHistory().remove(); } catch( UnsupportedRepositoryOperationException e ) { // This may happen if you've just created a Node, then hit remove() on it immediately, since // in that case, we do not have an UUID yet. } finally { m_session.setSuper( isSuper ); } } // // Removal happens in a depth-first manner. // // // Remove children. We do this in a reverse order in order // not to force annoying moves for same-name siblings. It's just faster. // LazyNodeIteratorImpl ndi = (LazyNodeIteratorImpl) getNodes(); ndi.skip( ndi.getSize() ); while( ndi.hasPrevious() ) { NodeImpl nd = ndi.previousNode(); // System.out.println("REMOVING "+nd.getPath()); nd.remove(true); }
jalkanen/Priha
2cc9fb8fbdcc057825b97ece003b3c50cd7e0c73
Fixed off-by-one error in internal SNS reordering.
diff --git a/ChangeLog b/ChangeLog index b32f53e..d5337db 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,514 +1,519 @@ 2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> + * 0.6.5 + + * Fixed an off-by-one problem with SNS reordering; all internal + unit tests run now too! + * 0.6.4 * Fixed some more issues with SNS reordering. This version now passes the JSR-170 TCK with zero errors or failures. * Merry Christmas! 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 41b4ea5..12c473d 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -332,1067 +332,1071 @@ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public PropertyIteratorImpl getProperties() throws RepositoryException { List<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( m_session.m_provider.getProperties(getInternalPath()) ); return new PropertyIteratorImpl( ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); pi.loadValue( vfi.createValue( uuid.toString() ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.enterState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } /** * Returns the UUID for this node. Utilizes an internal cache for the UUID, * so is fast after the first call. */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { // Fine, let's just fall through, and end up throwing an exception } } throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } /** * Returns true, if this Node has a child with the given QName. * * @param name A QName. * @return True, if there is a child by this name. * @throws RepositoryException */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { m_lockManager.removeLock( lock ); } // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { if( srcChildRelPath.indexOf('[') != -1 || hasNode(srcChildRelPath+"[2]" ) ) { // Yes, we are moving a SNS so this needs reordering. Path tmpPath = getInternalPath().resolve( m_session, "priha:tmpmove" ); // First, store the old version m_session.internalMove( srcPath, tmpPath, false ); String childName = srcChildRelPath.replaceAll( "\\[\\d+\\]", "" ); + // FIXME: Hackish trick. + boolean last = false; + if( dstPath == null ) { NodeIterator ni = getNodes(childName); dstPath = getInternalPath().resolve( m_session, childName+"["+ni.getSize()+"]" ); + last = true; } - + int dir; int startIdx; int endIdx; if( srcPath.getLastComponent().getIndex() < dstPath.getLastComponent().getIndex() ) { + // When moving forward, the dstPath is not actually the correct index; + // we want to place it _before_ the given index. + if( !last ) + { + int idx = dstPath.getLastComponent().getIndex() - 1; // Real last one + dstPath = dstPath.getParentPath().resolve( new Path.Component(dstPath.getLastComponent().getQName(),idx) ); + } + // Moving stuff forwards dir = -1; startIdx = srcPath.getLastComponent().getIndex()+1; endIdx = dstPath.getLastComponent().getIndex()+1; } else { dir = 1; startIdx = srcPath.getLastComponent().getIndex()-1; endIdx = dstPath.getLastComponent().getIndex()-1; } for( int i = startIdx; i != endIdx; i -= dir ) { String oldName = childName + "[" + i + "]"; String newName = childName + "[" + (i + dir) + "]"; System.out.println("Reordering SNS : "+oldName+" to "+newName); Path path1 = getInternalPath().resolve(m_session,oldName); -// Path tmppath = getInternalPath().resolve(m_session,"priha:tmpmove"); Path newPath = getInternalPath().resolve(m_session,newName); m_session.internalMove( path1, newPath, false ); - -// int oldI = newOrder.indexOf(newPath); - -// Path oldP = newOrder.set(newOrder.indexOf(path1),newPath); - -// newOrder.set(oldI, oldP); - } m_session.internalMove( tmpPath, dstPath, false ); } else { // // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. // Path p = newOrder.remove(srcIndex); if( dstIndex != -1 ) newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); else newOrder.add(p); } } finally { m_session.setSuper(isSuper); } // // Lock back up // if( lock != null ) { m_lockManager.moveLock( lock, dstPath ); } // // Finish. // enterState( ItemState.UPDATED ); m_childOrder = newOrder; } private PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ private PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); // prop.m_state = ItemState.NEW; // addChildProperty( prop ); // Again, a special case. First add the property to the lists. return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; // prop.setState( ItemState.NEW ); } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } else { // prop.setState( ItemState.UPDATED ); } if( value == null ) { removeProperty(prop); } else { //addChildProperty( prop ); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName);
jalkanen/Priha
70ca308d944e3a990a61a80a230d66d6d0b9195d
Fixed a number of compiler warnings.
diff --git a/tests/java/org/priha/core/MultiThreadTest.java b/tests/java/org/priha/core/MultiThreadTest.java index 391f560..a6647f4 100644 --- a/tests/java/org/priha/core/MultiThreadTest.java +++ b/tests/java/org/priha/core/MultiThreadTest.java @@ -1,248 +1,248 @@ package org.priha.core; import java.util.Random; import java.util.Vector; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.VersionException; import junit.framework.TestCase; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.core.PerformanceTest.Perf; public class MultiThreadTest extends TestCase { private static final int NUM_THREADS = 10; Vector<String> propertyPaths = new Vector<String>(); Vector<String> uuids = new Vector<String>(); public void testFileProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("filenocache.properties"); runRepoTest( rep, "File" ); } public void testEhFileProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("fileehcache.properties"); runRepoTest( rep, "FileEh" ); } public void testMemoryProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("memorynocache.properties"); runRepoTest( rep, "Memory" ); } public void testJdbcProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); runRepoTest( rep, "Jdbc" ); } public void testEhJdbcProvider() throws Exception { //Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcehcache.properties"); runRepoTest( rep, "JdbcEh" ); } private void runRepoTest( RepositoryImpl rep, String prefix ) throws InterruptedException, LoginException, RepositoryException { try { TestThread[] threads = new TestThread[NUM_THREADS]; for( int i = 0; i < NUM_THREADS; i++ ) { threads[i] = new TestThread(rep); threads[i].setName( prefix+"-TestThread-"+i ); threads[i].start(); } boolean someonestillalive = true; while(someonestillalive) { someonestillalive = false; Thread.sleep( 1000 ); for( TestThread tt : threads ) { if( !tt.isAlive() ) { if( tt.m_result != null ) fail( tt.m_result ); } else { someonestillalive = true; } } System.out.print( "." ); System.out.flush(); } } finally { System.out.println("\nAll threads done, now emptying repository..."); TestUtil.emptyRepo( rep ); } } public class TestThread extends Thread { private Repository m_repo; private Session m_session; public String m_result = null; private int m_numItems = 10; public TestThread( RepositoryImpl rep ) { m_repo = rep; } private void createRandomNodes() throws RepositoryException { Node nd = m_session.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("Save"); for( int i = 0; i < m_numItems; i++ ) { createRandomNode(nd); } m_session.save(); } private void createRandomNode(Node nd) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { String name = TestUtil.getUniqueID(16); String hash = "x-"+name.charAt(0); try { if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); n.addMixin("mix:referenceable"); Property p = n.setProperty( "test", TestUtil.getUniqueID(16) ); nd.save(); propertyPaths.add( p.getPath() ); uuids.add( n.getProperty("jcr:uuid").getString() ); } catch( RepositoryException e ) { // This is fine, since there should be some collisions } } public void readWriteRandomNodes() throws InterruptedException, RepositoryException { Random rand = new Random(); for( int i = 0; i < 500; i++ ) { Thread.sleep( rand.nextInt(20) ); int item = rand.nextInt( propertyPaths.size() ); try { Item ii = m_session.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), 16, ((Property)ii).getString().length() ); if( rand.nextDouble() > 0.95 ) { createRandomNode( m_session.getRootNode() ); } } - catch( PathNotFoundException e ) { } // OK + catch( PathNotFoundException e ) {} // OK } } public void readRandomNodes() throws InterruptedException, PathNotFoundException, RepositoryException { Random rand = new Random(); for( int i = 0; i < 5000; i++ ) { //Thread.sleep( rand.nextInt(20) ); int item = rand.nextInt( propertyPaths.size() ); try { Item ii = m_session.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), 16, ((Property)ii).getString().length() ); } catch( PathNotFoundException e ) {} // OK } } public void run() { Random rnd = new Random(); try { Thread.sleep( rnd.nextInt( 1000 ) ); m_session = m_repo.login(new SimpleCredentials("xxx",new char[0])); createRandomNodes(); Thread.sleep( 500 ); readWriteRandomNodes(); //Thread.sleep( rnd.nextInt( 1000 ) ); readRandomNodes(); } catch( Throwable t ) { t.printStackTrace(); m_result = t.getMessage(); } finally { m_session.logout(); } System.out.println("TestThread "+getName()+" finished"); } } } diff --git a/tests/java/org/priha/core/NodeImplTest.java b/tests/java/org/priha/core/NodeImplTest.java index 177ddf0..069d762 100644 --- a/tests/java/org/priha/core/NodeImplTest.java +++ b/tests/java/org/priha/core/NodeImplTest.java @@ -1,536 +1,539 @@ package org.priha.core; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; public class NodeImplTest extends AbstractTest { private SessionImpl m_session; private SessionImpl m_session2; @Override protected void setUp() throws Exception { super.setUp(); m_session = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = m_session.getRootNode().addNode("gobble"); nd.addMixin("mix:referenceable"); m_session.save(); m_session2 = m_repository.login(new SimpleCredentials("foo",new char[0])); } @Override protected void tearDown() throws Exception { super.tearDown(); m_session.logout(); m_session2.logout(); } public static Test suite() { return new TestSuite( NodeImplTest.class ); } public void testUUID() throws Exception { Node nd = (Node)m_session.getItem("/gobble"); assertNotNull( "no uuid", nd.getUUID() ); Node nd2 = m_session.getNodeByUUID( nd.getUUID() ); assertEquals( "wrong uuid", nd.getPath(), nd2.getPath() ); } public void testNew() throws Exception { Node nd = m_session.getRootNode().addNode("atari"); assertTrue("start",nd.isNew()); nd.addMixin("mix:referenceable"); assertTrue("mixin",nd.isNew()); nd.addNode("bar"); assertTrue("addnode",nd.isNew()); nd.setProperty("Garbage","out"); assertTrue("setproperty",nd.isNew()); m_session.refresh(true); } public void testReferences() throws Exception { Node gobble = (Node)m_session.getItem("/gobble"); Node nd = m_session.getRootNode().addNode( "zorp" ); nd.addMixin("mix:referenceable"); nd.setProperty("ownerOf", gobble); m_session.save(); Node gobble2 = (Node)m_session.getItem("/gobble"); PropertyIterator pi = gobble2.getReferences(); assertEquals( "wrong # of refs", 1, pi.getSize() ); Property p = pi.nextProperty(); assertEquals( "wrong ref", "ownerOf", p.getName() ); assertEquals( "wrong val", gobble2.getUUID(), p.getValue().getString() ); } /** Multiple references */ public void testReferences2() throws Exception { Node gobble = (Node)m_session.getItem("/gobble"); Node nd = m_session.getRootNode().addNode( "zorp" ); nd.addMixin("mix:referenceable"); nd.setProperty("ownerOf", gobble); nd = m_session.getRootNode().addNode( "burp" ); nd.addMixin("mix:referenceable"); nd.setProperty("ownerOf", gobble); m_session.save(); Node gobble2 = (Node)m_session.getItem("/gobble"); PropertyIterator pi = gobble2.getReferences(); assertEquals( "wrong # of refs", 2, pi.getSize() ); Property p = pi.nextProperty(); Property p2 = pi.nextProperty(); assertEquals( "wrong ref", "ownerOf", p.getName() ); assertEquals( "wrong val", gobble2.getUUID(), p.getValue().getString() ); assertEquals( "wrong ref 2", "ownerOf", p2.getName() ); assertEquals( "wrong val 2", gobble2.getUUID(), p2.getValue().getString() ); } public void testSave() throws Exception { Node root = m_session.getRootNode(); root.addNode("foo"); root.save(); Node test = m_session2.getRootNode().getNode("/foo"); assertNotNull( test ); } public void testGetNodes() throws Exception { Node root = m_session.getRootNode(); if( root.hasNode( "getnodestest" ) ) { fail("Repo not empty"); } Node x = root.addNode("getnodestest"); x.addNode("foo"); x.addNode("bar"); x.addNode("gobble"); root.save(); NodeIterator i = x.getNodes(); assertEquals("3", 3, i.getSize()); assertEquals("foo", "foo", i.nextNode().getName()); assertEquals("bar", "bar", i.nextNode().getName()); assertEquals("gobble", "gobble", i.nextNode().getName()); try { i.nextNode(); fail("Got past node count"); } catch( Exception e ) {} } public void testMixinLoadSave() throws Exception { Node root = m_session.getRootNode(); Node n = root.addNode("foo"); n.addMixin("mix:referenceable"); root.save(); Node n2 = m_session2.getRootNode().getNode("foo"); Property p = n2.getProperty("jcr:mixinTypes"); Value[] v = p.getValues(); boolean found = false; for( Value vv : v ) { - if( vv.getString().equals("mix:referenceable") ) { found = true; }; + if( vv.getString().equals("mix:referenceable") ) { found = true; } } assertTrue("mix:referenceable not found",found); assertNotNull( n2.getUUID() ); } public void testModified() throws Exception { Node root = m_session.getRootNode(); Node n = root.addNode("foo"); m_session.save(); assertFalse( "Not modified", n.isModified() ); n.setProperty("gii","blaa"); assertTrue( "Property add didn't reflect up to the changed node", n.isModified() ); } public void testDeleteAndReplace() throws Exception { Node n = m_session.getRootNode().addNode( "foo" ); n.setProperty( "prop1", "testproperty" ); m_session.save(); assertTrue( "property never appeared", n.hasProperty( "prop1" ) ); // Remove Property p = n.getProperty( "prop1" ); p.remove(); n.save(); assertFalse( "property still here", n.hasProperty( "prop1" ) ); n.setProperty( "prop1", "new value" ); n.save(); assertTrue( "property disappeared", n.hasProperty( "prop1" ) ); assertEquals( "property value", "new value", n.getProperty( "prop1" ).getString()); } + @SuppressWarnings("unused") public void testReorder1() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo1"); Node n2 = root.addNode("Foo2"); Node n3 = root.addNode("Foo3"); Node n4 = root.addNode("Foo4"); Node n5 = root.addNode("Foo5"); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); root.orderBefore("Foo1", null); // Works before save() ni = root.getNodes(); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); assertEquals("Foo1",ni.nextNode().getName()); root.save(); // works after save ni = root.getNodes(); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); assertEquals("Foo1",ni.nextNode().getName()); } + @SuppressWarnings("unused") public void testReorder2() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo1"); Node n2 = root.addNode("Foo2"); Node n3 = root.addNode("Foo3"); Node n4 = root.addNode("Foo4"); Node n5 = root.addNode("Foo5"); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); root.orderBefore("Foo4", "Foo2"); // Works before save() ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); root.save(); // works after save ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); } + @SuppressWarnings("unused") public void testReorder3() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo1"); Node n2 = root.addNode("Foo2"); Node n3 = root.addNode("Foo3"); Node n4 = root.addNode("Foo4"); Node n5 = root.addNode("Foo5"); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); root.orderBefore("Foo2", "Foo4"); // Works before save() ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); root.save(); // works after save ni = root.getNodes(); assertEquals("Foo1",ni.nextNode().getName()); assertEquals("Foo3",ni.nextNode().getName()); assertEquals("Foo2",ni.nextNode().getName()); assertEquals("Foo4",ni.nextNode().getName()); assertEquals("Foo5",ni.nextNode().getName()); } public void testSNS1() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo"); n1.setProperty("order", 1); Node n2 = root.addNode("Foo"); n2.setProperty("order", 2); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertTrue( m_session.itemExists( "/root/Foo/order" ) ); assertTrue( m_session.itemExists( "/root/Foo[1]/order" ) ); assertTrue( m_session.itemExists( "/root/Foo[2]/order" ) ); assertTrue( m_session.itemExists( "/root/Foo[2]" ) ); assertTrue( m_session.itemExists( "/root/Foo[1]" ) ); m_session.dump(); root.remove(); m_session.dump(); m_session.save(); m_session.dump(); assertFalse( "/root/Foo/order", m_session.itemExists( "/root/Foo/order" ) ); assertFalse( "/root/Foo[1]/order", m_session.itemExists( "/root/Foo[1]/order" ) ); assertFalse( "/root/Foo[2]/order", m_session.itemExists( "/root/Foo[2]/order" ) ); assertFalse( "/root/Foo[2]", m_session.itemExists( "/root/Foo[2]" ) ); assertFalse( "/root/Foo[1]", m_session.itemExists( "/root/Foo[1]" ) ); assertFalse( "/root", m_session.itemExists( "/root" ) ); } public void testReorderSNS1() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo"); n1.setProperty("order", 1); Node n2 = root.addNode("Foo"); n2.setProperty("order", 2); Node n3 = root.addNode("Foo"); n3.setProperty("order", 3); Node n4 = root.addNode("Foo"); n4.setProperty("order", 4); Node n5 = root.addNode("Foo"); n5.setProperty("order", 5); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); root.orderBefore("Foo[1]", null); // Works before save() ni = root.getNodes(); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); assertEquals(1,ni.nextNode().getProperty("order").getLong()); root.save(); // works after save ni = root.getNodes(); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); assertEquals(1,ni.nextNode().getProperty("order").getLong()); } public void testReorderSNS2() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo"); n1.setProperty("order", 1); Node n2 = root.addNode("Foo"); n2.setProperty("order", 2); Node n3 = root.addNode("Foo"); n3.setProperty("order", 3); Node n4 = root.addNode("Foo"); n4.setProperty("order", 4); Node n5 = root.addNode("Foo"); n5.setProperty("order", 5); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); root.orderBefore("Foo[4]", "Foo[2]"); // Works before save() ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); root.save(); // works after save ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); } public void testReorderSNS3() throws Exception { Node root = m_session.getRootNode().addNode("root", "nt:unstructured"); Node n1 = root.addNode("Foo"); n1.setProperty("order", 1); Node n2 = root.addNode("Foo"); n2.setProperty("order", 2); Node n3 = root.addNode("Foo"); n3.setProperty("order", 3); Node n4 = root.addNode("Foo"); n4.setProperty("order", 4); Node n5 = root.addNode("Foo"); n5.setProperty("order", 5); m_session.save(); NodeIterator ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); root.orderBefore("Foo[2]", "Foo[4]"); // Works before save() ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); root.save(); // works after save ni = root.getNodes(); assertEquals(1,ni.nextNode().getProperty("order").getLong()); assertEquals(3,ni.nextNode().getProperty("order").getLong()); assertEquals(2,ni.nextNode().getProperty("order").getLong()); assertEquals(4,ni.nextNode().getProperty("order").getLong()); assertEquals(5,ni.nextNode().getProperty("order").getLong()); } } diff --git a/tests/java/org/priha/core/PerformanceTest.java b/tests/java/org/priha/core/PerformanceTest.java index c55fed6..c84a4fc 100644 --- a/tests/java/org/priha/core/PerformanceTest.java +++ b/tests/java/org/priha/core/PerformanceTest.java @@ -1,701 +1,701 @@ package org.priha.core; import java.io.ByteArrayInputStream; import java.util.*; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.Release; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.core.RepositoryImpl; public class PerformanceTest extends TestCase { /** The size of a million can be configured here. ;-) */ private static final int DEFAULT_ITERATIONS = 100; private int m_iterations = DEFAULT_ITERATIONS; - private static int BLOB_SIZE = 1024*100; + private static final int BLOB_SIZE = 1024*100; private int m_blobsize = BLOB_SIZE; - private static int NODENAMELEN = 16; - private static int PROPERTYLEN = 16; + private static final int NODENAMELEN = 16; + private static final int PROPERTYLEN = 16; private Credentials m_creds = new SimpleCredentials("username","password".toCharArray()); private boolean m_memoryProviderTest = true; private boolean m_jackrabbitTest = true; private boolean m_jdbcProviderTest = true; private boolean m_jdbcProviderEhTest = true; private boolean m_fileProviderTest = true; private boolean m_fileProviderEhTest = true; private boolean m_largeTests = true; public void setUp() { String iters = System.getProperty("perftest.iterations"); if( iters != null ) m_iterations = Integer.parseInt(iters); String blobsize = System.getProperty("perftest.blobsize"); if( blobsize != null ) m_blobsize = Integer.parseInt(blobsize)*1024; } public void testMemoryProvider() throws Exception { if( !m_memoryProviderTest ) return; Perf.setProvider("MemoryProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("memorynocache.properties"); millionIterationsTest( rep, m_creds , m_iterations ); } public void testFileProvider() throws Exception { if( !m_fileProviderTest ) return; Perf.setProvider("FileProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("filenocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testFileEhcacheProvider() throws Exception { if( !m_fileProviderEhTest ) return; Perf.setProvider("FileProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("fileehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcProvider() throws Exception { if( !m_jdbcProviderTest ) return; Perf.setProvider("JdbcProvider, no cache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public void testJdbcEhcacheProvider() throws Exception { if( !m_jdbcProviderEhTest ) return; Perf.setProvider("JdbcProvider, with Ehcache"); RepositoryImpl rep = RepositoryManager.getRepository("jdbcehcache.properties"); millionIterationsTest( rep, m_creds, m_iterations ); } public static Repository getJackrabbitRepository() { try { Class<?> cc = Class.forName("org.apache.jackrabbit.core.TransientRepository"); return (Repository) cc.newInstance(); } catch( Exception e ) { return null; } } public void testJackrabbit() throws Exception { if( !m_jackrabbitTest ) return; Perf.setProvider("Jackrabbit"); Repository rep = getJackrabbitRepository(); if( rep != null ) { millionIterationsTest(rep, m_creds, m_iterations); } else { System.out.println("Skipping Jackrabbit comparison tests; classes not found in classpath"); } } /** Just a dummy test which is executed last and it will print out the * test result. */ public void testPrint() { Perf.print(this); } public static class TesterClass { private Repository m_repository; private Credentials m_creds; private int m_numNodes; private int m_readIters; private byte[] m_blob; ArrayList<String> propertyPaths = new ArrayList<String>(); ArrayList<String> uuids = new ArrayList<String>(); private boolean m_testNewSession = true; private boolean m_testSeqRead = true; private boolean m_testRandRead = true; private boolean m_testUUIDRead = true; private boolean m_testLargeRead = true; private boolean m_testCachedNode = true; private boolean m_testUpdate = true; public TesterClass(Repository rep, Credentials creds, int numIters, byte[] blob) { m_repository = rep; m_creds = creds; m_numNodes = numIters; m_readIters = numIters * 10; m_blob = blob; } public void testNewSession() throws LoginException, RepositoryException { if( !m_testNewSession ) return; // We want to make sure that we don't get the penalty of the first // session here. Session prime = m_repository.login(m_creds); try { // // Test how quickly subsequent sessions can be acquired. // Perf.start("NewSession"); for( int i = 0; i < m_numNodes; i++ ) { Session s2 = m_repository.login(m_creds); s2.logout(); } Perf.stop(m_numNodes); } finally { prime.logout(); } } public void testSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("Save"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID(NODENAMELEN); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); n.addMixin("mix:referenceable"); Property p = n.setProperty( "test", TestUtil.getUniqueID(PROPERTYLEN) ); propertyPaths.add( p.getPath() ); nd.save(); uuids.add( n.getProperty("jcr:uuid").getString() ); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testLargeSave() throws LoginException, RepositoryException { Session s = m_repository.login(m_creds); try { Node nd = s.getRootNode(); // // Test how quickly we can save a node and a single // property to it. // Perf.start("LargeSave"); for( int i = 0; i < m_numNodes; i++ ) { String name = TestUtil.getUniqueID( NODENAMELEN ); String hash = "x-"+name.charAt(0); if( !nd.hasNode(hash) ) { nd.addNode(hash); } Node n = nd.addNode( hash+"/"+name ); Property p = n.setProperty( "test", new ByteArrayInputStream(m_blob) ); propertyPaths.add( p.getPath() ); nd.save(); } s.save(); Perf.stop( m_numNodes ); } finally { s.logout(); } } public void testSeqRead() throws LoginException, RepositoryException { if( !m_testSeqRead ) return; Session s = m_repository.login(m_creds); try { // // Test how quickly we can read all the properties // of a single node using getNodes(). // Perf.start("SeqRead"); Node nd = s.getRootNode(); for( NodeIterator i = nd.getNodes(); i.hasNext(); ) { Node n = i.nextNode(); // Skip nodes which weren't created in this test. if( n.getName().startsWith("x-") ) { for( NodeIterator i2 = n.getNodes(); i2.hasNext(); ) { Node n2 = i2.nextNode(); Property p = n2.getProperty("test"); assertEquals( p.getName(), PROPERTYLEN, p.getString().length() ); } } } Perf.stop(m_numNodes); } finally { s.logout(); } } public void testRandRead() throws LoginException, RepositoryException { if( !m_testRandRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("RandRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), PROPERTYLEN, ((Property)ii).getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testUUIDRead() throws LoginException, RepositoryException { if( !m_testUUIDRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("UUID"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( uuids.size() ); Node ni = s.getNodeByUUID( uuids.get(item) ); assertEquals( ni.getName(), PROPERTYLEN, ni.getProperty("test").getString().length() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testLargeRead() throws LoginException, RepositoryException { if( !m_testLargeRead ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and read. // Perf.start("LargeRead"); for( int i = 0; i < m_readIters; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Item ii = s.getItem( propertyPaths.get(item) ); assertFalse( ii.getPath(), ii.isNode() ); assertEquals( ii.getName(), m_blob.length, ((Property)ii).getLength()); } Perf.stop(m_readIters); } finally { s.logout(); } } /** * Produces two figures: getProperty and getItem. The same item * is fetched through both methods, and the performance is measured. */ public void testCachedNode() throws RepositoryException { if( !m_testCachedNode ) return; Session s = m_repository.login(m_creds); try { String ss = propertyPaths.get( 0 ); Item ii = s.getItem(ss); Node nd = ii.getParent(); String propName = ii.getName(); // // First, access directly with getProperty() // Perf.start("getProperty"); for( int i = 0; i < m_readIters; i++ ) { Property prop = nd.getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // // Then, with getItem() // Perf.start("getItem"); for( int i = 0; i < m_readIters; i++ ) { Property prop = (Property) s.getItem( ss ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); // Finally, with getByUUID() String uuid = uuids.get(0); Perf.start("propUUID"); for( int i = 0; i < m_readIters; i++ ) { Property prop = s.getNodeByUUID( uuid ).getProperty( propName ); assertNotNull( prop.getString() ); } Perf.stop(m_readIters); } finally { s.logout(); } } public void testUpdate() throws RepositoryException { if( !m_testUpdate ) return; Session s = m_repository.login(m_creds); try { Random rand = new Random(); // // Test the speed of random access to properties. A property // is chosen by random and updated // Perf.start("Update"); for( int i = 0; i < m_numNodes; i++ ) { int item = rand.nextInt( propertyPaths.size() ); Property ii = (Property)s.getItem( propertyPaths.get(item) ); ii.setValue( "modified result" ); s.save(); } Perf.stop(m_numNodes); } finally { s.logout(); } } } public void millionIterationsTest( Repository rep, Credentials creds, int numIters ) throws Exception { TesterClass tc = new TesterClass( rep, creds, numIters, getBlob() ); try { // // Test how quickly the first session can be opened. // Perf.start("FirstSess"); Session s = rep.login(creds); Perf.stop(1); s.logout(); TestUtil.emptyRepo(rep); tc.testNewSession(); tc.testSave(); tc.testSeqRead(); tc.testRandRead(); tc.testUUIDRead(); tc.testUpdate(); tc.testCachedNode(); // // Test how quickly we can then empty the repository. // Perf.start("Remove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); if( m_largeTests ) { // // Large objects // getBlob(); tc.testLargeSave(); tc.testLargeRead(); Perf.start("LargeRemove"); TestUtil.emptyRepo(rep); tc.propertyPaths.clear(); Perf.stop(numIters); } } catch( Exception t ) { t.printStackTrace(); throw t; } finally { TestUtil.emptyRepo(rep); } } private static byte[] blob; private final byte[] getBlob() { if( blob == null) { blob = new byte[m_blobsize]; // 1 Meg for( int i = 0; i < m_blobsize; i++ ) blob[i] = (byte) (i % 255); } return blob; } public static Test suite() { return new TestSuite( PerformanceTest.class ); } /** * This class stores all results to a local hashmap, which can then be pretty-printed. * */ public static class Perf { private static HashMap<String, HashMap<String, Double>> results = new LinkedHashMap<String,HashMap<String,Double>>(); private static long startTime; private static String currTest; private static String currProvider; public static void setProvider(String p) { currProvider = p; } public static void start( String test ) { currTest = test; startTime = System.nanoTime(); } public static void stop( int iters ) { long stop = System.nanoTime(); long time = stop-startTime; - double itersSec = iters/((double)time/1e9); + double itersSec = iters/(time/1e9); HashMap<String,Double> hm; hm = results.get(currProvider); if( hm == null ) { hm = new HashMap<String,Double>(); results.put(currProvider, hm); } hm.put(currTest, itersSec); //TestUtil.printSpeed(currProvider+": "+currTest, iters, startTime, stop); } public static void print(PerformanceTest test) { System.out.println("Test results. The number is operations/seconds - larger means faster."); System.out.println("Blob size "+test.m_blobsize/1024+" kB"); System.out.println("Repository size "+test.m_iterations+" nodes"); System.out.println("Priha version "+Release.VERSTR); Repository jr = getJackrabbitRepository(); if( jr != null ) System.out.println("Jackrabbit version "+jr.getDescriptor( Repository.REP_VERSION_DESC )); ArrayList<String> keys = new ArrayList<String>(); keys.addAll( results.values().iterator().next().keySet() ); Collections.sort(keys); System.out.printf("%-30s",""); for( String key : keys ) { System.out.printf("%12s",key); } System.out.print("\n"); for( Map.Entry<String,HashMap<String,Double>> e : results.entrySet() ) { System.out.printf( "%-30s", e.getKey() ); for( String key : keys ) { Double val = e.getValue().get(key); if( val != null && val < 1 ) System.out.printf("%12.2f",val); else System.out.printf("%12.0f", val != null ? val : Double.NaN ); } System.out.print("\n"); } } } } diff --git a/tests/java/org/priha/core/RepositoryTest.java b/tests/java/org/priha/core/RepositoryTest.java index 529cc49..9e270dc 100644 --- a/tests/java/org/priha/core/RepositoryTest.java +++ b/tests/java/org/priha/core/RepositoryTest.java @@ -1,359 +1,359 @@ package org.priha.core; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.logging.Logger; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; import org.priha.RepositoryManager; import org.priha.TestUtil; public class RepositoryTest extends AbstractTest { Logger log = Logger.getLogger(RepositoryTest.class.getName()); Session m_session; protected void setUp() throws Exception { super.setUp(); TestUtil.emptyRepo(m_repository); m_session = m_repository.login(new SimpleCredentials("foo",new char[0])); } protected void tearDown() throws Exception { m_session.logout(); super.tearDown(); } public void testLogin() throws Exception { Node nd = m_session.getRootNode(); assertEquals( 0, nd.getDepth() ); } public void testShutdown() throws Exception { RepositoryImpl r = RepositoryManager.getRepository("priha_shutdown.properties"); Session s = r.login(); assertTrue("session start",s.isLive()); r.shutdown(); assertFalse("session should be closed", s.isLive()); try { r.login(); fail("Allowed login"); } catch( RepositoryException e ) { // Expected } } /** * Peek directly into the FileProvider repository to figure out if all the files * are properly removed. Weeds out files which are part of the system. * * @throws Exception */ public void testEmptyRepo() throws Exception { Node nd = m_session.getRootNode().addNode("testemptyrepo"); nd = nd.addNode("foo"); nd.setProperty("Barbapapa","Barbamama"); m_session.save(); TestUtil.emptyRepo(m_repository); File f = new File("/tmp/priha/fileprovider/workspaces/default/"); String[] paths = f.list(); for( String p : paths ) { if( p.startsWith("jcr;") || p.startsWith( "priha;") || p.startsWith( "." )) continue; // This is okay fail( "This was not removed: "+p ); } } public void testRemove() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); s.getRootNode().addNode("test"); s.save(); assertTrue( "was not created", s.getRootNode().hasNode("/test") ); Node nd = s.getRootNode().getNode("/test"); nd.remove(); s.save(); assertFalse( "was not removed", s.getRootNode().hasNode("/test") ); File f = new File("/tmp/priha/fileprovider/workspaces/default/test"); assertFalse( "File was not removed", f.exists() ); } public void testSave() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); Item it = s.getItem("/test"); assertTrue( "is not node", it.isNode() ); assertEquals( "wrong property", "foo",((Node)it).getProperty("a").getString()); } public void testSave2() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); s.logout(); s = m_repository.login(); Item it = s.getItem("/test"); assertTrue( "is not node", it.isNode() ); assertEquals( "wrong property", "foo",((Node)it).getProperty("a").getString()); } public void testRemoveProperty() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); nd.setProperty("foo", "bar"); s.save(); Item i = s.getItem("/foo"); assertTrue( "wrong type", i instanceof Property ); assertEquals( "wrong content", "bar", ((Property)i).getValue().getString() ); i.remove(); s.save(); Session s2 = m_repository.login(); try { s2.getItem("/foo"); fail("Still got it"); } catch( PathNotFoundException e ) { // Expected } File f = new File("/tmp/priha/fileprovider/workspaces/default/foo.info"); assertFalse( "File was not removed", f.exists() ); } public void testTraversal() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); boolean testFound = false; for( NodeIterator it = nd.getNodes(); it.hasNext(); ) { Node n = it.nextNode(); if( n.getName().equals("test") ) { testFound = true; } else if( n.getName().equals("jcr:system") ) { // We ignore this } else { fail("Extraneous node found"); } } assertTrue( "test node not found", testFound ); } - + @SuppressWarnings("unused") public void testBinaryProperty() throws Exception { Node nd = m_session.getRootNode(); nd = nd.addNode("binarytest"); String content = TestUtil.getUniqueID(32); InputStream in = new ByteArrayInputStream( content.getBytes() ); Property p = nd.setProperty("blob", in ); m_session.save(); Property p2 = (Property) m_session.getItem("/binarytest/blob"); assertEquals( content, p2.getString() ); } public void testMultiProviders() throws Exception { Repository r = RepositoryManager.getRepository("multiprovidertest.properties"); TestUtil.emptyRepo(r); Session s = r.login(new SimpleCredentials("foo",new char[0])); Session s2 = r.login(new SimpleCredentials("foo",new char[0]),"testworkspace"); assertFalse( "Must end up in different workspaces", s.getWorkspace().getName().equals(s2.getWorkspace().getName()) ); Node nd = s2.getRootNode().addNode("largefiles"); nd = nd.addNode("test"); nd.setProperty("reallybig", 42); nd = s.getRootNode().addNode("small"); nd.setProperty("reallysmall", "foobar"); s.save(); s2.save(); File f = new File("/tmp/priha-multi/fileprovider/workspaces/default/small/reallysmall.info"); assertTrue("small", f.exists() ); File f2 = new File("/tmp/priha-multi/fileprovider2/workspaces/testworkspace/largefiles/test/reallybig.info"); assertTrue("big", f2.exists() ); Property p = (Property)s.getItem("/small/reallysmall"); assertEquals("small content","foobar",p.getString()); p = (Property)s2.getItem("/largefiles/test/reallybig"); assertEquals("big content", p.getLong(), 42 ); s.logout(); s2.logout(); TestUtil.emptyRepo(r); assertFalse("small remove", f.exists()); assertFalse("big remove", f2.exists()); } public void testSameNameSiblings() throws Exception { Node nd = m_session.getRootNode().addNode("test", "nt:unstructured"); Node nd21 = nd.addNode( "samename", "nt:unstructured" ); nd21.setProperty( "order", 1 ); Node nd22 = nd.addNode( "samename", "nt:unstructured" ); nd22.setProperty( "order", 2 ); Node nd23 = nd.addNode( "samename", "nt:unstructured" ); nd23.setProperty( "order", 3 ); m_session.save(); nd = (Node) m_session.getItem("/test/samename[1]"); assertEquals( "one", 1, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[2]"); assertEquals( "two", 2, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[3]"); assertEquals( "three", 3, nd.getProperty( "order" ).getLong() ); } public void testSameNameSiblingsRemoval() throws Exception { Node nd = m_session.getRootNode().addNode("test", "nt:unstructured"); Node nd21 = nd.addNode( "samename", "nt:unstructured" ); nd21.setProperty( "order", 1 ); Node nd22 = nd.addNode( "samename", "nt:unstructured" ); nd22.setProperty( "order", 2 ); Node nd23 = nd.addNode( "samename", "nt:unstructured" ); nd23.setProperty( "order", 3 ); m_session.save(); nd22.remove(); m_session.save(); nd = (Node) m_session.getItem("test"); NodeIterator ni = nd.getNodes(); assertEquals( "samename1", "/test/samename", ni.nextNode().getPath() ); assertEquals( "samename2", "/test/samename[2]", ni.nextNode().getPath() ); try { ni.nextNode(); fail("Got third node!"); } catch( NoSuchElementException e ) {} nd = (Node) m_session.getItem("/test/samename[1]"); assertEquals( "one", 1, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[2]"); assertEquals( "samename[3] not moved to samename[2]", 3, nd.getProperty( "order" ).getLong() ); } public static Test suite() { return new TestSuite( RepositoryTest.class ); } } diff --git a/tests/java/org/priha/providers/FileProviderTest.java b/tests/java/org/priha/providers/FileProviderTest.java index 073abfb..34a06c6 100644 --- a/tests/java/org/priha/providers/FileProviderTest.java +++ b/tests/java/org/priha/providers/FileProviderTest.java @@ -1,136 +1,138 @@ package org.priha.providers; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; import org.priha.TestUtil; import org.priha.core.SessionImpl; public class FileProviderTest extends AbstractTest { SessionImpl m_session; public void setUp() throws Exception { super.setUp(); m_session = getNewSession(); } public void tearDown() throws Exception { TestUtil.emptyRepo(m_session.getRepository()); m_session.logout(); super.tearDown(); } private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { Node nd = m_session.getRootNode().addNode(UTF8_NAME); nd.setProperty(UTF8_NAME, UTF8_NAME); m_session.save(); Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); Property p2 = nd2.getProperty(UTF8_NAME); assertEquals(UTF8_NAME,nd2.getName()); assertEquals(UTF8_NAME,p2.getName()); assertEquals(UTF8_NAME,p2.getString()); } /** * JCR names are case-sensitive, so let's check that all these work. */ + @SuppressWarnings("unused") public void testCase1() throws Exception { Node nd = m_session.getRootNode().addNode("Test One"); nd.setProperty("Property One","KILL"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/test one"); fail("Found with wrong case"); } catch( PathNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/Test One/property one"); fail("Found property with wrong case"); } catch( PathNotFoundException e ) {} } + @SuppressWarnings("unused") public void testCase2() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("B", "foo"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/a"); fail("Found with wrong case"); } catch( PathNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/A/b"); fail("Found property with wrong case"); } catch( PathNotFoundException e ) {} } public void testCase3() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); Node nd2 = m_session.getRootNode().addNode("a"); nd2.setProperty("x","foo-b"); m_session.save(); assertFalse("same",nd.isSame(nd2)); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); Node ndb = (Node) m_session.getItem("/a"); assertEquals("foo-b",ndb.getProperty("x").getString()); } public void testPropertyCase1() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); nd.setProperty("X","foo-b"); m_session.save(); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); assertEquals("foo-b",nda.getProperty("X").getString()); } public static Test suite() { return new TestSuite( FileProviderTest.class ); } } diff --git a/tests/java/org/priha/providers/JdbcProviderTest.java b/tests/java/org/priha/providers/JdbcProviderTest.java index b5c5c2e..12362d4 100644 --- a/tests/java/org/priha/providers/JdbcProviderTest.java +++ b/tests/java/org/priha/providers/JdbcProviderTest.java @@ -1,141 +1,143 @@ package org.priha.providers; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.core.RepositoryImpl; import org.priha.core.SessionImpl; public class JdbcProviderTest extends TestCase { SessionImpl m_session; public void setUp() throws Exception { super.setUp(); RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); m_session = rep.login(new SimpleCredentials("foo",new char[0])); } public void tearDown() throws Exception { Repository rep = m_session.getRepository(); m_session.logout(); TestUtil.emptyRepo(rep); super.tearDown(); } private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { Node nd = m_session.getRootNode().addNode(UTF8_NAME, "priha:referenceable"); nd.setProperty(UTF8_NAME, UTF8_NAME); m_session.save(); Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); Property p2 = nd2.getProperty(UTF8_NAME); assertEquals(UTF8_NAME,nd2.getName()); assertEquals(UTF8_NAME,p2.getName()); assertEquals(UTF8_NAME,p2.getString()); } /** * JCR names are case-sensitive, so let's check that all these work. */ + @SuppressWarnings("unused") public void testCase1() throws Exception { Node nd = m_session.getRootNode().addNode("Test One"); nd.setProperty("Property One","KILL"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/test one"); fail("Found with wrong case"); } catch( PathNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/Test One/property one"); fail("Found property with wrong case"); } catch( PathNotFoundException e ) {} } + @SuppressWarnings("unused") public void testCase2() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("B", "foo"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/a"); fail("Found with wrong case"); } catch( PathNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/A/b"); fail("Found property with wrong case"); } catch( PathNotFoundException e ) {} } public void testCase3() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); Node nd2 = m_session.getRootNode().addNode("a"); nd2.setProperty("x","foo-b"); m_session.save(); assertFalse("same",nd.isSame(nd2)); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); Node ndb = (Node) m_session.getItem("/a"); assertEquals("foo-b",ndb.getProperty("x").getString()); } public void testPropertyCase1() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); nd.setProperty("X","foo-b"); m_session.save(); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); assertEquals("foo-b",nda.getProperty("X").getString()); } public static Test suite() { return new TestSuite( JdbcProviderTest.class ); } } diff --git a/tests/java/org/priha/query/XPathTest.java b/tests/java/org/priha/query/XPathTest.java index cbb0083..38e89de 100644 --- a/tests/java/org/priha/query/XPathTest.java +++ b/tests/java/org/priha/query/XPathTest.java @@ -1,196 +1,194 @@ package org.priha.query; -import java.util.ArrayList; - import javax.jcr.*; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.util.ConfigurationException; public class XPathTest extends TestCase { private Session m_session; private QueryManager m_mgr; public void setUp() throws LoginException, ConfigurationException, RepositoryException { TestUtil.emptyRepo(RepositoryManager.getRepository()); m_session = RepositoryManager.getRepository().login(new SimpleCredentials("foo",new char[0])); Node nd = m_session.getRootNode(); nd = nd.addNode("bookstore"); nd = nd.addNode("book"); nd.setProperty("title","How to cook humans"); nd.setProperty("price",35.0); nd = nd.getParent().addNode("book2"); nd.setProperty("title","How to cook forty humans"); nd.setProperty("price",42.0); nd = nd.getParent().addNode("funbooks"); nd = nd.addNode("book"); nd.setProperty("title","How to cook for forty humans"); nd.setProperty("price",19.0); m_session.save(); m_mgr = m_session.getWorkspace().getQueryManager(); } public void tearDown() throws LoginException, RepositoryException { TestUtil.emptyRepo(m_session.getRepository()); m_session.logout(); } private void checkMatchedPaths( QueryResult qr, String... paths ) throws RepositoryException { int idx = 0; for( NodeIterator ni = qr.getNodes(); ni.hasNext(); ) { Node totest = ni.nextNode(); if( totest.getName().startsWith( "jcr:" ) ) continue; assertEquals( paths[idx], paths[idx], totest.getPath() ); idx++; } } public void testNodeQuery1() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore/book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book" ); } public void testNodeQuery2() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore/book/title", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr ); } public void testQuery1() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore/book[@title]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book" ); } public void testQuery2() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*[@title]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book", "/bookstore/book2", "/bookstore/funbooks/book" ); } public void testQuery3() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore", "/bookstore/book", "/bookstore/book2", "/bookstore/funbooks", "/bookstore/funbooks/book"); } public void testQuery32() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore", "/bookstore/book", "/bookstore/book2", "/bookstore/funbooks", "/bookstore/funbooks/book"); Node nd = m_session.getRootNode().getNode("bookstore/book2"); nd.remove(); m_session.save(); q = m_mgr.createQuery( "//*", Query.XPATH ); qr = q.execute(); checkMatchedPaths( qr, "/bookstore", "/bookstore/book", "/bookstore/funbooks", "/bookstore/funbooks/book"); } public void testQuery4() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore//book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book", "/bookstore/funbooks/book" ); } public void testQuery5() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book", "/bookstore/funbooks/book" ); } public void testQuery6() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//funbooks/book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/funbooks/book" ); } public void testDoubleValueQuery() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*[price > 40.0]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book2" ); } public void testContainsQuery() throws Exception { Query q = m_mgr.createQuery("//*[jcr:contains(.,'forty')]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book2", "/bookstore/funbooks/book" ); } public void testContainsQuery2() throws Exception { Query q = m_mgr.createQuery("//*[jcr:contains(@title,'forty')]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book2", "/bookstore/funbooks/book" ); } public static Test suite() { return new TestSuite( XPathTest.class ); } }
jalkanen/Priha
c7bb4ff427ed512ae8a7facb6b84bcc593fdfad1
0.6.4 alpha, improved release building.
diff --git a/build.xml b/build.xml index baa39ed..a5ab5c8 100644 --- a/build.xml +++ b/build.xml @@ -1,260 +1,273 @@ <?xml version="1.0"?> <!-- A rather non-fancy build file. --> <project name="Priha" default="jar"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> <include name="*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> <!-- Jackrabbit is only included if it has been installed with maven --> <fileset dir="${user.home}"> <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> <include name=".m2/repository/commons-collections/**/*3.2.jar"/> <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> </fileset> </path> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> <src path="src/java"/> <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> <src path="tests/java"/> <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> - + <delete dir="tests/build"/> + </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> <!-- ***************************************************************** --> <!-- Distribution package building. - Use "ant dist" to build the distro package. + Use "ant dist" to build the distro package, and + "ant srczip" to create a source tarball. --> + <target name="srczip" depends="compile"> + <java classpath="build" outputproperty="version" classname="org.priha.Release" + args="-versiononly"> + </java> + + <zip zipfile="build/priha-${version}-src.zip"> + <zipfileset dir="." + excludes="build/** tests/build/** repository*/** tests/reports/** *.log doc/javadoc/**" + prefix="priha-${version}"/> + </zip> + </target> <target name="dist" depends="jar,javadoc"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}.zip"> <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> <zipfileset dir="." includes="ChangeLog README LICENSE NOTICE doc/**" prefix="priha-${version}"/> <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> <zipfileset dir="lib" includes="ehcache-*.jar hsqldb-*.jar" prefix="priha-${version}/extras-lib"/> </zip> </target> </project> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 557030d..ae04ca7 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,124 +1,130 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ public static final int MINORREVISION = 4; + /** + * E.g. "alpha" or "beta". + */ + public static final String POSTFIX = "alpha"; + /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ - public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; + public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ + ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : ""); private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Prevent instantiation. */ private Release() {} /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. * * @param argv Arguments. Currently allowed argument is "-versiononly", which prints * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } }
jalkanen/Priha
3eca4888183e7ff80cf8fda6bf387614ba81bf77
Fixed licenses, removed mysql connector.
diff --git a/.classpath b/.classpath index 8386e9b..6554b4f 100644 --- a/.classpath +++ b/.classpath @@ -1,21 +1,20 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src/java"/> <classpathentry kind="src" path="tests/java"/> <classpathentry kind="src" path="tests/tck"/> <classpathentry kind="src" path="src/generated-sources"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3.8.1"/> <classpathentry exported="true" kind="lib" path="tests/etc"/> <classpathentry kind="lib" path="etc"/> <classpathentry kind="lib" path="lib/jcr-1.0.jar"/> <classpathentry kind="lib" path="lib/javax.servlet.jar"/> <classpathentry kind="lib" path="lib/slf4j-api-1.5.3.jar"/> <classpathentry kind="lib" path="lib/slf4j-simple-1.5.3.jar"/> <classpathentry kind="lib" path="lib/ehcache-1.6.0.jar"/> <classpathentry kind="lib" path="lib/concurrent-1.3.4.jar"/> <classpathentry kind="lib" path="lib/hsqldb-1.8.0.10.jar"/> <classpathentry kind="lib" path="lib/h2-1.1.118.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> - <classpathentry kind="lib" path="lib/mysql-connector-java-5.1.8-bin.jar"/> <classpathentry kind="output" path="build"/> </classpath> diff --git a/NOTICE b/NOTICE index 98cb300..d81e131 100644 --- a/NOTICE +++ b/NOTICE @@ -1,9 +1,159 @@ Priha contains code developed and (C) Janne Jalkanen, 2006-2009. The Query Engine contains code developed by the Apache Software Foundation, used under the Apache Public License, v2.0. +ISO8601 code developed by Apache Software Foundation, used under the Apache Public +License v2.0. + Contains the JCR TCK developed by the Apache Software Foundation. Contains Base64 code from Robert Harder, under Public Domain. + +Libraries +========= + +jcr-1.0.jar +----------- + +TBD + +javax.servlet.jar +----------------- + +TBD + +SLF4J +----- +Copyright (c) 2004-2008 QOS.ch + +All rights reserved. Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and +to permit persons to whom the Software is furnished to do so, subject to the following +conditions: The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +EhCache +------- + +Copyright 2003-2009 Terracotta, Inc. Used under the Apache Public License 2.0. + +Concurrent +---------- + +(C) Doug Lea and Sun Microsystems. + +Hsqldb +------ + +Copyright (c) 1995-2000 by the Hypersonic SQL Group. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +Neither the name of the Hypersonic SQL Group nor the names of its +contributors may be used to endorse or promote products derived from this +software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP, +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +This software consists of voluntary contributions made by many individuals on behalf of the +Hypersonic SQL Group. + +For work added by the HSQL Development Group (a.k.a. hsqldb_lic.txt): + +Copyright (c) 2001-2005, The HSQL Development Group +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +Neither the name of the HSQL Development Group nor the names of its +contributors may be used to endorse or promote products derived from this +software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +H2 database +----------- + +Multiple-Licensed under the H2 License, Version 1.0, +and under the Eclipse Public License, Version 1.0 +(http://h2database.com/html/license.html). +Initial Developer: H2 Group + +Log4j +----- + +(C) Apache Software Foundation, licensed under the Apache Public License 2.0. + +Apache Commons Logging +---------------------- + +(C) Apache Software Foundation, licensed under the Apache Public License 2.0. + +Jackrabbit-1.0.jar +------------------ + +(C) Apache Software Foundation, licensed under the Apache Public License 2.0. + +Apache Xerces +------------- + +(C) Apache Software Foundation, licensed under the Apache Public License 2.0. + +JUnit 3 +------- + +JUnit 3 is distributed under the terms of the Common Public License 1.0, +http://junit.sourceforge.net/cpl-v10.html + +JUnit is available from http://junit.sourceforge.net/ + + + diff --git a/build.xml b/build.xml index dee04f6..baa39ed 100644 --- a/build.xml +++ b/build.xml @@ -1,246 +1,260 @@ <?xml version="1.0"?> <!-- A rather non-fancy build file. --> <project name="Priha" default="jar"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> <include name="*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> <!-- Jackrabbit is only included if it has been installed with maven --> <fileset dir="${user.home}"> <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> <include name=".m2/repository/commons-collections/**/*3.2.jar"/> <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> </fileset> </path> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> <src path="src/java"/> <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> <src path="tests/java"/> <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> - - <target name="dist" depends="jar,javadoc"> - <java classpath="build" outputproperty="version" classname="org.priha.Release" - args="-versiononly"> - </java> - <zip zipfile="build/priha-${version}.zip"> - <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> - <zipfileset dir="." includes="ChangeLog README doc/**" prefix="priha-${version}"/> - <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> - </zip> - </target> - <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> + + <!-- ***************************************************************** --> + + <!-- + + Distribution package building. + + Use "ant dist" to build the distro package. + + --> + + + <target name="dist" depends="jar,javadoc"> + <java classpath="build" outputproperty="version" classname="org.priha.Release" + args="-versiononly"> + </java> + + <zip zipfile="build/priha-${version}.zip"> + <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> + <zipfileset dir="." includes="ChangeLog README LICENSE NOTICE doc/**" prefix="priha-${version}"/> + <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> + <zipfileset dir="lib" includes="ehcache-*.jar hsqldb-*.jar" prefix="priha-${version}/extras-lib"/> + </zip> + </target> + + </project> diff --git a/lib/mysql-connector-java-5.1.8-bin.jar b/lib/mysql-connector-java-5.1.8-bin.jar deleted file mode 100644 index 5a7c6fb..0000000 Binary files a/lib/mysql-connector-java-5.1.8-bin.jar and /dev/null differ
jalkanen/Priha
e34af24033320c847cd2d3da58d351574bc131ab
Added CheckStyle, and cleaned a number of warnings from the code base.
diff --git a/.checkstyle b/.checkstyle new file mode 100644 index 0000000..2fbba5a --- /dev/null +++ b/.checkstyle @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<fileset-config file-format-version="1.2.0" simple-config="true"> + <local-check-config name="Priha checkstyle configuration" location="internal_config__1261654928515.xml" type="internal" description=""/> + <fileset name="all" enabled="true" check-config-name="Priha checkstyle configuration" local="true"> + <file-match-pattern match-pattern="." include-pattern="true"/> + </fileset> + <filter name="FilesFromPackage" enabled="true"> + <filter-data value="src/java/org/priha/query/aqt"/> + <filter-data value="src/java/org/priha/query/aqt/xpath"/> + <filter-data value="tests/tck"/> + <filter-data value="tests/tck/org"/> + <filter-data value="tests/tck/org/apache"/> + <filter-data value="src/generated-sources"/> + </filter> +</fileset-config> diff --git a/.project b/.project index 22915b3..0b6b75b 100644 --- a/.project +++ b/.project @@ -1,17 +1,23 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>priha</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> + <buildCommand> + <name>com.atlassw.tools.eclipse.checkstyle.CheckstyleBuilder</name> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> + <nature>com.atlassw.tools.eclipse.checkstyle.CheckstyleNature</nature> </natures> </projectDescription> diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 5ad188e..fa1412a 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,12 +1,70 @@ -#Sat Sep 12 00:03:38 EEST 2009 +#Thu Dec 24 13:54:41 EET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=warning org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.5 diff --git a/NOTICE b/NOTICE index b8fd555..98cb300 100644 --- a/NOTICE +++ b/NOTICE @@ -1,7 +1,9 @@ Priha contains code developed and (C) Janne Jalkanen, 2006-2009. The Query Engine contains code developed by the Apache Software Foundation, used under the Apache Public License, v2.0. Contains the JCR TCK developed by the Apache Software Foundation. + +Contains Base64 code from Robert Harder, under Public Domain. diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 3643369..557030d 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,116 +1,124 @@ /* Priha - A JSR-170 implementation library. - Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ -public class Release +public final class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ public static final int MINORREVISION = 4; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; + /** + * Prevent instantiation. + */ + private Release() {} + /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ - public static String[] DESCRIPTORS = { + public static final String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. + * + * @param argv Arguments. Currently allowed argument is "-versiononly", which prints + * just the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/RepositoryManager.java b/src/java/org/priha/RepositoryManager.java index 97b4a63..b2e14aa 100644 --- a/src/java/org/priha/RepositoryManager.java +++ b/src/java/org/priha/RepositoryManager.java @@ -1,159 +1,166 @@ /* Priha - A JSR-170 implementation library. - Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import java.io.IOException; import java.util.Properties; import org.priha.core.RepositoryImpl; import org.priha.util.ConfigurationException; import org.priha.util.FileUtil; /** * This is the main API for getting yourself a Repository object, and as * such, probably the only class you will need outside the basic JCR classes * (unless you want to develop a RepositoryProvider, but that's a whole another story). * <p> * The simplest way of getting yourself a Priha JCR Repository is to simply call * <code>RepositoryManager.getRepository</code>, which will find your "priha.properties" * file and return a ready-to-use repository. This default repository is a singleton. * <p> * Simple basic usage example which stores "some text" to the repository, and * then retrieves and prints it: * <pre> * Repository rep = RepositoryManager.getRepository(); * Session session = rep.login(); * * Node nd = session.getRootNode().addNode("myfirstnode"); * nd.addProperty("myfirstproperty", "some text"); * session.save(); * * Property newp = (Property)session.getItem("/myfirstnode/myfirstproperty"); * System.out.println( newp.getString() ); * </pre> * <p>The workspace you get with Repository.login() depends on the configuration. * It is always the <i>first</i> workspace defined for the first provider that * is on the "priha.providers" line. * */ // TODO: Add JNDI configuration somewhere here -public class RepositoryManager +public final class RepositoryManager { /** * An instance of the default repository. */ - private static RepositoryImpl m_repository = null; + private static RepositoryImpl c_repository; private static final String[] PROPERTYPATHS = { "/priha.properties", "/WEB-INF/priha.properties" }; + /** + * The Priha Namespace. Value is {@value}. + */ public static final String NS_PRIHA = "http://www.priha.org/ns/1.0"; + /** + * Prevent instantiation. + */ + private RepositoryManager() {} + /** * Returns a default repository object for no-pain setup. The Repository * object is shared among all requestors of the default repository. * <p> * This method will search for a "priha.properties" configuration file from * your classpath (and /WEB-INF/) and will use that. Failing to find one, * it will use the internal defaults (from the built-in priha_default.properties), * which almost certainly is not something you want - unless you just want * to test Priha. * - * @return - * @throws ClassNotFoundException - * @throws InstantiationException - * @throws IllegalAccessException + * @return The default repository object.s + * @throws ConfigurationException If there is a problem with the discovered + * preferences. */ public static RepositoryImpl getRepository() throws ConfigurationException { try { - if( m_repository == null ) - m_repository = getRepository( FileUtil.findProperties(PROPERTYPATHS) ); + if( c_repository == null ) + c_repository = getRepository( FileUtil.findProperties(PROPERTYPATHS) ); - return m_repository; + return c_repository; } catch (IOException e) { throw new ConfigurationException("Unable to load property file:"+e.getMessage()); } } /** * Returns a new repository object based on the Properties given. This method * guarantees a new Repository object, so it's a good idea to cache whatever * you get from here. * <p> * Note that if you do get two Repositories who share the same property file, * you will almost certainly hit some nasty race conditions with the repository * itself. So be very, very careful. * - * @param prefs - * @return - * @throws ConfigurationException + * @param prefs A Properties object containing preferences in Priha format. + * @return A new Repository. + * @throws ConfigurationException If the preferences were incorrect in some way. */ public static RepositoryImpl getRepository( Properties prefs ) throws ConfigurationException { return new RepositoryImpl( prefs ); } /** * Returns a new repository object by locating the property file given. This * method also guarantees a new Repository object. * <p> * This class is somewhat lenient in how it searches the property file. It * first tries the name as-is, then it tries to locate the file from the * classpath root, and then it tries to search your WEB-INF library. * * <p> * Note that if you do get two Repositories who share the same property file, * you will almost certainly hit some nasty race conditions with the repository * itself. So be very, very careful. * * @param propertyFilename A name for the property file. * @return A JCR Repository. * @throws ConfigurationException If the repository cannot be configured or the * property file cannot be located. */ public static RepositoryImpl getRepository( String propertyFilename ) throws ConfigurationException { String[] propertyPaths = { propertyFilename, "/"+propertyFilename, "/WEB-INF/propertyFileName" }; try { Properties props = FileUtil.findProperties(propertyPaths); if( props == null || props.isEmpty() ) { throw new ConfigurationException("The defined property file could not be located"); } return new RepositoryImpl(props); } catch (IOException e) { throw new ConfigurationException("Unable to find or read the property file!"); } } } diff --git a/src/java/org/priha/core/ItemImpl.java b/src/java/org/priha/core/ItemImpl.java index 99fd3b8..3917abf 100644 --- a/src/java/org/priha/core/ItemImpl.java +++ b/src/java/org/priha/core/ItemImpl.java @@ -1,363 +1,410 @@ /* Priha - A JSR-170 implementation library. - Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.PathRef; import org.priha.util.*; /** * Provides a basic implementation for Items. An Item stores a reference * to its Path, the Session, and keeps a record of its ItemState. Therefore * it's a fairly lightweight object. */ public abstract class ItemImpl implements Item { protected PathRef m_path; protected final SessionImpl m_session; -// protected ItemState m_state = ItemState.UNDEFINED; - protected boolean m_isNew = false; - -// public ItemImpl( SessionImpl session, String path ) throws NamespaceException, RepositoryException -// { -// this( session, PathFactory.getPath(session,path) ); -// } + protected boolean m_isNew; + /** + * Create an Item for a particular session and path. + * + * @param session Session which owns this Item + * @param path Path at which the Item is created. + */ public ItemImpl(SessionImpl session, Path path) { m_session = session; m_path = session.getPathManager().getPathRef(path); } - public ItemImpl(ItemImpl original, SessionImpl session) - { - this( session, original.getInternalPath() ); - } - + /** + * Returns the path reference object. + * + * @return The internal path reference. + */ public PathRef getPathReference() { if( m_path == null ) throw new RuntimeException("Path reference must not be null!"); return m_path; } + /** + * Return the current state of this Item. + * + * @return An {@link ItemState} representing the state. + */ public ItemState getState() { // // Check if the state exists in the change list. // ItemState state = ItemState.UNDEFINED; try { state = m_session.m_provider.getState( m_path ); } catch( PathNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } // If this object exists, but is not in the change list, then it's just // a simply existing object return state != null ? state : ItemState.EXISTS; } + /** + * Changes the {@link ItemState} of the Item, and places it in the appropriate + * queues. + * + * @param state New state. + * @throws RepositoryException If the state cannot be entered for some reason. + */ @SuppressWarnings("fallthrough") public void enterState( ItemState state ) throws RepositoryException { ItemState oldState = getState(); SessionProvider sp = m_session.m_provider; switch( state ) { case EXISTS: break; case NEW: if( oldState == ItemState.NEW ) break; m_isNew = true; /* FALLTHROUGH OK */ case REMOVED: // FIXME: Slightly hacky, this. if( state == ItemState.REMOVED && oldState == ItemState.REMOVED ) break; case MOVED: // // Additions and removals also affect the parent. // sp.m_changedItems.add( state, this ); if( !getInternalPath().isRoot() && !getParent().isModified() ) { getParent().enterState(ItemState.UPDATED); } break; case UPDATED: if( oldState == ItemState.EXISTS || oldState == ItemState.UNDEFINED ) { // If we're already modified, no use repeating that information sp.m_changedItems.add( state, this ); } break; case UNDEFINED: + default: throw new InvalidItemStateException("State cannot be set to UNDEFINED - that is the starting state of any Item only."); } } + /** + * {@inheritDoc} + */ public void accept(ItemVisitor visitor) throws RepositoryException { if( isNode() ) { visitor.visit( (Node) this ); } else { visitor.visit( (Property) this ); } } + /** + * {@inheritDoc} + */ public Item getAncestor(int depth) throws ItemNotFoundException, AccessDeniedException, RepositoryException { try { Path ancestorPath = getInternalPath().getAncestorPath(depth); return m_session.getItem(ancestorPath); } catch( InvalidPathException e ) { throw new ItemNotFoundException(e.getMessage()); } } + /** + * {@inheritDoc} + */ public int getDepth() throws RepositoryException { return getInternalPath().depth(); } + /** + * {@inheritDoc} + */ public String getName() throws RepositoryException { return m_session.fromQName( getInternalPath().getLastComponent() ); } /** * Returns the QName of this item. * * @return A QName. * @throws NamespaceException If the namespace cannot be parsed. * @throws RepositoryException If something else goes wrong. */ public QName getQName() throws NamespaceException, RepositoryException { QName qname = getInternalPath().getLastComponent(); return qname; } + /** + * {@inheritDoc} + */ public NodeImpl getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException { try { Path parentPath = getInternalPath().getParentPath(); NodeImpl parent = (NodeImpl)m_session.getItem(parentPath); return parent; } catch( InvalidPathException e ) { throw new ItemNotFoundException(e.getMessage()); } } + /** + * Get the internal path representation for this Item. + * + * @return The internal Path. + */ public Path getInternalPath() { try { return m_session.getPath( m_path ); } catch( PathNotFoundException e ) { throw new RuntimeException("Invalid path received: "+m_path,e); } } + /** + * {@inheritDoc} + */ public String getPath() throws RepositoryException { return PathFactory.getMappedPath( m_session, getInternalPath() ); -// return getInternalPath().toString(m_session); } + /** + * {@inheritDoc} + */ public SessionImpl getSession() throws RepositoryException { return m_session; } + /** + * {@inheritDoc} + */ public boolean isModified() { // // An Item is not modified, if it's, well, not modified or it's been recently // added (then it's NEW). // ItemState state = getState(); return state != ItemState.EXISTS && state != ItemState.NEW; } + /** + * {@inheritDoc} + */ public boolean isNew() { return m_isNew || getState() == ItemState.UNDEFINED; } + /** + * {@inheritDoc} + */ public boolean isNode() { return false; } - public boolean isSame(Item otherItem) throws RepositoryException + /** + * {@inheritDoc} + */ + public boolean isSame(Item otherItem) throws RepositoryException { if( m_session.getRepository() == otherItem.getSession().getRepository() ) { if( getPath().equals(otherItem.getPath()) ) { if( isNode() == otherItem.isNode() ) { if( isNode() ) { return true; } else if( getParent().getPath().equals(otherItem.getParent().getPath()) ) { return true; } } } } return false; } + /** + * {@inheritDoc} + */ public void refresh(boolean keepChanges) throws InvalidItemStateException, RepositoryException { if( !m_session.itemExists(getInternalPath()) ) throw new InvalidItemStateException("You cannot refresh an Item which has been deleted!"); if( getState() == ItemState.REMOVED || getState() == ItemState.MOVED ) throw new InvalidItemStateException("Node has been removed"); m_session.refresh( keepChanges, getInternalPath() ); } + /** + * {@inheritDoc} + */ public abstract void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException; + /** + * {@inheritDoc} + */ public abstract void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException ; -// protected abstract void saveItemOnly() throws RepositoryException; + /** + * Returns a human-readable description of the Item. + * + * @return Something readable. + */ + @Override public String toString() { try { return "Node["+m_session.getWorkspace().getName()+":"+getPath()+"]"; } catch( RepositoryException e ) { return "Node["+m_session.getWorkspace().getName()+":"+getInternalPath()+"]"; } } - /** Marks this Node + its parent modified. - * @throws RepositoryException */ -// protected void markModified(boolean isModified) throws RepositoryException -// { -// markModified( isModified, true ); -// } -// -// protected void markModified(boolean isModified, boolean parentToo) throws RepositoryException -// { -// if( m_state == ItemState.EXISTS ) m_state = ItemState.UPDATED; -// -// m_session.markDirty(this); -// -// if( !getInternalPath().isRoot() && parentToo ) -// { -// // -// // Regardless of the state of the current Item, the parent -// // shall always be marked as modified (since the state of this -// // child has changed.) -// // -// NodeImpl parent = getParent(); -// parent.markModified(true, false); -// } -// } - + /** + * {@inheritDoc} + */ @Override public int hashCode() { return getInternalPath().hashCode()-17; } /** * Performs mandatory housekeeping right before saving. - * @throws RepositoryException + * @throws RepositoryException If something goes wrong */ protected void preSave() throws RepositoryException { if( getState() == ItemState.UNDEFINED ) { throw new IllegalStateException("Node "+getInternalPath()+" must not be in UNDEFINED state at this point (this is a bug in Priha, please report!)"); } } /** * Performs mandatory housekeeping after item state has been persisted to disk. * */ protected void postSave() { m_isNew = false; } private transient long m_creationTime = System.currentTimeMillis(); + /** + * Returns the creation time of this Item instance. + * + * @return The creation time. + */ public long getCreationTime() { return m_creationTime; } } diff --git a/src/java/org/priha/core/ItemState.java b/src/java/org/priha/core/ItemState.java index b0f7080..fbf1fce 100644 --- a/src/java/org/priha/core/ItemState.java +++ b/src/java/org/priha/core/ItemState.java @@ -1,37 +1,37 @@ /* Priha - A JSR-170 implementation library. - Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; /** * The ItemState enumeration tracks the state of a Node. * <ul> * <li>NEW = The Item is new, and has never been saved. * <li>EXISTS = Item was loaded from the repository and has not been changed. * <li>REMOVED = Item has been removed and cannot be addressed any more. * <li>MOVED = Item was moved * </ul> */ public enum ItemState { NEW, EXISTS, REMOVED, MOVED, UPDATED, UNDEFINED -} \ No newline at end of file +} diff --git a/src/java/org/priha/core/ItemStore.java b/src/java/org/priha/core/ItemStore.java index 11d1929..2be436d 100644 --- a/src/java/org/priha/core/ItemStore.java +++ b/src/java/org/priha/core/ItemStore.java @@ -1,81 +1,79 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.util.Collection; import java.util.List; import javax.jcr.Credentials; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.RepositoryException; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.providers.StoreTransaction; import org.priha.providers.ValueContainer; import org.priha.util.QName; public interface ItemStore { void open(Credentials credentials, String workspaceName) throws NoSuchWorkspaceException, RepositoryException; void stop(); void close(WorkspaceImpl ws); void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException; NodeImpl findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException; ItemImpl getItem(WorkspaceImpl ws, Path path) throws InvalidPathException, RepositoryException; List<? extends Path> listNodes(WorkspaceImpl m_workspace, Path parentpath) throws RepositoryException; Collection<? extends String> listWorkspaces() throws RepositoryException; boolean nodeExists(WorkspaceImpl m_workspace, Path path) throws RepositoryException; void remove(StoreTransaction tx, Path path) throws RepositoryException; void addNode(StoreTransaction tx, NodeImpl ni) throws RepositoryException; void putProperty(StoreTransaction tx, Path path, ValueContainer value) throws RepositoryException; /** * Locate all properties of type REFERENCE with the content of the particular UUID. * * @param m_workspace * @param uuid * @return * @throws RepositoryException */ Collection<? extends PropertyImpl> getReferences(WorkspaceImpl w, String uuid) throws RepositoryException; List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException; public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException; public void storeFinished(StoreTransaction tx) throws RepositoryException; public void storeCancelled(StoreTransaction tx) throws RepositoryException; void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException; - - void rename(StoreTransaction tx,Path path, Path.Component newName) throws RepositoryException; } diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index c9b76bb..b84049f 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,631 +1,614 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; import org.priha.core.locks.LockManager; import org.priha.core.locks.QLock; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.util.LazyNodeIteratorImpl; import org.priha.util.PropertyIteratorImpl; import org.priha.util.QName; import org.priha.util.TextUtil; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; /** * Implements a Node. This is one of the most heavy classes in Priha, with a lot * of stuff happening. The NodeImpl class does some basic caching for some state * objects, so keeping references can be faster in some cases. */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; /** * A compile-time flag for allowing/disallowing Same Name Sibling support. * addNode() will throw an exception if you disallow these. This is sometimes * useful for debugging. */ private static final boolean ALLOW_SNS = true; private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); - - /** - * Creates a clone of the NodeImpl, and places it to the given Session - * - * @param original - * @param session - * @throws RepositoryException - * @throws IllegalStateException - * @throws ValueFormatException - */ - protected NodeImpl( NodeImpl original, SessionImpl session ) throws ValueFormatException, IllegalStateException, RepositoryException - { - super( original, session ); - m_primaryType = original.m_primaryType; - m_definition = original.m_definition; - } - protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { enterState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.enterState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.enterState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public PropertyIteratorImpl getProperties() throws RepositoryException { List<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( m_session.m_provider.getProperties(getInternalPath()) ); return new PropertyIteratorImpl( ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); diff --git a/src/java/org/priha/core/ProviderManager.java b/src/java/org/priha/core/ProviderManager.java index 2e42f9b..b2b2152 100644 --- a/src/java/org/priha/core/ProviderManager.java +++ b/src/java/org/priha/core/ProviderManager.java @@ -159,529 +159,513 @@ public class ProviderManager implements ItemStore * the property set for a provider. * <p> * Essentially returns a property set where all instances of * <code>priha.provider.[providerName].property = value</code> * are replaced with <code>property = value</code>. * * @param repository The repository from which the properties are read * @param providerName The name to filter with * @return A valid set of Properties. It can also be empty, if there * were no properties defined for this providerName. * @see ProviderManager#instantiateProvider(RepositoryImpl, String, Properties) */ public static Properties filterProperties( RepositoryImpl repository, String providerName ) { Properties props = new Properties(); String prefix = PROP_PRIHA_PROVIDER_PREFIX + providerName + "."; for( Enumeration<String> e = repository.getPropertyNames(); e.hasMoreElements(); ) { String key = e.nextElement(); if( key.startsWith(prefix) ) { String val = repository.getProperty(key); key = key.substring(prefix.length()); props.setProperty(key, val); } } return props; } /** * Instantiates a RepositoryProvider using the given class name and * the properties, and calls its start() method. * * @param rep The RepositoryImpl who will own this RepositoryProvider * @param className The FQN of the class. * @param props A filtered set of Properties * @return A started RepositoryProvider. * * @throws ConfigurationException If the provider cannot be instantiated or the configuration * is faulty. * * @see ProviderManager#filterProperties(RepositoryImpl, String) */ public static RepositoryProvider instantiateProvider(RepositoryImpl rep, String className, Properties props) throws ConfigurationException { Class<?> cl; RepositoryProvider provider; try { cl = Class.forName( className ); provider = (RepositoryProvider) cl.newInstance(); provider.start( rep, props ); } catch (ClassNotFoundException e) { throw new ConfigurationException("Could not find provider class",className); } catch (InstantiationException e) { throw new ConfigurationException("Could not instantiate provider class",className); } catch (IllegalAccessException e) { throw new ConfigurationException("Could not access provider class",className); } return provider; } public void open(Credentials credentials, String workspaceName) throws NoSuchWorkspaceException, RepositoryException { ProviderInfo pi = m_workspaceAccess.get(workspaceName); if( pi == null ) throw new NoSuchWorkspaceException("No such workspace: '"+workspaceName+"'"); try { pi.lock.writeLock().lock(); pi.provider.open( m_repository, credentials, workspaceName ); } finally { pi.lock.writeLock().unlock(); } } private ValueContainer getPropertyValue(WorkspaceImpl impl, Path ptPath) throws RepositoryException { ProviderInfo pi = getProviderInfo(impl,ptPath); try { pi.lock.readLock().lock(); ValueContainer stored = pi.provider.getPropertyValue( impl, ptPath ); return stored; } finally { pi.lock.readLock().unlock(); } } /** * Returns the set of workspaces declared in the config file. * * @throws ConfigurationException */ public Collection<String> listWorkspaces() throws ConfigurationException { return m_workspaceAccess.keySet(); } public List<Path>listNodes(WorkspaceImpl impl, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( impl, path ); try { pi.lock.readLock().lock(); return pi.provider.listNodes( impl, path ); } finally { pi.lock.readLock().unlock(); } } public void close(WorkspaceImpl impl) { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.close( impl ); } finally { pi.lock.writeLock().unlock(); } } } /** * Removes the item at the end of the path. * * @param impl * @param path * @throws RepositoryException */ public void remove(StoreTransaction tx, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); try { pi.lock.writeLock().lock(); pi.provider.remove( tx, path ); } finally { pi.lock.writeLock().unlock(); } } /** * Loads the state of a node from the repository. * * @param ws TODO * @param path * @return A brand new NodeImpl. * * @throws RepositoryException */ public NodeImpl loadNode( WorkspaceImpl ws, Path path ) throws RepositoryException { NodeImpl ni = null; Path ptPath = path.resolve( JCRConstants.Q_JCR_PRIMARYTYPE ); PropertyImpl primaryType = ws.createPropertyImpl( ptPath ); ValueContainer v = getPropertyValue( ws, ptPath ); if( v == null ) throw new RepositoryException("Repository did not return a primary type for path "+path); primaryType.loadValue( v.getValue() ); QName pt = ((QNameValue.Impl)v.getValue()).getQValue().getValue(); QNodeTypeManager ntm = QNodeTypeManager.getInstance(); QNodeType type = ntm.getNodeType( pt ); QNodeDefinition nd = type.findNodeDefinition( pt ); ni = ws.getSession().createNode( path, type, nd, false ); return ni; } /** * LOad the state of a single property from the repository. * * @param ws * @param ni * @param ptPath * @param name * @return * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private PropertyImpl loadProperty(WorkspaceImpl ws, NodeImpl ni, Path ptPath, QName name) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueContainer values = getPropertyValue( ws, ptPath ); PropertyImpl p = ws.createPropertyImpl( ptPath ); // // Find the proper property definition. // QPropertyDefinition pd = ni.getPrimaryQNodeType().findPropertyDefinition(name,values.isMultiple()); if( pd == null ) { for( NodeType mixin : ni.getMixinNodeTypes() ) { pd = ((QNodeType.Impl)mixin).getQNodeType().findPropertyDefinition( name, values.isMultiple() ); if( pd != null ) break; } if( pd == null ) throw new RepositoryException("Unable to locate property definition for nodetype "+ni.getPrimaryNodeType()+", name="+name); } p.setDefinition( pd.new Impl(ws.getSession()) ); // FIXME: Inoptimal if( values.isMultiple() ) p.loadValue( values.getValues(), values.getType() ); else p.loadValue( values.getValue() ); return p; } public void addNode(StoreTransaction tx, NodeImpl ni) throws RepositoryException { Path path = ni.getInternalPath(); if( !path.isRoot() && !nodeExists(tx.getWorkspace(), path.getParentPath()) ) throw new ConstraintViolationException("Parent path is missing for path "+path); ProviderInfo pi = getProviderInfo(tx.getWorkspace(),path); try { pi.lock.writeLock().lock(); pi.provider.addNode(tx, path, ni.getQDefinition()); } finally { pi.lock.writeLock().unlock(); } } public void copy(WorkspaceImpl m_workspace, Path srcpath, Path destpath) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } public NodeImpl findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); Path path = pi.provider.findByUUID(ws, uuid); return loadNode(ws, path); } catch(ItemNotFoundException e) {} finally { pi.lock.readLock().unlock(); } } throw new ItemNotFoundException("Could not locate a node by this UUID"); } public ItemImpl getItem(WorkspaceImpl ws, Path path) throws InvalidPathException, RepositoryException { try { NodeImpl ni = loadNode( ws, path ); return ni; } catch( RepositoryException e ) { if( path.isRoot() ) throw e; // Otherwise we just get a relatively unclear "root has no parent" NodeImpl ni = loadNode( ws, path.getParentPath() ); return loadProperty( ws, ni, path, path.getLastComponent() ); } } public boolean nodeExists(WorkspaceImpl ws, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.nodeExists(ws, path); } finally { pi.lock.readLock().unlock(); } } public void putProperty(StoreTransaction tx, Path path, ValueContainer value ) throws RepositoryException { ProviderInfo pi = getProviderInfo( tx.getWorkspace(), path ); ValueContainer vc = value.deepClone(tx.getWorkspace().getSession()); try { pi.lock.writeLock().lock(); pi.provider.putPropertyValue( tx, path, vc ); } finally { pi.lock.writeLock().unlock(); } } public void stop() { for( ProviderInfo pi : m_providers ) { try { pi.lock.writeLock().lock(); pi.provider.stop(m_repository); } finally { pi.lock.writeLock().unlock(); } } } public Collection<? extends PropertyImpl> getReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { ArrayList<PropertyImpl> result = new ArrayList<PropertyImpl>(); List<Path> paths = new ArrayList<Path>(); for( ProviderInfo pi : m_providers ) { try { pi.lock.readLock().lock(); paths.addAll(pi.provider.findReferences( ws, uuid )); } finally { pi.lock.readLock().unlock(); } } for( Path path : paths ) { NodeImpl nd = loadNode( ws, path.getParentPath() ); result.add( nd.getProperty(ws.getSession().fromQName(path.getLastComponent())) ); } return result; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { ProviderInfo pi = getProviderInfo( ws, path ); try { pi.lock.readLock().lock(); return pi.provider.listProperties(ws, path); } finally { pi.lock.readLock().unlock(); } } public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( ws.getName() ); try { pi.lock.writeLock().lock(); return pi.provider.storeStarted( ws ); } finally { pi.lock.writeLock().unlock(); } } public void storeFinished(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeFinished( tx ); } finally { pi.lock.writeLock().unlock(); } } public void storeCancelled(StoreTransaction tx) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.storeCancelled( tx ); } finally { pi.lock.writeLock().unlock(); } } /** * Stores information about a provider. */ private class ProviderInfo { public String[] workspaces; public RepositoryProvider provider; public ReadWriteLock lock; } /** * Returns the name of the default workspace. This is usually "default", but * it may change depending on how you configure Priha. * * @return */ public String getDefaultWorkspace() { return m_defaultWorkspaceName; } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException { ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); try { pi.lock.writeLock().lock(); pi.provider.reorderNodes( tx, internalPath, childOrder ); } finally { pi.lock.writeLock().unlock(); } } - - public void rename(StoreTransaction tx,Path path, Path.Component newName) throws RepositoryException - { - ProviderInfo pi = m_workspaceAccess.get( tx.getWorkspace().getName() ); - - try - { - pi.lock.writeLock().lock(); - - pi.provider.rename( tx, path, newName ); - } - finally - { - pi.lock.writeLock().unlock(); - } - } } diff --git a/src/java/org/priha/path/PathFactory.java b/src/java/org/priha/path/PathFactory.java index 9c0162a..ed33feb 100644 --- a/src/java/org/priha/path/PathFactory.java +++ b/src/java/org/priha/path/PathFactory.java @@ -1,113 +1,111 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.path; import java.lang.ref.WeakReference; import java.util.WeakHashMap; import javax.jcr.NamespaceException; import javax.jcr.RepositoryException; import org.priha.core.namespace.NamespaceMapper; /** * Gets Paths from a local storage. * <p> * If you possibly can, you should use PathFactory to get yourself a Path object. This * factory class stores the Paths in a WeakHashMap, and is always guaranteed to give * you a good Path object. In most cases, this is a lot faster than calling the regular * {@link Path#Path(String)} constructor, since path parsing can take quite a bit of * time. */ public class PathFactory { private static WeakHashMap<String,WeakReference<Path>> c_map = new WeakHashMap<String,WeakReference<Path>>(128); private static WeakHashMap<Path,String> c_reverseMap = new WeakHashMap<Path,String>(128); /** * This method clears up the PathFactory cache maps. It is mandatory that this * method is called every time when you change namespace mappings, otherwise the results * of getPath() might no longer be correct. */ public static void reset() { c_map.clear(); c_reverseMap.clear(); } /** * Turns a String to a Path. * * @param path A String representing the Path * @return A valid Path object. - * @throws RepositoryException - * @throws NamespaceException + * @throws RepositoryException If there is a problem parsing the Path + * @throws NamespaceException If the Path contains a prefix which could not be parsed. */ public static Path getPath(NamespaceMapper ns, String path) throws NamespaceException, RepositoryException { Path result = null; WeakReference<Path> ref = c_map.get(path); if( ref != null ) { result = ref.get(); } if( result == null ) { result = new Path(ns,path); c_map.put( path, new WeakReference<Path>(result) ); c_reverseMap.put( result, path ); } return result; } public static String getMappedPath(NamespaceMapper ns, Path path) throws NamespaceException, RepositoryException { // String p = c_reverseMap.get( path ); String p = null; if( p == null ) { p = path.toString(ns); c_reverseMap.put( path, p ); c_map.put( p, new WeakReference<Path>(path) ); } return p; } /** * Turns a FQN-representation of a Path into a real Path. * * @param property * @return - * @throws NamespaceException, RepositoryException - * @throws * @throws NamespaceException */ public static Path getPath(String property) throws NamespaceException, RepositoryException { Path p = new Path(null,property); return p; } } diff --git a/src/java/org/priha/providers/EhCachingProvider.java b/src/java/org/priha/providers/EhCachingProvider.java index 9105138..a4712d5 100644 --- a/src/java/org/priha/providers/EhCachingProvider.java +++ b/src/java/org/priha/providers/EhCachingProvider.java @@ -1,481 +1,473 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import javax.jcr.*; import javax.management.MBeanServer; import net.sf.ehcache.*; import net.sf.ehcache.constructs.blocking.LockTimeoutException; import net.sf.ehcache.management.ManagementService; import org.priha.core.PropertyImpl; import org.priha.core.ProviderManager; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.core.values.StreamValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.Path; import org.priha.path.Path.Component; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * Uses EHCache for an intermediate level cache. It lies on top of a real provider, * like FileProvider, and provides caching for most of the items that can be fetched * from the cache. Configurable properties are: * <ul> * <li><b>realProvider</b> - The nickname of the underlying provider to use.</li> * <li><b>cacheName</b> - A name for the cache under which it gets registered to * the EHCache CacheManager. If a cache by this name already * exists (e.g. from the ehcache configuration XML file), * it will be used. If it does not exist, we create one.</li> * <li><b>size</b> - The size of the cache (in items; default is 5000)</li> * <li><b>maxSize</b> - The maximum size of the objects which are cached. Default is 10 kB. * </ul> * Priha creates a memory only cache. */ public class EhCachingProvider implements RepositoryProvider { private static final int DEFAULT_CACHESIZE = 5000; private static final String DEFAULT_CACHENAME = "priha.ehCache"; private static final long DEFAULT_MINCACHEABLESIZE = 10*1024; public static final String PROP_MAXCACHEABLESIZE = "maxSize"; public static final String PROP_SIZE = "size"; public static final String PROP_CACHENAME = "cacheName"; public static final String PROP_REALPROVIDER = "realProvider"; private Logger log = Logger.getLogger(EhCachingProvider.class.getName()); private CacheManager m_cacheManager; private Ehcache m_valueCache; private RepositoryProvider m_realProvider; private long m_maxCacheableSize = DEFAULT_MINCACHEABLESIZE; public EhCachingProvider() { } public void start(RepositoryImpl repository, Properties properties) throws ConfigurationException { m_cacheManager = CacheManager.getInstance(); String realProviderNick = properties.getProperty(PROP_REALPROVIDER); Properties props = ProviderManager.filterProperties(repository, realProviderNick); String className = props.getProperty("class"); String workspaceList = properties.getProperty("workspaces"); if( workspaceList != null ) props.setProperty("workspaces", workspaceList); m_realProvider = ProviderManager.instantiateProvider(repository, className, props); String cacheName = props.getProperty(PROP_CACHENAME, DEFAULT_CACHENAME); int size = Integer.parseInt( props.getProperty(PROP_SIZE, Integer.toString(DEFAULT_CACHESIZE) ) ); // Since we store multiple objects per a single cache item (UUIDs/etc), we double the size // of the cache here. size = size * 2; m_maxCacheableSize = Long.parseLong( props.getProperty(PROP_MAXCACHEABLESIZE, Long.toString( DEFAULT_MINCACHEABLESIZE ) ) ); Ehcache myCache = m_cacheManager.getEhcache( cacheName ); if( myCache == null ) { myCache = new Cache(cacheName, size, false, true, 30, 20); // // For some completely unfathomable reason, the BlockingCache blocks // on the same thread every 5-10 calls to getPropertyValue() on OSX 10.4, // both Java5 and Java6. So until I figure out what is going on, // we can't use it :-( // // myCache = new BlockingCache(myCache)); // // ((BlockingCache)myCache).setTimeoutMillis( 10*1000 ); m_cacheManager.addCache(myCache); } m_valueCache = m_cacheManager.getEhcache( cacheName ); // // Register to MBeanServer // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); try { ManagementService.registerMBeans(m_cacheManager, mBeanServer, false, false, false, true); } catch( CacheException e ) { // Failure is not fatal. } log.fine("Started EHCache with real provider class "+m_realProvider.getClass().getName()); } public void stop(RepositoryImpl rep) { m_realProvider.stop(rep); m_cacheManager.shutdown(); log.fine("Stopped EHCache"); } /** * Gives an unique ID with which to use as the cache key for Values. * * @param ws * @param path * @return */ private final String getVid(WorkspaceImpl ws, Path path) { return ws.getName()+";"+path.toString()+";V"; } /** For the Property name lists */ private final String getPid(WorkspaceImpl ws, Path path) { return ws.getName()+";"+path.toString()+";P"; } /** For the Node child lists */ private final String getNid(WorkspaceImpl ws, Path path) { return ws.getName()+";"+path.toString()+";N"; } /** For UUIDs */ private final String getUid(WorkspaceImpl ws, String uuid) { return ws.getName()+";"+uuid; // UUIDs are unique enough } /** For Reverse UUIDs */ private final String getRUid(WorkspaceImpl ws, Path path ) { return ws.getName()+";"+path.toString()+";U"; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_realProvider.open(rep, credentials, workspaceName); } public void close(WorkspaceImpl ws) { if( m_valueCache.getStatus() == Status.STATUS_ALIVE ) { Statistics s = m_valueCache.getStatistics(); log.fine("EHCache statistics right before close(): "+s.toString()); m_valueCache.removeAll(); } m_realProvider.close(ws); } public void addNode(StoreTransaction tx, Path path, QNodeDefinition def) throws RepositoryException { if( !path.isRoot() ) m_valueCache.remove( getNid(tx.getWorkspace(),path.getParentPath()) ); m_realProvider.addNode(tx, path,def); } /* public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_realProvider.copy(ws, srcpath, destpath); } */ /* * UUIDs are fairly safe because even if the Node was deleted, SessionImpl will * attempt to fetch the Node itself based on the Path, so that will fail then. * So we can just cache all the values happily. * * Also, the mappings don't really change, except in a move() operation. * * (non-Javadoc) * @see org.priha.providers.RepositoryProvider#findByUUID(org.priha.core.WorkspaceImpl, java.lang.String) */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { try { Element e = m_valueCache.get( getUid( ws, uuid ) ); if( e != null ) { return (Path)e.getObjectValue(); } Path p = m_realProvider.findByUUID(ws, uuid); m_valueCache.put( new Element( getUid( ws, uuid ), p ) ); m_valueCache.put( new Element( getRUid( ws, p ), uuid ) ); return p; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout getting propery value"); } catch( RuntimeException e ) { // Release lock m_valueCache.put( new Element( getUid( ws, uuid ), null ) ); throw new RepositoryException("Error getting property value"); } } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { return m_realProvider.findReferences(ws, uuid); } // // Binary objects are not cached, unless they are smaller than the max cacheable size. // private boolean isCacheable(ValueContainer o) throws ValueFormatException { if( o.getType() == PropertyType.BINARY ) { if( !o.isMultiple() && o.getValue() instanceof StreamValueImpl ) { StreamValueImpl svi = (StreamValueImpl)o.getValue(); try { return svi.getLength() <= m_maxCacheableSize; } catch( IOException e ) {} // Fine, can be ignored. } return false; } return true; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { String key = getVid(ws,path); try { Element e = m_valueCache.get( key ); if( e != null ) { ValueContainer o = (ValueContainer)e.getObjectValue(); // // If this is a mapped instance, then we'll actually return // a new copy of it for this particular Session. // // FIXME: Optimize by checking the Session, if this comes from the same one, no need to clone. // return o.sessionInstance( ws.getSession() ); } ValueContainer o = m_realProvider.getPropertyValue(ws, path); if( isCacheable(o) ) { e = new Element( key, o ); m_valueCache.put( e ); } return o; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout getting propery value",e); } catch( RuntimeException e ) { throw new RepositoryException("Error getting propery value",e); } } @SuppressWarnings("unchecked") public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws RepositoryException { try { Element e = m_valueCache.get( getNid(ws,parentpath) ); if( e != null ) return (List<Path>)e.getValue(); List<Path> list = m_realProvider.listNodes(ws, parentpath); e = new Element( getNid(ws,parentpath), list ); m_valueCache.put( e ); return list; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout getting propery value"); } catch( RuntimeException e ) { // Release lock m_valueCache.put( new Element(getNid(ws,parentpath),null) ); throw new RepositoryException("Error getting propery value", e); } } @SuppressWarnings("unchecked") public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { try { Element e = m_valueCache.get( getPid(ws,path) ); if( e != null ) return (List<QName>)e.getValue(); List<QName> list = m_realProvider.listProperties(ws, path); e = new Element( getPid(ws,path), list ); m_valueCache.put( e ); return list; } catch( LockTimeoutException e ) { throw new RepositoryException("Lock timeout listing properties"); } catch( RuntimeException e ) { // Release lock m_valueCache.put( new Element(getPid(ws,path),null) ); throw new RepositoryException("Error listing properties"); } } public Collection<String> listWorkspaces() throws RepositoryException { return m_realProvider.listWorkspaces(); } /* public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { // // We need to make sure UUID mapping is still okay. // Element e = m_valueCache.get( getRUid(ws,srcpath) ); if( e != null ) { String uuid = (String)e.getValue(); m_valueCache.remove( uuid ); m_valueCache.remove( getRUid(ws,srcpath) ); } m_realProvider.move(ws, srcpath, destpath); } */ public boolean nodeExists(WorkspaceImpl ws, Path path) throws RepositoryException { if( m_valueCache.isKeyInCache( getNid(ws,path) ) ) return true; return m_realProvider.nodeExists(ws, path); } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc ) throws RepositoryException { WorkspaceImpl ws = tx.getWorkspace(); m_valueCache.remove( getVid(ws,path ) ); m_realProvider.putPropertyValue(tx, path, vc); if( isCacheable( vc ) ) { Element e = new Element( getVid( ws, path ), vc ); m_valueCache.put( e ); } } public void remove(StoreTransaction tx, Path path) throws RepositoryException { m_realProvider.remove(tx,path); WorkspaceImpl ws = tx.getWorkspace(); m_valueCache.remove( getVid(ws,path) ); m_valueCache.remove( getPid(ws,path) ); m_valueCache.remove( getNid(ws,path) ); if( !path.isRoot() ) m_valueCache.remove( getNid(ws,path.getParentPath()) ); } public void storeFinished( StoreTransaction tx ) throws RepositoryException { m_realProvider.storeFinished( tx ); } public void storeCancelled( StoreTransaction tx ) throws RepositoryException { m_realProvider.storeCancelled( tx ); // Something fairly hairy happened, so we hedge our bets by emptying the cache // completely. m_valueCache.removeAll(); } public StoreTransaction storeStarted( WorkspaceImpl ws ) throws RepositoryException { return m_realProvider.storeStarted( ws ); } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) throws RepositoryException { m_realProvider.reorderNodes(tx, internalPath, childOrder); } - - public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException - { - m_realProvider.rename(tx, path, newName); - m_valueCache.remove( getNid(tx.getWorkspace(),path) ); - m_valueCache.remove( getPid(tx.getWorkspace(),path) ); - m_valueCache.remove( getVid(tx.getWorkspace(),path) ); - } } diff --git a/src/java/org/priha/providers/RepositoryProvider.java b/src/java/org/priha/providers/RepositoryProvider.java index cc1d7ba..4cea78c 100644 --- a/src/java/org/priha/providers/RepositoryProvider.java +++ b/src/java/org/priha/providers/RepositoryProvider.java @@ -1,287 +1,263 @@ /* Priha - A JSR-170 implementation library. - Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import java.util.Collection; import java.util.List; import java.util.Properties; import javax.jcr.*; -import javax.jcr.nodetype.NodeDefinition; -import org.priha.core.PropertyImpl; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.Path; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * A few ground rules: * <ul> * <li>A RepositoryProvider shall not cache the Session object</li> * <li>A RepositoryProvider shall be thread-safe</li> * <li>There shall always be a default workspace called "default"</li> * </ul> * <p> * Priha RepositoryManager ensures that methods which modify the repository * (addNode(), close(), copy(), move(), open(), putPropertyValue(), remove(), * start(), stop(), storeFinished(), storeStarted()) are single-threaded. * However, the rest of the methods which are supposed to read from the * repository, are protected by a read lock, and therefore they can be * accessed at the same time from multiple threads. If you do any modifications * anywhere, make sure these are thread-safe. * <p> * The RepositoryProvider lifecycle is as follows. * <ol> * <li>When Priha first starts up and parses its configuration, it locates each * RepositoryProvider from the configuration, and calls its <code>start()</code> * method to notify that it exists.</li> * <li>Once the user then grabs a Session object, the RepositoryProvider is * notified via the <code>open()</code> method.</li> * <li>The user now uses all of the other methods from the repo.</li> * <li>Once the user chooses to logout, then the <code>close()</code> method * is called.</li> * <li>Then, finally, when Priha closes down, the <code>stop()</code> method * will be called. Priha installs its own shutdown hook for this case.</li> * </ol> */ public interface RepositoryProvider { // // REPOSITORY MANAGEMENT // /** * Opens a repository. Called whenever a session login() is performed. * * @param rep The Repository which owns this Provider. * @param credentials The Credentials object passed to the Session.open() call. May be null, * if there were no credentials. * @param workspaceName The workspace which will be accessed. - * @throws NoSuchWorkspaceException, if no such workspace exists. + * @throws NoSuchWorkspaceException if no such workspace exists. */ public void open( RepositoryImpl rep, Credentials credentials, String workspaceName ) throws RepositoryException, NoSuchWorkspaceException; /** * Starts access to a repository. This is called only once per * RepositoryProvider lifecycle. * * @param repository The Repository which owns this provider. * @param properties A set of filtered properties for this provider. * @throws ConfigurationException If the repository cannot be started due to a faulty configuration. * * @see org.priha.core.ProviderManager#filterProperties(RepositoryImpl, String) */ public void start( RepositoryImpl repository, Properties properties ) throws ConfigurationException; /** * Stops a given repository. This may be called without a preceding call * to close(). All allocated resources can now be deallocated. * <p> * This method will only be called when the Repository shuts down. * * @param rep The Repository object. */ public void stop( RepositoryImpl rep ); /** * The repository will no longer be used by a session, so any session-specific * things can now be deallocated. * * @param ws The Workspace attached to the Session. */ public void close( WorkspaceImpl ws ); /** * Lists all workspaces which are available in this Repository. This method is * called after start() but before open(). * * @return The workspace names. * @throws RepositoryException */ public Collection<String> listWorkspaces() throws RepositoryException; // // GETTING NODES AND VALUES // /** * Returns a list of properties for a Node. * * @param ws The Workspace in which the properties should be located. * @param path The path of the Node. * @return A List of the names of the properties under this Node. * @throws PathNotFoundException If the path given does not exist. * @throws RepositoryException If something goes wrong. */ public abstract List<QName> listProperties( WorkspaceImpl ws, Path path ) throws PathNotFoundException, RepositoryException; /** * Returns the value of a property. * * @param ws The workspace in which the property value should be located. * @param path The path to the Property * @return Either a ValueImpl or ValueImpl[], depending on whether this is a multi-valued thing * @throws RepositoryException If something goes wrong. * @throws PathNotFoundException If there is nothing at the end of this Path, i.e. the object could not be found. */ public abstract ValueContainer getPropertyValue( WorkspaceImpl ws, Path path ) throws PathNotFoundException, RepositoryException; /** * Returns true, if the Node exists. * * @param ws The workspace in which the existence of the Node is checked. * @param path The path to the Node. * @return True, if the node exists. False otherwise (like when it's actually a Property) * @throws RepositoryException */ public boolean nodeExists( WorkspaceImpl ws, Path path ) throws RepositoryException; - /** - * Copies content from one path to another path. - * - * @param ws - * @param srcpath - * @param destpath - * @throws RepositoryException - */ -// public void copy( WorkspaceImpl ws, Path srcpath, Path destpath ) throws RepositoryException; - - /** - * Moves the content at the end of one Path to the destpath. - * - * @param ws - * @param srcpath - * @param destpath - * @throws RepositoryException - */ -// public void move( WorkspaceImpl ws, Path srcpath, Path destpath ) throws RepositoryException; - /** * Lists all the Nodes from the repository which belong to this parent. * * @param ws The Workspace. * @param parentpath The path to the Node whose children should be listed. * @return A List of Path objects with the <i>full</i> paths to the children. * @throws RepositoryException If the children cannot be found. */ public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws RepositoryException; /** * If an item by this UUID exists, returns a Path. * * @param ws * @param uuid * @return * @throws ItemNotFoundException If the repository does not contain an UUID by this name. */ public Path findByUUID( WorkspaceImpl ws, String uuid ) throws ItemNotFoundException, RepositoryException; /** * Finds all the Property paths which are of type REFERENCE and whose content * is equal to the UUID given. * * @param ws * @param uuid * @return A list of paths to properties which reference the node by the given UUID. * @throws RepositoryException */ public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException; // // METHODS WHICH CHANGE THE REPOSITORY CONTENT // /** * Adds a new Node to the repository to the given Path. The properties of the * Node will be stored separately using successive putPropertyValue() calls. * This includes also system things like the jcr:primaryType, so this method * really exists just to ensure that the Node can be added to the repository. * * @param ws The workspace. * @param path Path to the node in this workspace. * @paran definition The definition of the Node which will be added. The provider * may use this to optimize for particular types. * @throws RepositoryException If the Node cannot be added. */ public void addNode( StoreTransaction tx, Path path, QNodeDefinition definition ) throws RepositoryException; /** * Sets or adds a new Property to the repository. Note that * a Property may be multi-valued. It is up to the provider to * decide how it serializes the data. * * @param ws The workspace * @param property The Property content to store. * @throws RepositoryException If the property cannot be stored. */ public void putPropertyValue( StoreTransaction tx, Path path, ValueContainer property ) throws RepositoryException; /** * Removes a node or a property from the repository. If the removed * entity is a Node, all of its children and properties MUST also be removed * from the repository. * <p> * In addition, it MUST NOT be an error if remove() is called on a path * which is already removed. In such a case, remove() shall fail silently. * * @param ws * @param path */ public void remove( StoreTransaction tx, Path path ) throws RepositoryException; /** * This method is called whenever Priha starts a transaction which will save the * contents of the repository. You could, for example, use this to start a transaction. * * @param ws The workspace * @return An arbitrary StoreTransaction object. May be null. */ public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException; /** * This method is called when the repository-changing operation is complete. For example, * you could close the transaction at this stage. * @param tx The same StoreTransaction object which was returned from storeStarted(). */ public void storeFinished(StoreTransaction tx) throws RepositoryException; /** * If the store has been cancelled and changes need to be rolled back. A RepositoryProvider * should use this opportunity to make sure it is in a consistent state. * * @param tx The transaction from storeStarted(). */ public void storeCancelled(StoreTransaction tx) throws RepositoryException; public void reorderNodes(StoreTransaction tx, Path path, List<Path> childOrder) throws RepositoryException; - - public void rename(StoreTransaction tx, Path path, Path.Component newName ) throws RepositoryException; } diff --git a/src/java/org/priha/util/Base64.java b/src/java/org/priha/util/Base64.java index e36391f..3e53245 100644 --- a/src/java/org/priha/util/Base64.java +++ b/src/java/org/priha/util/Base64.java @@ -1,1829 +1,2026 @@ /* Priha - A JSR-170 implementation library. - Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) + Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.util; - /** - * <p>Encodes and decodes to and from Base64 notation.</p> - * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> - * - * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass - * several pieces of information to the encoder. In the "higher level" methods such as - * encodeBytes( bytes, options ) the options parameter can be used to indicate such - * things as first gzipping the bytes before encoding them, not inserting linefeeds - * (though that breaks strict Base64 compatibility), and encoding using the URL-safe - * and Ordered dialects.</p> - * - * <p>The constants defined in Base64 can be OR-ed together to combine options, so you - * might make a call like this:</p> - * + * <p> + * Encodes and decodes to and from Base64 notation. + * </p> + * <p> + * Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>. + * </p> + * <p> + * The <tt>options</tt> parameter, which appears in a few places, is used to + * pass several pieces of information to the encoder. In the "higher level" + * methods such as encodeBytes( bytes, options ) the options parameter can be + * used to indicate such things as first gzipping the bytes before encoding + * them, not inserting linefeeds (though that breaks strict Base64 + * compatibility), and encoding using the URL-safe and Ordered dialects. + * </p> + * <p> + * The constants defined in Base64 can be OR-ed together to combine options, so + * you might make a call like this: + * </p> * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DONT_BREAK_LINES );</code> - * - * <p>to compress the data before encoding it and then making the output have no newline characters.</p> - * - * + * <p> + * to compress the data before encoding it and then making the output have no + * newline characters. + * </p> * <p> * Change Log: * </p> * <ul> - * <li>v2.2.2 - Fixed encodeFileToFile and decodeFileToFile to use the - * Base64.InputStream class to encode and decode on the fly which uses - * less memory than encoding/decoding an entire file into memory before writing.</li> - * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug - * when using very small files (~< 40 bytes).</li> - * <li>v2.2 - Added some helper methods for encoding/decoding directly from - * one file to the next. Also added a main() method to support command line - * encoding/decoding from one file to the next. Also added these Base64 dialects: - * <ol> - * <li>The default is RFC3548 format.</li> - * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates - * URL and file name friendly format as described in Section 4 of RFC3548. - * http://www.faqs.org/rfcs/rfc3548.html</li> - * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates - * URL and file name friendly format that preserves lexical ordering as described - * in http://www.faqs.org/qa/rfcc-1940.html</li> - * </ol> - * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> - * for contributing the new Base64 dialects. - * </li> - * - * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added - * some convenience methods for reading and writing to and from files.</li> - * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems - * with other encodings (like EBCDIC).</li> - * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the - * encoded data was a single byte.</li> - * <li>v2.0 - I got rid of methods that used booleans to set options. - * Now everything is more consolidated and cleaner. The code now detects - * when data that's being decoded is gzip-compressed and will decompress it - * automatically. Generally things are cleaner. You'll probably have to - * change some method calls that you were making to support the new - * options format (<tt>int</tt>s that you "OR" together).</li> - * <li>v1.5.1 - Fixed bug when decompressing and decoding to a - * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. - * Added the ability to "suspend" encoding in the Output Stream so - * you can turn on and off the encoding if you need to embed base64 - * data in an otherwise "normal" stream (like an XML file).</li> - * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. - * This helps when using GZIP streams. - * Added the ability to GZip-compress objects before encoding them.</li> - * <li>v1.4 - Added helper methods to read/write files.</li> - * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> - * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream - * where last buffer being read, if not completely full, was not returned.</li> - * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> - * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> + * <li>v2.2.2 - Fixed encodeFileToFile and decodeFileToFile to use the + * Base64.InputStream class to encode and decode on the fly which uses less + * memory than encoding/decoding an entire file into memory before writing.</li> + * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug when + * using very small files (~< 40 bytes).</li> + * <li>v2.2 - Added some helper methods for encoding/decoding directly from one + * file to the next. Also added a main() method to support command line + * encoding/decoding from one file to the next. Also added these Base64 + * dialects: + * <ol> + * <li>The default is RFC3548 format.</li> + * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates + * URL and file name friendly format as described in Section 4 of RFC3548. + * http://www.faqs.org/rfcs/rfc3548.html</li> + * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates + * URL and file name friendly format that preserves lexical ordering as + * described in http://www.faqs.org/qa/rfcc-1940.html</li> + * </ol> + * Special thanks to Jim Kellerman at <a + * href="http://www.powerset.com/">http://www.powerset.com/</a> for contributing + * the new Base64 dialects.</li> + * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. + * Added some convenience methods for reading and writing to and from files.</li> + * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on + * systems with other encodings (like EBCDIC).</li> + * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the + * encoded data was a single byte.</li> + * <li>v2.0 - I got rid of methods that used booleans to set options. Now + * everything is more consolidated and cleaner. The code now detects when data + * that's being decoded is gzip-compressed and will decompress it automatically. + * Generally things are cleaner. You'll probably have to change some method + * calls that you were making to support the new options format (<tt>int</tt>s + * that you "OR" together).</li> + * <li>v1.5.1 - Fixed bug when decompressing and decoding to a byte[] using + * <tt>decode( String s, boolean gzipCompressed )</tt>. Added the ability to + * "suspend" encoding in the Output Stream so you can turn on and off the + * encoding if you need to embed base64 data in an otherwise "normal" stream + * (like an XML file).</li> + * <li>v1.5 - Output stream pases on flush() command but doesn't do anything + * itself. This helps when using GZIP streams. Added the ability to + * GZip-compress objects before encoding them.</li> + * <li>v1.4 - Added helper methods to read/write files.</li> + * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> + * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input + * stream where last buffer being read, if not completely full, was not + * returned.</li> + * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the + * wrong time.</li> + * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> - * * <p> - * I am placing this code in the Public Domain. Do with it as you will. - * This software comes with no guarantees or warranties but with - * plenty of well-wishing instead! - * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> - * periodically to check for updates or to contribute improvements. + * I am placing this code in the Public Domain. Do with it as you will. This + * software comes with no guarantees or warranties but with plenty of + * well-wishing instead! Please visit <a + * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically + * to check for updates or to contribute improvements. * </p> - * + * * @author Robert Harder * @author rob@iharder.net * @version 2.2.2 */ -public class Base64 +public final class Base64 { - -/* ******** P U B L I C F I E L D S ******** */ - - + + /* ******** P U B L I C F I E L D S ******** */ + /** No options specified. Value is zero. */ - public final static int NO_OPTIONS = 0; - + public static final int NO_OPTIONS = 0; + /** Specify encoding. */ - public final static int ENCODE = 1; - - + public static final int ENCODE = 1; + /** Specify decoding. */ - public final static int DECODE = 0; - - + public static final int DECODE = 0; + /** Specify that data should be gzip-compressed. */ - public final static int GZIP = 2; - - + public static final int GZIP = 2; + /** Don't break lines when encoding (violates strict Base64 specification) */ - public final static int DONT_BREAK_LINES = 8; - - /** - * Encode using Base64-like encoding that is URL- and Filename-safe as described - * in Section 4 of RFC3548: - * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. - * It is important to note that data encoded this way is <em>not</em> officially valid Base64, - * or at the very least should not be called Base64 without also specifying that is - * was encoded using the URL- and Filename-safe dialect. - */ - public final static int URL_SAFE = 16; - - - /** - * Encode using the special "ordered" dialect of Base64 described here: - * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. - */ - public final static int ORDERED = 32; - - -/* ******** P R I V A T E F I E L D S ******** */ - - + public static final int DONT_BREAK_LINES = 8; + + /** + * Encode using Base64-like encoding that is URL- and Filename-safe as + * described in Section 4 of RFC3548: <a + * href="http://www.faqs.org/rfcs/rfc3548.html" + * >http://www.faqs.org/rfcs/rfc3548.html</a>. It is important to note that + * data encoded this way is <em>not</em> officially valid Base64, or at the + * very least should not be called Base64 without also specifying that is + * was encoded using the URL- and Filename-safe dialect. + */ + public static final int URL_SAFE = 16; + + /** + * Encode using the special "ordered" dialect of Base64 described here: <a + * href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc- + * 1940.html</a>. + */ + public static final int ORDERED = 32; + + /* ******** P R I V A T E F I E L D S ******** */ + /** Maximum line length (76) of Base64 output. */ - private final static int MAX_LINE_LENGTH = 76; - - + private static final int MAX_LINE_LENGTH = 76; + /** The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte)'='; - - + private static final byte EQUALS_SIGN = (byte) '='; + /** The new line character (\n) as a byte. */ - private final static byte NEW_LINE = (byte)'\n'; - - + private static final byte NEW_LINE = (byte) '\n'; + /** Preferred encoding. */ - private final static String PREFERRED_ENCODING = "UTF-8"; - - + private static final String PREFERRED_ENCODING = "UTF-8"; + // I think I end up not using the BAD_ENCODING indicator. - //private final static byte BAD_ENCODING = -9; // Indicates error in encoding - private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding - private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding - - -/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ - + // private final static byte BAD_ENCODING = -9; // Indicates error in + // encoding + private static final byte WHITE_SPACE_ENC = -5; // Indicates white space in + // encoding + + private static final byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in + // encoding + + /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ + /** The 64 valid Base64 values. */ - //private final static byte[] ALPHABET; - /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ - private final static byte[] _STANDARD_ALPHABET = - { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' - }; - - - /** - * Translates a Base64 value to either its 6-bit reconstruction value - * or a negative number indicating some other meaning. + // private final static byte[] ALPHABET; + /* + * Host platform me be something funny like EBCDIC, so we hardcode these + * values. + */ + private static final byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', + (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', + (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', + (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', + (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', + (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', + (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', + (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', + (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', + (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', + (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; + + /** + * Translates a Base64 value to either its 6-bit reconstruction value or a + * negative number indicating some other meaning. **/ - private final static byte[] _STANDARD_DECODABET = - { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9,-9,-9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ + private static final byte[] _STANDARD_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 0 + // - + // 8 + -5, -5, // Whitespace: + // Tab and + // Linefeed + -9, -9, // Decimal 11 - + // 12 + -5, // Whitespace: + // Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 14 + // - + // 26 + -9, -9, -9, -9, -9, // Decimal + // 27 + // - + // 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 33 + // - + // 42 + 62, // Plus sign at + // decimal 43 + -9, -9, -9, // Decimal 44 + // - 46 + 63, // Slash at decimal + // 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers + // zero + // through + // nine + -9, -9, -9, // Decimal 58 + // - 60 + -1, // Equals sign at + // decimal 61 + -9, -9, -9, // Decimal 62 + // - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters + // 'A' + // through + // 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters + // 'O' + // through + // 'Z' + -9, -9, -9, -9, -9, -9, // Decimal + // 91 + // - + // 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters + // 'a' + // through + // 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters + // 'n' + // through + // 'z' + -9, -9, -9, -9 // Decimal + // 123 - + // 126 + /* + * ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + */ }; - - -/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ - - /** - * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: - * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. - * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." - */ - private final static byte[] _URL_SAFE_ALPHABET = - { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' + + /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ + + /** + * Used in the URL- and Filename-safe dialect described in Section 4 of + * RFC3548: <a + * href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org + * /rfcs/rfc3548.html</a>. Notice that the last two bytes become "hyphen" + * and "underscore" instead of "plus" and "slash." + */ + private static final byte[] _URL_SAFE_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', + (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', + (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', + (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', + (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', + (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', + (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', + (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', + (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', + (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', + (byte) '8', (byte) '9', (byte) '-', (byte) '_' }; + + /** + * Used in decoding URL- and Filename-safe dialects of Base64. + */ + private static final byte[] _URL_SAFE_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 0 + // - + // 8 + -5, -5, // Whitespace: + // Tab and + // Linefeed + -9, -9, // Decimal 11 - + // 12 + -5, // Whitespace: + // Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 14 + // - + // 26 + -9, -9, -9, -9, -9, // Decimal + // 27 + // - + // 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 33 + // - + // 42 + -9, // Plus sign at + // decimal 43 + -9, // Decimal 44 + 62, // Minus sign at + // decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal + // 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers + // zero + // through + // nine + -9, -9, -9, // Decimal 58 + // - 60 + -1, // Equals sign at + // decimal 61 + -9, -9, -9, // Decimal 62 + // - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters + // 'A' + // through + // 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters + // 'O' + // through + // 'Z' + -9, -9, -9, -9, // Decimal + // 91 - + // 94 + 63, // Underscore at + // decimal 95 + -9, // Decimal 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters + // 'a' + // through + // 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters + // 'n' + // through + // 'z' + -9, -9, -9, -9 // Decimal + // 123 - + // 126 + /* + * ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + */ }; - - /** - * Used in decoding URL- and Filename-safe dialects of Base64. - */ - private final static byte[] _URL_SAFE_DECODABET = - { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 62, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9, // Decimal 91 - 94 - 63, // Underscore at decimal 95 - -9, // Decimal 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ + + /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ + + /** + * I don't get the point of this technique, but it is described here: <a + * href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc- + * 1940.html</a>. + */ + private static final byte[] _ORDERED_ALPHABET = { (byte) '-', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', + (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', + (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', + (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', + (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', + (byte) 'Z', (byte) '_', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', + (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', + (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', + (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', + (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' }; + + /** + * Used in decoding the "ordered" dialect of Base64. + */ + private static final byte[] _ORDERED_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 0 + // - + // 8 + -5, -5, // Whitespace: Tab + // and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: + // Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 14 + // - + // 26 + -9, -9, -9, -9, -9, // Decimal + // 27 + // - + // 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal + // 33 + // - + // 42 + -9, // Plus sign at + // decimal 43 + -9, // Decimal 44 + 0, // Minus sign at + // decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers + // zero + // through + // nine + -9, -9, -9, // Decimal 58 + // - 60 + -1, // Equals sign at + // decimal 61 + -9, -9, -9, // Decimal 62 + // - 64 + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters + // 'A' + // through + // 'M' + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters + // 'N' + // through + // 'Z' + -9, -9, -9, -9, // Decimal + // 91 - 94 + 37, // Underscore at + // decimal 95 + -9, // Decimal 96 + 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters + // 'a' + // through + // 'm' + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters + // 'n' + // through + // 'z' + -9, -9, -9, -9 // Decimal + // 123 - + // 126 + /* + * ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + */ }; + /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ + /** + * Returns one of the _SOMETHING_ALPHABET byte arrays depending on the + * options specified. It's possible, though silly, to specify ORDERED and + * URLSAFE in which case one of them will be picked, though there is no + * guarantee as to which one will be picked. + */ + private final static byte[] getAlphabet( int options ) + { + if( (options & URL_SAFE) == URL_SAFE ) + return _URL_SAFE_ALPHABET; + else if( (options & ORDERED) == ORDERED ) + return _ORDERED_ALPHABET; + else + return _STANDARD_ALPHABET; -/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ + } // end getAlphabet - /** - * I don't get the point of this technique, but it is described here: - * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. - */ - private final static byte[] _ORDERED_ALPHABET = + /** + * Returns one of the _SOMETHING_DECODABET byte arrays depending on the + * options specified. It's possible, though silly, to specify ORDERED and + * URL_SAFE in which case one of them will be picked, though there is no + * guarantee as to which one will be picked. + */ + private static final byte[] getDecodabet( int options ) { - (byte)'-', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', - (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'_', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' - }; - - /** - * Used in decoding the "ordered" dialect of Base64. - */ - private final static byte[] _ORDERED_DECODABET = - { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 0, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' - 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' - -9,-9,-9,-9, // Decimal 91 - 94 - 37, // Underscore at decimal 95 - -9, // Decimal 96 - 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' - 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; + if( (options & URL_SAFE) == URL_SAFE ) + return _URL_SAFE_DECODABET; + else if( (options & ORDERED) == ORDERED ) + return _ORDERED_DECODABET; + else + return _STANDARD_DECODABET; - -/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ - - - /** - * Returns one of the _SOMETHING_ALPHABET byte arrays depending on - * the options specified. - * It's possible, though silly, to specify ORDERED and URLSAFE - * in which case one of them will be picked, though there is - * no guarantee as to which one will be picked. - */ - private final static byte[] getAlphabet( int options ) - { - if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET; - else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET; - else return _STANDARD_ALPHABET; - - } // end getAlphabet - - - /** - * Returns one of the _SOMETHING_DECODABET byte arrays depending on - * the options specified. - * It's possible, though silly, to specify ORDERED and URL_SAFE - * in which case one of them will be picked, though there is - * no guarantee as to which one will be picked. - */ - private final static byte[] getDecodabet( int options ) - { - if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET; - else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET; - else return _STANDARD_DECODABET; - - } // end getAlphabet - + } // end getAlphabet - /** Defeats instantiation. */ - private Base64(){} - + private Base64() + { + } /** - * Encodes or decodes two files from the command line; - * <strong>feel free to delete this method (in fact you probably should) - * if you're embedding this code into a larger program.</strong> + * Encodes or decodes two files from the command line; <strong>feel free to + * delete this method (in fact you probably should) if you're embedding this + * code into a larger program.</strong> */ - public final static void main( String[] args ) + public static final void main( final String[] args ) { - if( args.length < 3 ){ - usage("Not enough arguments."); - } // end if: args.length < 3 - else { + if( args.length < 3 ) + { + usage( "Not enough arguments." ); + } // end if: args.length < 3 + else + { String flag = args[0]; String infile = args[1]; String outfile = args[2]; - if( flag.equals( "-e" ) ){ + if( flag.equals( "-e" ) ) + { Base64.encodeFileToFile( infile, outfile ); - } // end if: encode - else if( flag.equals( "-d" ) ) { + } // end if: encode + else if( flag.equals( "-d" ) ) + { Base64.decodeFileToFile( infile, outfile ); - } // end else if: decode - else { + } // end else if: decode + else + { usage( "Unknown flag: " + flag ); - } // end else - } // end else - } // end main + } // end else + } // end else + } // end main /** * Prints command line usage. - * + * * @param msg A message to include with usage info. */ - private final static void usage( String msg ) + private static final void usage( String msg ) { System.err.println( msg ); System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" ); - } // end usage - - -/* ******** E N C O D I N G M E T H O D S ******** */ - - + } // end usage + + /* ******** E N C O D I N G M E T H O D S ******** */ + /** - * Encodes up to the first three bytes of array <var>threeBytes</var> - * and returns a four-byte array in Base64 notation. - * The actual number of significant bytes in your array is - * given by <var>numSigBytes</var>. - * The array <var>threeBytes</var> needs only be as big as - * <var>numSigBytes</var>. - * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. - * + * Encodes up to the first three bytes of array <var>threeBytes</var> and + * returns a four-byte array in Base64 notation. The actual number of + * significant bytes in your array is given by <var>numSigBytes</var>. The + * array <var>threeBytes</var> needs only be as big as + * <var>numSigBytes</var>. Code can reuse a byte array by passing a + * four-byte array as <var>b4</var>. + * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; - } // end encode3to4 + } // end encode3to4 - /** - * <p>Encodes up to three bytes of the array <var>source</var> - * and writes the resulting four Base64 bytes to <var>destination</var>. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * <var>srcOffset</var> and <var>destOffset</var>. - * This method does not check to make sure your arrays - * are large enough to accomodate <var>srcOffset</var> + 3 for - * the <var>source</var> array or <var>destOffset</var> + 4 for - * the <var>destination</var> array. - * The actual number of significant bytes in your array is - * given by <var>numSigBytes</var>.</p> - * <p>This is the lowest level of the encoding methods with - * all possible parameters.</p> - * + * <p> + * Encodes up to three bytes of the array <var>source</var> and writes the + * resulting four Base64 bytes to <var>destination</var>. The source and + * destination arrays can be manipulated anywhere along their length by + * specifying <var>srcOffset</var> and <var>destOffset</var>. This method + * does not check to make sure your arrays are large enough to accomodate + * <var>srcOffset</var> + 3 for the <var>source</var> array or + * <var>destOffset</var> + 4 for the <var>destination</var> array. The + * actual number of significant bytes in your array is given by + * <var>numSigBytes</var>. + * </p> + * <p> + * This is the lowest level of the encoding methods with all possible + * parameters. + * </p> + * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ - private static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset, int options ) + private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { - byte[] ALPHABET = getAlphabet( options ); - - // 1 2 3 + byte[] ALPHABET = getAlphabet( options ); + + // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes - // --------| || || || | Six bit groups to index ALPHABET - // >>18 >>12 >> 6 >> 0 Right shift necessary - // 0x3f 0x3f 0x3f Additional AND - + // --------| || || || | Six bit groups to index ALPHABET + // >>18 >>12 >> 6 >> 0 Right shift necessary + // 0x3f 0x3f 0x3f Additional AND + // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear - // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) - | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) - | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); + // when Java treats a value as negative that is cast from a byte to an + // int. + int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) + | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch( numSigBytes ) { case 3: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; return destination; - + case 2: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = EQUALS_SIGN; + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = EQUALS_SIGN; return destination; - + case 1: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = EQUALS_SIGN; - destination[ destOffset + 3 ] = EQUALS_SIGN; + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = EQUALS_SIGN; + destination[destOffset + 3] = EQUALS_SIGN; return destination; - + default: return destination; - } // end switch - } // end encode3to4 - - - + } // end switch + } // end encode3to4 + /** - * Serializes an object and returns the Base64-encoded - * version of that serialized object. If the object - * cannot be serialized or there is another error, - * the method will return <tt>null</tt>. - * The object is not GZip-compressed before being encoded. - * + * Serializes an object and returns the Base64-encoded version of that + * serialized object. If the object cannot be serialized or there is another + * error, the method will return <tt>null</tt>. The object is not + * GZip-compressed before being encoded. + * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) { return encodeObject( serializableObject, NO_OPTIONS ); - } // end encodeObject - - + } // end encodeObject /** - * Serializes an object and returns the Base64-encoded - * version of that serialized object. If the object - * cannot be serialized or there is another error, - * the method will return <tt>null</tt>. + * Serializes an object and returns the Base64-encoded version of that + * serialized object. If the object cannot be serialized or there is another + * error, the method will return <tt>null</tt>. * <p> - * Valid options:<pre> + * Valid options: + * + * <pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters - * <i>Note: Technically, this makes your encoding non-compliant.</i> + * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> - * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> - * + * Example: + * <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> + * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) { // Streams - java.io.ByteArrayOutputStream baos = null; - java.io.OutputStream b64os = null; - java.io.ObjectOutputStream oos = null; - java.util.zip.GZIPOutputStream gzos = null; - + java.io.ByteArrayOutputStream baos = null; + java.io.OutputStream b64os = null; + java.io.ObjectOutputStream oos = null; + java.util.zip.GZIPOutputStream gzos = null; + // Isolate options - int gzip = (options & GZIP); + int gzip = (options & GZIP); // int dontBreakLines = (options & DONT_BREAK_LINES); - + try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream - baos = new java.io.ByteArrayOutputStream(); + baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); - + // GZip? if( gzip == GZIP ) { gzos = new java.util.zip.GZIPOutputStream( b64os ); - oos = new java.io.ObjectOutputStream( gzos ); - } // end if: gzip + oos = new java.io.ObjectOutputStream( gzos ); + } // end if: gzip else - oos = new java.io.ObjectOutputStream( b64os ); - + oos = new java.io.ObjectOutputStream( b64os ); + oos.writeObject( serializableObject ); - } // end try + } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; - } // end catch + } // end catch finally { - try{ oos.close(); } catch( Exception e ){} - try{ gzos.close(); } catch( Exception e ){} - try{ b64os.close(); } catch( Exception e ){} - try{ baos.close(); } catch( Exception e ){} - } // end finally - + try + { + oos.close(); + } + catch( Exception e ) + { + } + try + { + gzos.close(); + } + catch( Exception e ) + { + } + try + { + b64os.close(); + } + catch( Exception e ) + { + } + try + { + baos.close(); + } + catch( Exception e ) + { + } + } // end finally + // Return value according to relevant encoding. - try + try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) + } // end try + catch( java.io.UnsupportedEncodingException uue ) { return new String( baos.toByteArray() ); - } // end catch - - } // end encode - - + } // end catch + + } // end encode /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * * @param source The data to convert * @since 1.4 */ public static String encodeBytes( byte[] source ) { return encodeBytes( source, 0, source.length, NO_OPTIONS ); - } // end encodeBytes - - + } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> - * Valid options:<pre> + * Valid options: + * + * <pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters - * <i>Note: Technically, this makes your encoding non-compliant.</i> + * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> - * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> - * - * + * Example: + * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> + * * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) - { + { return encodeBytes( source, 0, source.length, options ); - } // end encodeBytes - - + } // end encodeBytes + /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, NO_OPTIONS ); - } // end encodeBytes - - + } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> - * Valid options:<pre> + * Valid options: + * + * <pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters - * <i>Note: Technically, this makes your encoding non-compliant.</i> + * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> - * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> - * - * + * Example: + * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> + * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options - * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) { // Isolate options - int dontBreakLines = ( options & DONT_BREAK_LINES ); - int gzip = ( options & GZIP ); - + int dontBreakLines = (options & DONT_BREAK_LINES); + int gzip = (options & GZIP); + // Compress? if( gzip == GZIP ) { - java.io.ByteArrayOutputStream baos = null; - java.util.zip.GZIPOutputStream gzos = null; - Base64.OutputStream b64os = null; - - + java.io.ByteArrayOutputStream baos = null; + java.util.zip.GZIPOutputStream gzos = null; + Base64.OutputStream b64os = null; + try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); - gzos = new java.util.zip.GZIPOutputStream( b64os ); - + gzos = new java.util.zip.GZIPOutputStream( b64os ); + gzos.write( source, off, len ); gzos.close(); - } // end try + } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; - } // end catch + } // end catch finally { - try{ gzos.close(); } catch( Exception e ){} - try{ b64os.close(); } catch( Exception e ){} - try{ baos.close(); } catch( Exception e ){} - } // end finally + try + { + gzos.close(); + } + catch( Exception e ) + { + } + try + { + b64os.close(); + } + catch( Exception e ) + { + } + try + { + baos.close(); + } + catch( Exception e ) + { + } + } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) + } // end try + catch( java.io.UnsupportedEncodingException uue ) { return new String( baos.toByteArray() ); - } // end catch - } // end if: compress - + } // end catch + } // end if: compress + // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; - - int len43 = len * 4 / 3; - byte[] outBuff = new byte[ ( len43 ) // Main 4:3 - + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding - + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines + + int len43 = len * 4 / 3; + byte[] outBuff = new byte[(len43) // Main 4:3 + + ((len % 3) > 0 ? 4 : 0) // Account for + // padding + + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New + // lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; - for( ; d < len2; d+=3, e+=4 ) + for( ; d < len2; d += 3, e += 4 ) { - encode3to4( source, d+off, 3, outBuff, e, options ); + encode3to4( source, d + off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) - { - outBuff[e+4] = NEW_LINE; + { + outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; - } // end if: end of line - } // en dfor: each piece of array + } // end if: end of line + } // en dfor: each piece of array if( d < len ) { - encode3to4( source, d+off, len - d, outBuff, e, options ); + encode3to4( source, d + off, len - d, outBuff, e, options ); e += 4; - } // end if: some padding needed + } // end if: some padding needed - // Return value according to relevant encoding. try { return new String( outBuff, 0, e, PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) + } // end try + catch( java.io.UnsupportedEncodingException uue ) { return new String( outBuff, 0, e ); - } // end catch - - } // end else: don't compress - - } // end encodeBytes - + } // end catch + + } // end else: don't compress + + } // end encodeBytes + + /* ******** D E C O D I N G M E T H O D S ******** */ - - - -/* ******** D E C O D I N G M E T H O D S ******** */ - - /** - * Decodes four bytes from array <var>source</var> - * and writes the resulting bytes (up to three of them) - * to <var>destination</var>. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * <var>srcOffset</var> and <var>destOffset</var>. - * This method does not check to make sure your arrays - * are large enough to accomodate <var>srcOffset</var> + 4 for - * the <var>source</var> array or <var>destOffset</var> + 3 for - * the <var>destination</var> array. - * This method returns the actual number of bytes that - * were converted from the Base64 encoding. - * <p>This is the lowest level of the decoding methods with - * all possible parameters.</p> + * Decodes four bytes from array <var>source</var> and writes the resulting + * bytes (up to three of them) to <var>destination</var>. The source and + * destination arrays can be manipulated anywhere along their length by + * specifying <var>srcOffset</var> and <var>destOffset</var>. This method + * does not check to make sure your arrays are large enough to accomodate + * <var>srcOffset</var> + 4 for the <var>source</var> array or + * <var>destOffset</var> + 3 for the <var>destination</var> array. This + * method returns the actual number of bytes that were converted from the + * Base64 encoding. + * <p> + * This is the lowest level of the decoding methods with all possible + * parameters. + * </p> * - * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put - * @param options alphabet type is pulled from this (standard, url-safe, ordered) + * @param options alphabet type is pulled from this (standard, url-safe, + * ordered) * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { - byte[] DECODABET = getDecodabet( options ); - + byte[] DECODABET = getDecodabet( options ); + // Example: Dk== - if( source[ srcOffset + 2] == EQUALS_SIGN ) + if( source[srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); + // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 + // ) + // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); + + destination[destOffset] = (byte) (outBuff >>> 16); return 1; } - + // Example: DkL= - else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) + else if( source[srcOffset + 3] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); + // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 + // ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); + + destination[destOffset] = (byte) (outBuff >>> 16); + destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } - + // Example: DkLE else { - try{ - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) - // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) - | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); - - - destination[ destOffset ] = (byte)( outBuff >> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); - destination[ destOffset + 2 ] = (byte)( outBuff ); - - return 3; - }catch( Exception e){ - System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); - System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); - System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); - System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); + try + { + // Two ways to do the same thing. Don't know which way I like + // best. + // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) + // >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) + // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF)); + + destination[destOffset] = (byte) (outBuff >> 16); + destination[destOffset + 1] = (byte) (outBuff >> 8); + destination[destOffset + 2] = (byte) (outBuff); + + return 3; + } + catch( Exception e ) + { + System.out.println( "" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]]) ); + System.out.println( "" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]]) ); + System.out.println( "" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]]) ); + System.out.println( "" + source[srcOffset + 3] + ": " + (DECODABET[source[srcOffset + 3]]) ); return -1; - } // end catch + } // end catch } - } // end decodeToBytes - - - - + } // end decodeToBytes + /** - * Very low-level access to decoding ASCII characters in - * the form of a byte array. Does not support automatically - * gunzipping or any other "fancy" features. - * + * Very low-level access to decoding ASCII characters in the form of a byte + * array. Does not support automatically gunzipping or any other "fancy" + * features. + * * @param source The Base64 encoded data - * @param off The offset of where to begin decoding - * @param len The length of characters to decode + * @param off The offset of where to begin decoding + * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len, int options ) { - byte[] DECODABET = getDecodabet( options ); - - int len34 = len * 3 / 4; - byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output - int outBuffPosn = 0; - - byte[] b4 = new byte[4]; - int b4Posn = 0; - int i = 0; - byte sbiCrop = 0; - byte sbiDecode = 0; - for( i = off; i < off+len; i++ ) + byte[] DECODABET = getDecodabet( options ); + + int len34 = len * 3 / 4; + byte[] outBuff = new byte[len34]; // Upper limit on size of output + int outBuffPosn = 0; + + byte[] b4 = new byte[4]; + int b4Posn = 0; + int i = 0; + byte sbiCrop = 0; + byte sbiDecode = 0; + for( i = off; i < off + len; i++ ) { - sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits - sbiDecode = DECODABET[ sbiCrop ]; - - if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better + sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits + sbiDecode = DECODABET[sbiCrop]; + + if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or + // better { if( sbiDecode >= EQUALS_SIGN_ENC ) { - b4[ b4Posn++ ] = sbiCrop; + b4[b4Posn++] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; - + // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; - } // end if: quartet built - - } // end if: equals sign or better - - } // end if: white space, equals sign or better + } // end if: quartet built + + } // end if: equals sign or better + + } // end if: white space, equals sign or better else { System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; - } // end else: - } // each input character - - byte[] out = new byte[ outBuffPosn ]; - System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); + } // end else: + } // each input character + + byte[] out = new byte[outBuffPosn]; + System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; - } // end decode - - - - + } // end decode + /** - * Decodes data from Base64 notation, automatically - * detecting gzip-compressed data and decompressing it. - * + * Decodes data from Base64 notation, automatically detecting + * gzip-compressed data and decompressing it. + * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode( String s ) - { - return decode( s, NO_OPTIONS ); - } - - + { + return decode( s, NO_OPTIONS ); + } + /** - * Decodes data from Base64 notation, automatically - * detecting gzip-compressed data and decompressing it. - * + * Decodes data from Base64 notation, automatically detecting + * gzip-compressed data and decompressing it. + * * @param s the string to decode - * @param options encode options such as URL_SAFE + * @param options encode options such as URL_SAFE * @return the decoded data * @since 1.4 */ - @SuppressWarnings("cast") + @SuppressWarnings( "cast" ) public static byte[] decode( String s, int options ) - { + { byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); - } // end try + } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); - } // end catch - //</change> - + } // end catch + // </change> + // Decode bytes = decode( bytes, 0, bytes.length, options ); - - + // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( bytes != null && bytes.length >= 4 ) { - - int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); - if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) + + int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); + if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { - java.io.ByteArrayInputStream bais = null; + java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; - int length = 0; + int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); - while( ( length = gzis.read( buffer ) ) >= 0 ) + while ( (length = gzis.read( buffer )) >= 0 ) { - baos.write(buffer,0,length); - } // end while: reading input + baos.write( buffer, 0, length ); + } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); - } // end try + } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes - } // end catch + } // end catch finally { - try{ baos.close(); } catch( Exception e ){} - try{ gzis.close(); } catch( Exception e ){} - try{ bais.close(); } catch( Exception e ){} - } // end finally - - } // end if: gzipped - } // end if: bytes.length >= 2 - - return bytes; - } // end decode + try + { + baos.close(); + } + catch( Exception e ) + { + } + try + { + gzis.close(); + } + catch( Exception e ) + { + } + try + { + bais.close(); + } + catch( Exception e ) + { + } + } // end finally + } // end if: gzipped + } // end if: bytes.length >= 2 - + return bytes; + } // end decode /** - * Attempts to decode Base64 data and deserialize a Java - * Object within. Returns <tt>null</tt> if there was an error. - * + * Attempts to decode Base64 data and deserialize a Java Object within. + * Returns <tt>null</tt> if there was an error. + * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject( String encodedObject ) { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject ); - - java.io.ByteArrayInputStream bais = null; - java.io.ObjectInputStream ois = null; + + java.io.ByteArrayInputStream bais = null; + java.io.ObjectInputStream ois = null; Object obj = null; - + try { bais = new java.io.ByteArrayInputStream( objBytes ); - ois = new java.io.ObjectInputStream( bais ); - + ois = new java.io.ObjectInputStream( bais ); + obj = ois.readObject(); - } // end try + } // end try catch( java.io.IOException e ) { e.printStackTrace(); obj = null; - } // end catch + } // end catch catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); obj = null; - } // end catch + } // end catch finally { - try{ bais.close(); } catch( Exception e ){} - try{ ois.close(); } catch( Exception e ){} - } // end finally - + try + { + bais.close(); + } + catch( Exception e ) + { + } + try + { + ois.close(); + } + catch( Exception e ) + { + } + } // end finally + return obj; - } // end decodeObject - - - + } // end decodeObject + /** * Convenience method for encoding data to a file. - * + * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise - * * @since 2.1 */ public static boolean encodeToFile( byte[] dataToEncode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { - bos = new Base64.OutputStream( - new java.io.FileOutputStream( filename ), Base64.ENCODE ); + bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); success = true; - } // end try + } // end try catch( java.io.IOException e ) { - + success = false; - } // end catch: IOException + } // end catch: IOException finally { - try{ bos.close(); } catch( Exception e ){} - } // end finally - + try + { + bos.close(); + } + catch( Exception e ) + { + } + } // end finally + return success; - } // end encodeToFile - - + } // end encodeToFile + /** * Convenience method for decoding data to a file. - * + * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise - * * @since 2.1 */ public static boolean decodeToFile( String dataToDecode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { - bos = new Base64.OutputStream( - new java.io.FileOutputStream( filename ), Base64.DECODE ); - bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); - success = true; - } // end try + bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); + bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); + success = true; + } // end try catch( java.io.IOException e ) { success = false; - } // end catch: IOException + } // end catch: IOException finally { - try{ bos.close(); } catch( Exception e ){} - } // end finally - + try + { + bos.close(); + } + catch( Exception e ) + { + } + } // end finally + return success; - } // end decodeToFile - - - - + } // end decodeToFile + /** - * Convenience method for reading a base64-encoded - * file and decoding it. - * + * Convenience method for reading a base64-encoded file and decoding it. + * * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful - * * @since 2.1 */ public static byte[] decodeFromFile( String filename ) { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; - int length = 0; + int length = 0; int numBytes = 0; - + // Check for size of file if( file.length() > Integer.MAX_VALUE ) { System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); return null; - } // end if: file too big for int index - buffer = new byte[ (int)file.length() ]; - + } // end if: file too big for int index + buffer = new byte[(int) file.length()]; + // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( file ) ), Base64.DECODE ); - + bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); + // Read until done - while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) + while ( (numBytes = bis.read( buffer, length, 4096 )) >= 0 ) length += numBytes; - + // Save in a variable to return - decodedData = new byte[ length ]; + decodedData = new byte[length]; System.arraycopy( buffer, 0, decodedData, 0, length ); - - } // end try + + } // end try catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); - } // end catch: IOException + } // end catch: IOException finally { - try{ bis.close(); } catch( Exception e) {} - } // end finally - + try + { + bis.close(); + } + catch( Exception e ) + { + } + } // end finally + return decodedData; - } // end decodeFromFile - - - + } // end decodeFromFile + /** - * Convenience method for reading a binary file - * and base64-encoding it. - * + * Convenience method for reading a binary file and base64-encoding it. + * * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful - * * @since 2.1 */ public static String encodeFromFile( String filename ) { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); - byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1) - int length = 0; + byte[] buffer = new byte[Math.max( (int) (file.length() * 1.4), 40 )]; // Need + // max() + // for + // math + // on + // small + // files + // (v2.2.1) + int length = 0; int numBytes = 0; - + // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( file ) ), Base64.ENCODE ); - + bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); + // Read until done - while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) + while ( (numBytes = bis.read( buffer, length, 4096 )) >= 0 ) length += numBytes; - + // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); - - } // end try + + } // end try catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); - } // end catch: IOException + } // end catch: IOException finally { - try{ bis.close(); } catch( Exception e) {} - } // end finally - + try + { + bis.close(); + } + catch( Exception e ) + { + } + } // end finally + return encodedData; - } // end encodeFromFile - - - - + } // end encodeFromFile + /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. - * + * * @param infile Input file * @param outfile Output file * @return true if the operation is successful * @since 2.2 */ public static boolean encodeFileToFile( String infile, String outfile ) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; - try{ - in = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( infile ) ), - Base64.ENCODE ); + try + { + in = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( infile ) ), Base64.ENCODE ); out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); byte[] buffer = new byte[65536]; // 64K int read = -1; - while( ( read = in.read(buffer) ) >= 0 ){ - out.write( buffer,0,read ); - } // end while: through file + while ( (read = in.read( buffer )) >= 0 ) + { + out.write( buffer, 0, read ); + } // end while: through file success = true; - } catch( java.io.IOException exc ){ + } + catch( java.io.IOException exc ) + { exc.printStackTrace(); - } finally{ - try{ in.close(); } catch( Exception exc ){} - try{ out.close(); } catch( Exception exc ){} - } // end finally - + } + finally + { + try + { + in.close(); + } + catch( Exception exc ) + { + } + try + { + out.close(); + } + catch( Exception exc ) + { + } + } // end finally + return success; - } // end encodeFileToFile - - - + } // end encodeFileToFile + /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. - * + * * @param infile Input file * @param outfile Output file * @return true if the operation is successful * @since 2.2 */ public static boolean decodeFileToFile( String infile, String outfile ) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; - try{ - in = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( infile ) ), - Base64.DECODE ); + try + { + in = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( infile ) ), Base64.DECODE ); out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); byte[] buffer = new byte[65536]; // 64K int read = -1; - while( ( read = in.read(buffer) ) >= 0 ){ - out.write( buffer,0,read ); - } // end while: through file + while ( (read = in.read( buffer )) >= 0 ) + { + out.write( buffer, 0, read ); + } // end while: through file success = true; - } catch( java.io.IOException exc ){ + } + catch( java.io.IOException exc ) + { exc.printStackTrace(); - } finally{ - try{ in.close(); } catch( Exception exc ){} - try{ out.close(); } catch( Exception exc ){} - } // end finally - + } + finally + { + try + { + in.close(); + } + catch( Exception exc ) + { + } + try + { + out.close(); + } + catch( Exception exc ) + { + } + } // end finally + return success; - } // end decodeFileToFile - - - /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ - - - + } // end decodeFileToFile + + /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ + /** * A {@link Base64.InputStream} will read data from another - * <tt>java.io.InputStream</tt>, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. - * + * <tt>java.io.InputStream</tt>, given in the constructor, and encode/decode + * to/from Base64 notation on the fly. + * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { - private boolean encode; // Encoding or decoding - private int position; // Current position in the buffer - private byte[] buffer; // Small buffer holding converted data - private int bufferLength; // Length of buffer (3 or 4) - private int numSigBytes; // Number of meaningful bytes in the buffer - private int lineLength; - private boolean breakLines; // Break lines at less than 80 characters - private int options; // Record options used to create the stream. - //private byte[] alphabet; // Local copies to avoid extra method calls - private byte[] decodabet; // Local copies to avoid extra method calls - - + private boolean encode; // Encoding or decoding + + private int position; // Current position in the buffer + + private byte[] buffer; // Small buffer holding converted data + + private int bufferLength; // Length of buffer (3 or 4) + + private int numSigBytes; // Number of meaningful bytes in the buffer + + private int lineLength; + + private boolean breakLines; // Break lines at less than 80 characters + + private int options; // Record options used to create the stream. + + // private byte[] alphabet; // Local copies to avoid extra method calls + private byte[] decodabet; // Local copies to avoid extra method calls + /** * Constructs a {@link Base64.InputStream} in DECODE mode. - * + * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) - { + { this( in, DECODE ); - } // end constructor - - + } // end constructor + /** - * Constructs a {@link Base64.InputStream} in - * either ENCODE or DECODE mode. + * Constructs a {@link Base64.InputStream} in either ENCODE or DECODE + * mode. * <p> - * Valid options:<pre> + * Valid options: + * + * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) - * <i>Note: Technically, this makes your encoding non-compliant.</i> + * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> - * - * + * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) - { + { super( in ); - this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; - this.encode = (options & ENCODE) == ENCODE; + this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; + this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 4 : 3; - this.buffer = new byte[ bufferLength ]; - this.position = -1; - this.lineLength = 0; - this.options = options; // Record for later, mostly to determine which alphabet to use - //this.alphabet = getAlphabet(options); - this.decodabet = getDecodabet(options); - } // end constructor - + this.buffer = new byte[bufferLength]; + this.position = -1; + this.lineLength = 0; + this.options = options; // Record for later, mostly to determine + // which alphabet to use + // this.alphabet = getAlphabet(options); + this.decodabet = getDecodabet( options ); + } // end constructor + /** - * Reads enough of the input stream to convert - * to/from Base64 and returns the next byte. - * + * Reads enough of the input stream to convert to/from Base64 and + * returns the next byte. + * * @return next byte * @since 1.3 */ - public int read() throws java.io.IOException - { + public int read() throws java.io.IOException + { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { try - { + { int b = in.read(); - + // If end of stream, b is -1. if( b >= 0 ) { - b3[i] = (byte)b; + b3[i] = (byte) b; numBinaryBytes++; - } // end if: not end of stream - - } // end try: read + } // end if: not end of stream + + } // end try: read catch( java.io.IOException e ) - { + { // Only a problem if we got no data at all. if( i == 0 ) throw e; - - } // end catch - } // end for: each needed input byte - + + } // end catch + } // end for: each needed input byte + if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); position = 0; numSigBytes = 4; - } // end if: got data + } // end if: got data else { return -1; - } // end else - } // end if: encoding - + } // end else + } // end if: encoding + // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; - do{ b = in.read(); } - while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); - + do + { + b = in.read(); + } + while ( b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC ); + if( b < 0 ) break; // Reads a -1 if end of stream - - b4[i] = (byte)b; - } // end for: each needed input byte - + + b4[i] = (byte) b; + } // end for: each needed input byte + if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0, options ); position = 0; - } // end if: got four characters - else if( i == 0 ){ + } // end if: got four characters + else if( i == 0 ) + { return -1; - } // end else if: also padded correctly + } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); - } // end - - } // end else: decode - } // end else: get data - + } // end + + } // end else: decode + } // end else: get data + // Got data? if( position >= 0 ) { // End of relevant data? - if( /*!encode &&*/ position >= numSigBytes ) + if( /* !encode && */position >= numSigBytes ) return -1; - + if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; - } // end if + } // end if else { - lineLength++; // This isn't important when decoding - // but throwing an extra "if" seems - // just as wasteful. - - int b = buffer[ position++ ]; + lineLength++; // This isn't important when decoding + // but throwing an extra "if" seems + // just as wasteful. + + int b = buffer[position++]; if( position >= bufferLength ) position = -1; return b & 0xFF; // This is how you "cast" a byte that's - // intended to be unsigned. - } // end else - } // end if: position >= 0 - + // intended to be unsigned. + } // end else + } // end if: position >= 0 + // Else error else - { + { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream." ); - } // end else - } // end read - - + } // end else + } // end read + /** - * Calls {@link #read()} repeatedly until the end of stream - * is reached or <var>len</var> bytes are read. - * Returns number of bytes read into array or -1 if - * end of stream is encountered. - * + * Calls {@link #read()} repeatedly until the end of stream is reached + * or <var>len</var> bytes are read. Returns number of bytes read into + * array or -1 if end of stream is encountered. + * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); - - //if( b < 0 && i == 0 ) - // return -1; - + + // if( b < 0 && i == 0 ) + // return -1; + if( b >= 0 ) - dest[off + i] = (byte)b; + dest[off + i] = (byte) b; else if( i == 0 ) return -1; else break; // Out of 'for' loop - } // end for: each byte read + } // end for: each byte read return i; - } // end read - - } // end inner class InputStream - - - - - - - /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ - - - + } // end read + + } // end inner class InputStream + + /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ + /** * A {@link Base64.OutputStream} will write data to another - * <tt>java.io.OutputStream</tt>, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. - * + * <tt>java.io.OutputStream</tt>, given in the constructor, and + * encode/decode to/from Base64 notation on the fly. + * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; - private int position; - private byte[] buffer; - private int bufferLength; - private int lineLength; + + private int position; + + private byte[] buffer; + + private int bufferLength; + + private int lineLength; + private boolean breakLines; - private byte[] b4; // Scratch used in a few places + + private byte[] b4; // Scratch used in a few places + private boolean suspendEncoding; - private int options; // Record for later - //private byte[] alphabet; // Local copies to avoid extra method calls - private byte[] decodabet; // Local copies to avoid extra method calls - + + private int options; // Record for later + + // private byte[] alphabet; // Local copies to avoid extra method calls + private byte[] decodabet; // Local copies to avoid extra method calls + /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. - * - * @param out the <tt>java.io.OutputStream</tt> to which data will be written. + * + * @param out the <tt>java.io.OutputStream</tt> to which data will be + * written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) - { + { this( out, ENCODE ); - } // end constructor - - + } // end constructor + /** - * Constructs a {@link Base64.OutputStream} in - * either ENCODE or DECODE mode. + * Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE + * mode. * <p> - * Valid options:<pre> + * Valid options: + * + * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) - * <i>Note: Technically, this makes your encoding non-compliant.</i> + * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> - * - * @param out the <tt>java.io.OutputStream</tt> to which data will be written. + * + * @param out the <tt>java.io.OutputStream</tt> to which data will be + * written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) - { + { super( out ); - this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; - this.encode = (options & ENCODE) == ENCODE; + this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; + this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; - this.buffer = new byte[ bufferLength ]; - this.position = 0; - this.lineLength = 0; + this.buffer = new byte[bufferLength]; + this.position = 0; + this.lineLength = 0; this.suspendEncoding = false; - this.b4 = new byte[4]; - this.options = options; - //this.alphabet = getAlphabet(options); - this.decodabet = getDecodabet(options); - } // end constructor - - + this.b4 = new byte[4]; + this.options = options; + // this.alphabet = getAlphabet(options); + this.decodabet = getDecodabet( options ); + } // end constructor + /** - * Writes the byte to the output stream after - * converting to/from Base64 notation. - * When encoding, bytes are buffered three - * at a time before the output stream actually - * gets a write() call. - * When decoding, bytes are buffered four - * at a time. - * + * Writes the byte to the output stream after converting to/from Base64 + * notation. When encoding, bytes are buffered three at a time before + * the output stream actually gets a write() call. When decoding, bytes + * are buffered four at a time. + * * @param theByte the byte to write * @since 1.3 */ - public void write(int theByte) throws java.io.IOException + public void write( int theByte ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theByte ); return; - } // end if: supsended - + } // end if: supsended + // Encode? if( encode ) { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) // Enough to encode. + buffer[position++] = (byte) theByte; + if( position >= bufferLength ) // Enough to encode. { out.write( encode3to4( b4, buffer, bufferLength, options ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { out.write( NEW_LINE ); lineLength = 0; - } // end if: end of line + } // end if: end of line position = 0; - } // end if: enough to output - } // end if: encoding + } // end if: enough to output + } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? - if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) + if( decodabet[theByte & 0x7f] > WHITE_SPACE_ENC ) { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) // Enough to output. + buffer[position++] = (byte) theByte; + if( position >= bufferLength ) // Enough to output. { int len = Base64.decode4to3( buffer, 0, b4, 0, options ); out.write( b4, 0, len ); - //out.write( Base64.decode4to3( buffer ) ); + // out.write( Base64.decode4to3( buffer ) ); position = 0; - } // end if: enough to output - } // end if: meaningful base64 character - else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) + } // end if: enough to output + } // end if: meaningful base64 character + else if( decodabet[theByte & 0x7f] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); - } // end else: not white space either - } // end else: decoding - } // end write - - - + } // end else: not white space either + } // end else: decoding + } // end write + /** - * Calls {@link #write(int)} repeatedly until <var>len</var> - * bytes are written. - * + * Calls {@link #write(int)} repeatedly until <var>len</var> bytes are + * written. + * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theBytes, off, len ); return; - } // end if: supsended - + } // end if: supsended + for( int i = 0; i < len; i++ ) { - write( theBytes[ off + i ] ); - } // end for: each byte written - - } // end write - - - + write( theBytes[off + i] ); + } // end for: each byte written + + } // end write + /** - * Method added by PHIL. [Thanks, PHIL. -Rob] - * This pads the buffer without closing the stream. + * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer + * without closing the stream. */ - public void flushBase64() throws java.io.IOException + public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position, options ) ); position = 0; - } // end if: encoding + } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); - } // end else: decoding - } // end if: buffer partially full + } // end else: decoding + } // end if: buffer partially full - } // end flush + } // end flush - - /** - * Flushes and closes (I think, in the superclass) the stream. - * + /** + * Flushes and closes (I think, in the superclass) the stream. + * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); - + buffer = null; - out = null; - } // end close - - - + out = null; + } // end close + /** - * Suspends encoding of the stream. - * May be helpful if you need to embed a piece of - * base640-encoded data in a stream. - * + * Suspends encoding of the stream. May be helpful if you need to embed + * a piece of base640-encoded data in a stream. + * * @since 1.5.1 */ - public void suspendEncoding() throws java.io.IOException + public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; - } // end suspendEncoding - - + } // end suspendEncoding + /** - * Resumes encoding of the stream. - * May be helpful if you need to embed a piece of - * base640-encoded data in a stream. - * + * Resumes encoding of the stream. May be helpful if you need to embed a + * piece of base640-encoded data in a stream. + * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; - } // end resumeEncoding - - - - } // end inner class OutputStream - - -} // end class Base64 + } // end resumeEncoding + + } // end inner class OutputStream + +} // end class Base64
jalkanen/Priha
367c8dd58214d27f75d8098172ecf8d0ab0a1dc2
Reworked the SNS reordering again, and clarified some edge cases. Passes now TCK.
diff --git a/ChangeLog b/ChangeLog index 84535a6..b32f53e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,521 @@ +2009-12-24 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.6.4 + + * Fixed some more issues with SNS reordering. This version now + passes the JSR-170 TCK with zero errors or failures. + + * Merry Christmas! + 2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.3 * Solved a fairly hairy graph matching issue in SimpleQueryProvider, and I think finally deep queries work as they are meant to work. Yay! 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.4 * Fixed a number of versioning unit tests by implementing Node.isCheckedOut()... 2008-10-06 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index d62399a..3643369 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,116 +1,116 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ - public static final int MINORREVISION = 3; + public static final int MINORREVISION = 4; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index d39f690..c9b76bb 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,1403 +1,1448 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; -import org.priha.core.locks.QLock; import org.priha.core.locks.LockManager; +import org.priha.core.locks.QLock; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; -import org.priha.path.Path.Component; -import org.priha.util.*; +import org.priha.util.LazyNodeIteratorImpl; +import org.priha.util.PropertyIteratorImpl; +import org.priha.util.QName; +import org.priha.util.TextUtil; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; /** * Implements a Node. This is one of the most heavy classes in Priha, with a lot * of stuff happening. The NodeImpl class does some basic caching for some state * objects, so keeping references can be faster in some cases. */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; /** * A compile-time flag for allowing/disallowing Same Name Sibling support. * addNode() will throw an exception if you disallow these. This is sometimes * useful for debugging. */ private static final boolean ALLOW_SNS = true; private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); /** * Creates a clone of the NodeImpl, and places it to the given Session * * @param original * @param session * @throws RepositoryException * @throws IllegalStateException * @throws ValueFormatException */ protected NodeImpl( NodeImpl original, SessionImpl session ) throws ValueFormatException, IllegalStateException, RepositoryException { super( original, session ); m_primaryType = original.m_primaryType; m_definition = original.m_definition; } protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { enterState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.enterState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.enterState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } /** * Returns a lazy iterator over the children of this Node. */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public PropertyIteratorImpl getProperties() throws RepositoryException { List<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( m_session.m_provider.getProperties(getInternalPath()) ); return new PropertyIteratorImpl( ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); pi.loadValue( vfi.createValue( uuid.toString() ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.enterState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } /** * Returns the UUID for this node. Utilizes an internal cache for the UUID, * so is fast after the first call. */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { // Fine, let's just fall through, and end up throwing an exception } } throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } /** * Returns true, if this Node has a child with the given QName. * * @param name A QName. * @return True, if there is a child by this name. * @throws RepositoryException */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); - - // - // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. - // - Path p = newOrder.remove(srcIndex); - if( dstIndex != -1 ) - newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); - else - newOrder.add(p); - + // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { - m_lockManager.moveLock(lock, dstPath); + m_lockManager.removeLock( lock ); } + // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { - int realidx = 1; - for( int i = 0; i < newOrder.size(); i++ ) + if( srcChildRelPath.indexOf('[') != -1 || hasNode(srcChildRelPath+"[2]" ) ) { - Path.Component qn = newOrder.get(i).getLastComponent(); - - // Is this the moved path or its SNS? We check just the QName part, not the index. - if( qn.getNamespaceURI().equals(srcPath.getLastComponent().getNamespaceURI()) && - qn.getLocalPart().equals(srcPath.getLastComponent().getLocalPart())) + // Yes, we are moving a SNS so this needs reordering. + Path tmpPath = getInternalPath().resolve( m_session, "priha:tmpmove" ); + + // First, store the old version + m_session.internalMove( srcPath, + tmpPath, + false ); + + String childName = srcChildRelPath.replaceAll( "\\[\\d+\\]", "" ); + + if( dstPath == null ) { - if( qn.getIndex() != realidx ) - { - System.out.println("Trying to reorder SNS... : "+qn); - QName q = qn.getQName(); - Component newName = new Component(q,realidx); + NodeIterator ni = getNodes(childName); + dstPath = getInternalPath().resolve( m_session, + childName+"["+ni.getSize()+"]" ); + } + + int dir; + int startIdx; + int endIdx; + if( srcPath.getLastComponent().getIndex() < dstPath.getLastComponent().getIndex() ) + { + // Moving stuff forwards + dir = -1; + startIdx = srcPath.getLastComponent().getIndex()+1; + endIdx = dstPath.getLastComponent().getIndex()+1; + } + else + { + dir = 1; + startIdx = srcPath.getLastComponent().getIndex()-1; + endIdx = dstPath.getLastComponent().getIndex()-1; + } + + for( int i = startIdx; i != endIdx; i -= dir ) + { + String oldName = childName + "[" + i + "]"; + String newName = childName + "[" + (i + dir) + "]"; + + System.out.println("Reordering SNS : "+oldName+" to "+newName); - Path path1 = getInternalPath().resolve(qn); - Path tmppath = getInternalPath().resolve(m_session,"priha:tmpmove"); - Path newPath = getInternalPath().resolve(newName); + Path path1 = getInternalPath().resolve(m_session,oldName); +// Path tmppath = getInternalPath().resolve(m_session,"priha:tmpmove"); + Path newPath = getInternalPath().resolve(m_session,newName); - m_session.rename( path1, tmppath.getLastComponent() ); - m_session.rename( newPath, path1.getLastComponent() ); - m_session.rename( tmppath, newName ); + m_session.internalMove( path1, newPath, false ); - int oldI = newOrder.indexOf(newPath); - Path oldP = newOrder.set(i,newPath); +// int oldI = newOrder.indexOf(newPath); + +// Path oldP = newOrder.set(newOrder.indexOf(path1),newPath); - newOrder.set(oldI, oldP); +// newOrder.set(oldI, oldP); - realidx++; - } } + + m_session.internalMove( tmpPath, + dstPath, + false ); + } + else + { + // + // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. + // + Path p = newOrder.remove(srcIndex); + if( dstIndex != -1 ) + newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); + else + newOrder.add(p); + } } finally { m_session.setSuper(isSuper); } + + // + // Lock back up + // + + if( lock != null ) + { + m_lockManager.moveLock( lock, dstPath ); + } + // // Finish. // enterState( ItemState.UPDATED ); m_childOrder = newOrder; } private PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ private PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); // prop.m_state = ItemState.NEW; // addChildProperty( prop ); // Again, a special case. First add the property to the lists. return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { // // Handle new property // Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); prop.m_isNew = true; // prop.setState( ItemState.NEW ); } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } else { // prop.setState( ItemState.UPDATED ); } if( value == null ) { removeProperty(prop); } else { //addChildProperty( prop ); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.enterState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); return prop; } public PropertyImpl setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } try { Value val = m_session.getValueFactory().createValue( value, type ); return setProperty( name, val ); } catch( ValueFormatException e ) { // This is kind of stupid to start throwing the same exception again. throw new ConstraintViolationException(e.getMessage()); } } public PropertyImpl setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException { if( m_session.hasPendingChanges() ) throw new InvalidItemStateException("A Session must not have unsaved changes prior to calling update()"); SessionImpl srcSession = m_session.getRepository().login(srcWorkspaceName); // FIXME: This should really reuse the Session somehow. Now we do two logins, one here // and one in getCorrespondingNodePath() try { String correspondingPath = getCorrespondingNodePath( srcWorkspaceName ); String destPath = getParent().getPath()+"/"+getName(); remove(); m_session.save(); m_session.getWorkspace().copy( srcSession, correspondingPath, destPath, true ); m_session.save(); } catch( ItemNotFoundException e ) { // Return quietly; nothing happens in this case. } finally { srcSession.logout(); } } public boolean isNode() { return true; } protected void internalSave() throws RepositoryException { m_session.saveNodes( getInternalPath() ); diff --git a/src/java/org/priha/core/SessionImpl.java b/src/java/org/priha/core/SessionImpl.java index 635e35c..88dca38 100644 --- a/src/java/org/priha/core/SessionImpl.java +++ b/src/java/org/priha/core/SessionImpl.java @@ -1,790 +1,812 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.AccessControlException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import javax.xml.parsers.ParserConfigurationException; import org.priha.core.locks.QLock; import org.priha.core.locks.LockManager; import org.priha.core.namespace.NamespaceMapper; import org.priha.core.values.ValueFactoryImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.PathManager; import org.priha.path.PathRef; import org.priha.path.Path.Component; import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.xml.*; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * The SessionImpl class implements a JCR Session. It is non thread safe, * so each Thread must have its own Session. */ public class SessionImpl implements Session, NamespaceMapper { static final String PRIHA_OLD_PATH = "priha:oldPath"; private static final String JCR_SYSTEM = "jcr:system"; /** * This is a magical property which gets added to a Node whenever * a move occurs. It's value is a Path which points from source to target * and target to source nodes which have been saved - it's point is * to make sure that the user will save both the source and the target * at the same time. This property is never saved to the Provider. */ static final String MOVE_CONSTRAINT = "priha:moveConstraint"; private RepositoryImpl m_repository; private WorkspaceImpl m_workspace; private List<String> m_lockTokens = new ArrayList<String>(); private SimpleCredentials m_credentials; private Logger log = Logger.getLogger( getClass().getName() ); private boolean m_isSuperSession = false; private ValueFactoryImpl m_valueFactory = new ValueFactoryImpl(this); protected SessionProvider m_provider; public SessionImpl( RepositoryImpl rep, Credentials creds, String name ) throws RepositoryException { m_repository = rep; m_workspace = new WorkspaceImpl( this, name, rep.getProviderManager() ); m_provider = new SessionProvider( this, rep.getProviderManager() ); if( creds instanceof SimpleCredentials ) { m_credentials = (SimpleCredentials)creds; } if( !hasNode("/") ) { repopulate(); } } public boolean setSuper(boolean value) { boolean oldval = m_isSuperSession; m_isSuperSession = value; return oldval; } /** * Returns true, if this Session should be considered to be a supersession, * which can do whatever it wants (that is, mostly ignore any Constraint Violations. * <p> * One should be careful, since it is possible with this method to end up in * a repository with an inconsistent state. * * @return */ public boolean isSuper() { return m_isSuperSession; } public List<Path> listNodes( Path parentpath ) throws RepositoryException { return m_provider.listNodes(parentpath); } boolean hasNode( String absPath ) throws RepositoryException { return hasNode( PathFactory.getPath(this,absPath) ); } public boolean hasNode( Path absPath ) throws RepositoryException { checkLive(); return m_provider.nodeExists( absPath ); } boolean hasProperty( Path absPath ) throws RepositoryException { checkLive(); try { ItemImpl ii = m_provider.getItem(absPath); if( ii.getState() == ItemState.REMOVED ) return false; if( !ii.isNode() ) return true; } catch( PathNotFoundException e) {} catch( ItemNotFoundException e) {} return false; } public void addLockToken(String lt) { m_lockTokens.add(lt); } /** * Any credentials are fine to give full access. */ public void checkPermission(String absPath, String actions) throws AccessControlException, RepositoryException { checkLive(); actions = actions.trim(); if( actions.equals( "read" ) ) return; if( m_credentials == null && !isSuper() ) throw new AccessControlException("Read-only session"); return; } /** Quick way to check for write permissions. */ protected void checkWritePermission() throws AccessControlException, RepositoryException { try { checkPermission("/","add_node"); } catch( AccessControlException e ) { throw new AccessDeniedException(e.getMessage()); } } public Object getAttribute(String name) { Object res = null; if( m_credentials != null ) { res = m_credentials.getAttribute(name); } return res; } public String[] getAttributeNames() { if( m_credentials != null ) { return m_credentials.getAttributeNames(); } return new String[0]; } public ItemImpl getItem( Path absPath ) throws PathNotFoundException, RepositoryException { checkLive(); ItemImpl ii = m_provider.getItem( absPath ); return ii; } public ItemImpl getItem(String absPath) throws PathNotFoundException, RepositoryException { return getItem( PathFactory.getPath(this,absPath) ); } public String[] getLockTokens() { return m_lockTokens.toArray( new String[m_lockTokens.size()] ); } public NodeImpl getNodeByUUID(String uuid) throws ItemNotFoundException, RepositoryException { checkLive(); return m_provider.findByUUID(uuid); } public RepositoryImpl getRepository() { return m_repository; } public NodeImpl getRootNode() throws RepositoryException { return (NodeImpl) getItem(Path.ROOT); } public String getUserID() { return "anonymous"; } public ValueFactoryImpl getValueFactory() throws UnsupportedRepositoryOperationException, RepositoryException { checkLive(); return m_valueFactory; } public WorkspaceImpl getWorkspace() { return m_workspace; } public boolean hasPendingChanges() throws RepositoryException { checkLive(); return m_provider.hasPendingChanges(); } public Session impersonate(Credentials credentials) throws LoginException, RepositoryException { checkLive(); return m_repository.login( credentials, getWorkspace().getName() ); } public final boolean isLive() { return m_workspace != null; } private final void checkLive() throws RepositoryException { if( !isLive() ) throw new RepositoryException("This Session is no longer live and cannot be used."); } public boolean itemExists(String absPath) throws RepositoryException { checkLive(); return itemExists( PathFactory.getPath(this,absPath) ); } public void logout() { if( isLive() ) { m_repository.removeSession(this); LockManager.getInstance(m_workspace).expireSessionLocks( this ); m_workspace.logout(); m_workspace = null; } } + /** + * A convenience class to move stuff based on Paths instead of Strings. + */ + public void move( Path srcPath, Path destPath ) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, NamespaceException, RepositoryException + { + // FIXME: This should really be the main routine + move( srcPath.toString( this ), destPath.toString(this) ); + } + + public void move(String srcAbsPath, String destAbsPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException + { + checkLive(); + checkWritePermission(); + + internalMove(srcAbsPath,destAbsPath,true); + } + + public void internalMove( Path srcPath, Path destPath, boolean obeyConstraints ) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, NamespaceException, RepositoryException + { + // FIXME: This should really be the main routine + internalMove( srcPath.toString( this ), destPath.toString(this), obeyConstraints ); + } + /** * Moves work as follows: * <ol> * <li>We add a new Node to the destAbsPath * <li>We copy all properties from the old Node to the new Node * <li>The old Node gets tagged with a property "priha:oldPath" which contains the current path * <li>The Path of the old Node (and all other Nodes which refer to it) is changed to point at the new location * <li>The Node is marked as being MOVED instead of REMOVED. * </ol> */ - public void move(String srcAbsPath, String destAbsPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException + public void internalMove(String srcAbsPath, String destAbsPath, boolean obeyConstraints) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { - checkLive(); - checkWritePermission(); - System.out.println("Moving "+srcAbsPath+" to "+destAbsPath); - if( destAbsPath.endsWith("]") && !isSuper() ) throw new ConstraintViolationException("Destination path must not have an index as its final component."); boolean isSuper = setSuper( true ); try { Path path = PathFactory.getPath( this, destAbsPath ); if( m_workspace.isCheckedIn( (NodeImpl)getItem(path.getParentPath()) ) ) throw new VersionException("Versioned node checked in"); if( hasNode( path ) ) { throw new ItemExistsException("Destination node "+getWorkspace().getName()+":"+path.toString(this)+" already exists!"); } NodeImpl srcnode = getRootNode().getNode(srcAbsPath); String newDestPath = destAbsPath; LockManager lm = LockManager.getInstance( m_workspace ); if( lm.findLock( srcnode.getParent().getInternalPath() ) != null ) throw new LockException( "Lock on source path prevents move" ); QLock lock = lm.findLock( srcnode.getInternalPath() ); if( lock != null ) lm.moveLock( lock, PathFactory.getPath(newDestPath) ); NodeImpl destnode = getRootNode().addNode( newDestPath, srcnode.getPrimaryNodeType().getName() ); destnode.tag( PRIHA_OLD_PATH, srcnode.getPath() ); for( NodeIterator ni = srcnode.getNodes(); ni.hasNext(); ) { Node child = ni.nextNode(); String relPath = child.getName(); String newPath = destAbsPath + "/" + relPath; System.out.println("Child path move "+child.getPath()+" => "+newPath ); - move( child.getPath(), newPath ); + internalMove( child.getPath(), newPath, obeyConstraints ); } for( PropertyIterator pi = srcnode.getProperties(); pi.hasNext(); ) { PropertyImpl p = (PropertyImpl)pi.nextProperty(); // newDestPath = destAbsPath + "/" + nd.getName() + "/" + // p.getName(); // System.out.println(" property "+p.getPath()+" ==> "+newDestPath // ); // Primary type has already been set, so we won't move that. if( !p.getName().equals( "jcr:primaryType" ) ) { if( p.getDefinition().isMultiple() ) { PropertyImpl pix = destnode.internalSetProperty( p.getQName(), p.getValues(), p.getType() ); pix.enterState( ItemState.NEW ); } else { destnode.setProperty( p.getName(), p.getValue() ); } } p.remove(); } // Set up move constraints (that is, making sure the user can only save // a top node, and not just moved bits). - srcnode.getParent().tag( MOVE_CONSTRAINT, destnode.getParent().getPath() ); - destnode.getParent().tag( MOVE_CONSTRAINT, srcnode.getParent().getPath() ); + if( obeyConstraints ) + { + srcnode.getParent().tag( MOVE_CONSTRAINT, destnode.getParent().getPath() ); + destnode.getParent().tag( MOVE_CONSTRAINT, srcnode.getParent().getPath() ); + } // Since this is a move op, we want to make sure that the old path // does not change. //srcnode.freezePath(); // Finally, remove the source node. //srcnode.remove(); srcnode.enterState( ItemState.MOVED ); // m_provider.remove( srcnode ); // FIXME: Make sure this is ok getPathManager().move( srcnode.getInternalPath(), destnode.getInternalPath() ); // FIXME: OK with new ChangeStore? } finally { setSuper( isSuper ); } } - + void refresh( boolean keepChanges, Path path ) throws RepositoryException { checkLive(); m_provider.refresh( keepChanges, path ); } public void refresh(boolean keepChanges) throws RepositoryException { refresh( keepChanges, Path.ROOT ); } /** * This method makes sure that certain default stuff is available. * @throws RepositoryException */ private void repopulate() throws RepositoryException { boolean isSuper = setSuper(true); if( !hasNode("/") ) { NodeImpl ni = null; log.info("Repository empty; setting up root node..."); QNodeType rootType = getWorkspace().getNodeTypeManager().getNodeType("nt:unstructured").getQNodeType(); QNodeDefinition nd = rootType.findNodeDefinition( QName.valueOf("*") ); ni = new NodeImpl( this, "/", rootType, nd, true ); ni.enterState( ItemState.NEW ); ni.addMixin( "mix:referenceable" ); // Make referenceable. //m_provider.addNode( ni ); ni.sanitize(); save(); } if( !hasNode("/"+JCR_SYSTEM) ) { getRootNode().addNode(JCR_SYSTEM, "nt:unstructured"); // FIXME: Should probably set up all sorts of things. save(); } setSuper(isSuper); } public void removeLockToken(String lt) { m_lockTokens.remove(lt); } public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException { saveNodes( Path.ROOT ); } /** * Saves all modified nodes that start with the given path prefix. This * can be used to save a node and all its children. * * @param pathprefix * @throws RepositoryException */ protected void saveNodes( Path pathprefix ) throws RepositoryException { checkLive(); checkWritePermission(); m_provider.save( pathprefix ); } public boolean itemExists( Path absPath ) throws RepositoryException { return hasNode(absPath) || hasProperty(absPath); } public void remove(ItemImpl itemImpl) throws RepositoryException { checkLive(); checkWritePermission(); m_provider.remove( itemImpl ); } public List<PropertyImpl> getReferences(String uuid) throws RepositoryException { checkLive(); return m_provider.getReferences( uuid ); } /* ========================================================================= */ /* XML import/export */ public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, VersionException, InvalidSerializedDataException, LockException, RepositoryException { checkLive(); checkWritePermission(); XMLImport importer = new XMLImport( this, false, PathFactory.getPath(this,parentAbsPath), uuidBehavior ); try { importer.doImport( in ); } catch (ParserConfigurationException e) { log.log( Level.WARNING, "Could not get SAX parser", e ); throw new RepositoryException("Could not get SAX parser, please check logs."); } catch (SAXException e) { log.log( Level.WARNING, "Importing failed", e ); if( e.getException() != null && e.getException() instanceof RepositoryException ) throw (RepositoryException) e.getException(); throw new InvalidSerializedDataException("Importing failed: "+e.getMessage()); } } public ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, RepositoryException { XMLImport importer = new XMLImport( this, false, PathFactory.getPath(this,parentAbsPath), uuidBehavior ); return importer; } public void exportDocumentView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse) throws PathNotFoundException, SAXException, RepositoryException { checkLive(); XMLExport export = new XMLDocExport(this); export.export( absPath, contentHandler, skipBinary, noRecurse ); } public void exportDocumentView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse) throws IOException, PathNotFoundException, RepositoryException { checkLive(); XMLExport export = new XMLDocExport( this ); ContentHandler handler = new StreamContentHandler( out ); try { export.export( absPath, handler, skipBinary, noRecurse ); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void exportSystemView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse) throws PathNotFoundException, SAXException, RepositoryException { checkLive(); XMLExport export = new XMLSysExport( this ); export.export( absPath, contentHandler, skipBinary, noRecurse ); } public void exportSystemView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse) throws IOException, PathNotFoundException, RepositoryException { checkLive(); XMLExport export = new XMLSysExport( this ); ContentHandler handler = new StreamContentHandler( out ); try { export.export( absPath, handler, skipBinary, noRecurse ); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* ========================================================================= */ /* Namespaces */ /** Maps prefixes to URIs. Prefixes are always unique, therefore they are the keys */ private HashMap<String,String> m_nsmap = new HashMap<String,String>(); public void setNamespacePrefix(String newPrefix, String existingUri) throws NamespaceException, RepositoryException { checkLive(); // Throws an exception if the URI does not exist, so this is a cheap way to check for validity. m_workspace.getNamespaceRegistry().getPrefix(existingUri); if( newPrefix.toLowerCase().startsWith("xml") ) throw new NamespaceException("No namespace starting with 'xml' may be remapped (6.3.3)"); String currentUri = null; try { currentUri = m_workspace.getNamespaceRegistry().getURI( newPrefix ); } catch( NamespaceException e ) {} if( currentUri != null && currentUri.equals(existingUri) ) { throw new NamespaceException("Existing prefix cannot be remapped (6.3.3)"); } PathFactory.reset(); m_nsmap.put(newPrefix, existingUri ); } public String getNamespacePrefix(String uri) throws NamespaceException, RepositoryException { checkLive(); for( Map.Entry<String, String> e : m_nsmap.entrySet() ) { if( e.getValue().equals( uri ) ) return e.getKey(); } return m_workspace.getNamespaceRegistry().getPrefix(uri); } public String[] getNamespacePrefixes() throws RepositoryException { checkLive(); Set<String> prefixes = new TreeSet<String>(); Set<String> uris = new TreeSet<String>(); uris.addAll( m_nsmap.values() ); uris.addAll( Arrays.asList( m_workspace.getNamespaceRegistry().getURIs() ) ); for( String u : uris ) { prefixes.add( getNamespacePrefix( u ) ); } return prefixes.toArray( new String[prefixes.size()] ); } public String getNamespaceURI(String prefix) throws NamespaceException, RepositoryException { checkLive(); String uri = m_nsmap.get(prefix); if( uri == null ) { return m_workspace.getNamespaceRegistry().getURI(prefix); } return uri; } public String fromQName(QName c) { if( c == null ) return null; try { String uri = c.getNamespaceURI(); if( uri.length() > 0 ) { String prefix = getNamespacePrefix( uri ); return prefix+":"+c.getLocalPart(); } } catch( Exception e ) { } return c.getLocalPart(); } public QName toQName(String c) throws NamespaceException, RepositoryException { checkLive(); if( c == null ) return null; if( c.indexOf( '{' ) != -1 ) throw new RepositoryException("Already in QName format: "+c); int idx = c.indexOf(':'); if( idx != -1 ) { String prefix = c.substring(0,idx); String name = c.substring(idx+1); String uri = getNamespaceURI( prefix ); return new QName( uri, name, prefix ); } return new QName(c); } /** * This method creates a correct Node subclass based on the NodeType. It * can return Version or VersionHistory objects, as well as regular Nodes. * * @param absPath * @param assignedType * @param assignedNodeDef * @return * @throws RepositoryException */ protected NodeImpl createNode(Path absPath, QNodeType assignedType, QNodeDefinition assignedNodeDef, boolean initDefaults) throws RepositoryException { NodeImpl ni; if( assignedType.isNodeType(JCRConstants.Q_NT_VERSION) ) { ni = new VersionImpl( this, absPath, assignedType, assignedNodeDef, initDefaults ); } else if( assignedType.isNodeType(JCRConstants.Q_NT_VERSIONHISTORY) ) { ni = new VersionHistoryImpl( this, absPath, assignedType, assignedNodeDef, initDefaults ); } else { ni = new NodeImpl( this, absPath, assignedType, assignedNodeDef, initDefaults ); } return ni; } public String toString() { return "Session["+(isSuper()?"SUPER":"")+"]"; } /** * This method provides debug information about the state of the Session. Do not rely * it giving it in any particular format. The dump will be done to the System.out stream. */ public void dump() { System.out.println(this); m_provider.m_changedItems.dump(); } /** * Shortcut for getPathManager().getPath(). * @param p * @return * @throws PathNotFoundException */ public Path getPath(PathRef p) throws PathNotFoundException { return m_provider.getPath( p ); } public PathManager getPathManager() { return m_provider.getPathManager(); } public void rename(Path path1, Component newName) { System.out.println("Renaming "+path1+" to "+newName); } } diff --git a/src/java/org/priha/core/locks/LockManager.java b/src/java/org/priha/core/locks/LockManager.java index 3a3731a..ff0e656 100644 --- a/src/java/org/priha/core/locks/LockManager.java +++ b/src/java/org/priha/core/locks/LockManager.java @@ -1,185 +1,190 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core.locks; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Logger; import javax.jcr.Workspace; import org.priha.core.SessionImpl; import org.priha.core.WorkspaceImpl; import org.priha.path.InvalidPathException; import org.priha.path.Path; /** * A LockManager exists per static workspace. This means that it * manages *all* the locks for a given workspace, regardless of the * Session which accesses it. */ // FIXME: This class should avoid synchronization as much as possible. public class LockManager { private static HashMap<String,LockManager> m_lockManagers = new HashMap<String,LockManager>(); private HashMap<Path,QLock> m_locks = new HashMap<Path,QLock>(); //private String m_workspace; private Logger log = Logger.getLogger( LockManager.class.getName() ); private SessionImpl m_session; private LockManager(WorkspaceImpl ws) { m_session = ws.getSession(); } public synchronized void addLock( QLock lock ) { m_locks.put( lock.getPath(), lock ); } /** * Checks if the object at this path holds a lock. * * @param path * @return */ public synchronized QLock getLock( Path path ) { QLock lock = m_locks.get(path); return lock; } /** * Checks if the object at this path or any object above it * holds a lock. * * @param path * @return */ public synchronized QLock findLock( Path path ) { boolean deepRequired = false; while( !path.isRoot() ) { QLock li = m_locks.get( path ); if( li != null ) { if( deepRequired && li.isDeep() ) return li; // new QLock(li,m_session); else if( !deepRequired ) return li; // new QLock(li,m_session); } try { path = path.getParentPath(); deepRequired = true; } catch (InvalidPathException e) { log.warning("Internal error: "+e.getMessage()); } } return null; } /** * This method must be used to access a LockManager. * * @param ws * @return */ public static synchronized LockManager getInstance(WorkspaceImpl ws) { LockManager lm = m_lockManagers.get(ws.getName()); if( lm == null ) { lm = new LockManager( ws ); m_lockManagers.put( ws.getName(), lm ); } return lm; } public synchronized void expireSessionLocks( SessionImpl session ) { for( Iterator<Map.Entry<Path,QLock>> i = m_locks.entrySet().iterator(); i.hasNext(); ) { Map.Entry<Path,QLock> e = i.next(); QLock li = e.getValue(); if( li.expire(session) ) { // i.remove(); } } } /** * Updates a lock with a new path. * * @param lock Lock to change. * @param destPath New path. */ public synchronized void moveLock(QLock lock, Path destPath) { System.out.println("Moving lock from "+lock.getPath()+" to "+destPath); removeLock(lock); lock.move(destPath); addLock(lock); } + /** + * Removes the lock, if it exists. + * + * @param lock Lock to remove. + */ public synchronized void removeLock(QLock lock) { m_locks.remove(lock.getPath()); } /** * Checks if any of the children of this Node hold a lock * to which the session does not hold a key to. * * @param internalPath * @return */ public synchronized boolean hasChildLock(Path internalPath) { for( Path p : m_locks.keySet() ) { //TODO Slightly unoptimal if( internalPath.isParentOf(p) ) { /* QLock li = m_locks.get(p); if( li.getLockToken() == null && li.isSessionScoped() ) return true; */ return true; } } return false; } }
jalkanen/Priha
2778f1323e3f59b295559d1ac7c71de73cfe68a7
Rewrote LocationStepQueryNode and PathStepQueryNode handling in such a way that we first collect potential matches at every step, narrowing down until we have a final set of matches. This solves quite a few deep query problems, as it's considerably simpler than what we were doing. Bah, too clever for my own good. It's really just a simple graph matching exercise...
diff --git a/ChangeLog b/ChangeLog index 694731f..84535a6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,519 @@ +2009-12-23 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.6.3 + + * Solved a fairly hairy graph matching issue in SimpleQueryProvider, + and I think finally deep queries work as they are meant to work. Yay! + 2009-12-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.2 * Rewrote ItemState handling to clean up some cases where ChangeStore got awfully confused as to when something was updated or not. This also fixes some problems with SNS handling, which isn't still perfect though. It also changes reliability of multiple move()s in a single Session. 2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> * Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip. * Bug 6: compile and compiletests -targets had wrong dirsets. Thanks to Kees Kuip pointing this out. * ant clean would also delete generated sources - needing a svn update. Now fixed. 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.4 * Fixed a number of versioning unit tests by implementing Node.isCheckedOut()... 2008-10-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.3 * Massive reoptimization of FileProvider to do reference management properly. This also meant some additions to the Provider API. 2008-10-01 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 151caa7..d62399a 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,116 +1,116 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ - public static final int MINORREVISION = 2; + public static final int MINORREVISION = 3; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/query/PrihaQueryManager.java b/src/java/org/priha/query/PrihaQueryManager.java index b17d42e..017b648 100644 --- a/src/java/org/priha/query/PrihaQueryManager.java +++ b/src/java/org/priha/query/PrihaQueryManager.java @@ -1,90 +1,84 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.query; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import org.priha.core.SessionImpl; -import org.priha.query.aqt.DefaultQueryNodeFactory; -import org.priha.query.aqt.QueryRootNode; -import org.priha.query.aqt.xpath.XPathQueryBuilder; /** * Manages our Provider modules and provides the QueryManager interface. * * @author Janne Jalkanen */ public class PrihaQueryManager implements QueryManager { private static final String[] SUPPORTEDLANGUAGES = { Query.XPATH }; - private static final String DEFAULT_QUERYPROVIDER = "org.priha.BasicQueryProvider"; - - private QueryProvider m_queryProvider; - private SessionImpl m_session; public PrihaQueryManager( SessionImpl session ) { m_session = session; } /** * Get the QueryProvider which will be used to resolve the actual query. * * @return A QueryProvider instance. */ protected QueryProvider getQueryProvider() { return new SimpleQueryProvider(); } public Query createQuery(String statement, String language) throws InvalidQueryException, RepositoryException { if( language.equals( Query.XPATH ) ) { + /* QueryRootNode root = XPathQueryBuilder.createQuery(statement, m_session, new DefaultQueryNodeFactory(null) ); - + */ return new XPathQueryImpl( m_session, statement ); } throw new InvalidQueryException("Query language "+language+" is not supported."); } public Query getQuery(Node node) throws InvalidQueryException, RepositoryException { if( !node.isNodeType( "nt:query" ) ) throw new InvalidQueryException("Node is not of type 'nt:query'"); return createQuery( node.getProperty( "jcr:statement" ).getString(), node.getProperty( "jcr:language" ).getString() ); } public String[] getSupportedQueryLanguages() throws RepositoryException { return SUPPORTEDLANGUAGES; } } diff --git a/src/java/org/priha/query/QueryImpl.java b/src/java/org/priha/query/QueryImpl.java index fe520a6..fc97b3e 100644 --- a/src/java/org/priha/query/QueryImpl.java +++ b/src/java/org/priha/query/QueryImpl.java @@ -1,70 +1,72 @@ package org.priha.query; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.query.Query; import javax.jcr.query.QueryResult; import javax.jcr.version.VersionException; import org.priha.core.SessionImpl; import org.priha.query.aqt.QueryRootNode; /** * The root class for Priha query implementations. * * @author Janne Jalkanen */ public abstract class QueryImpl implements Query { private QueryRootNode m_root; private SessionImpl m_session; private String m_storedQueryPath = null; /** * Construct a QueryImpl for a given Session and a given abstract * query tree. Subclasses are expected to create the AQT. * * @param session The Session against which this Query is created * @param root The AQT Root node */ public QueryImpl(SessionImpl session, QueryRootNode root) { m_session = session; m_root = root; } public QueryResult execute() throws RepositoryException { QueryProvider qp = m_session.getWorkspace().getQueryManager().getQueryProvider(); + System.out.println( "Executing "+getStatement() ); + return qp.query(m_session, m_root); } public String getStoredQueryPath() throws ItemNotFoundException, RepositoryException { if( m_storedQueryPath == null ) throw new ItemNotFoundException("This is not a stored query"); return m_storedQueryPath; } public Node storeAsNode(String absPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, UnsupportedRepositoryOperationException, RepositoryException { Node queryNode = m_session.getRootNode().addNode( absPath, "nt:query" ); queryNode.setProperty( "jcr:statement", getStatement() ); queryNode.setProperty( "jcr:language", getLanguage() ); m_storedQueryPath = queryNode.getPath(); return queryNode; } } diff --git a/src/java/org/priha/query/SimpleQueryProvider.java b/src/java/org/priha/query/SimpleQueryProvider.java index 082da8b..04a2475 100644 --- a/src/java/org/priha/query/SimpleQueryProvider.java +++ b/src/java/org/priha/query/SimpleQueryProvider.java @@ -1,850 +1,888 @@ package org.priha.query; import java.io.IOException; import java.util.*; import javax.jcr.*; import javax.jcr.query.QueryResult; import org.priha.core.*; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.Path; import org.priha.query.aqt.*; import org.priha.query.aqt.OrderQueryNode.OrderSpec; -import org.priha.util.NodeIteratorImpl; import org.priha.util.QName; /** * This class provides a very simple query provider which does direct * comparisons against the contents of the repository. The upside is that this * makes it very simple; with the obvious downside that this is really slow * because it traverses the entire repository one matched Node at a time. * * @author Janne Jalkanen */ public class SimpleQueryProvider extends TraversingQueryNodeVisitor implements QueryProvider { public QueryResult query( SessionImpl session, QueryRootNode root ) throws RepositoryException { QueryCollector c = new QueryCollector(); c.setCurrentItem( session.getRootNode() ); visit( root, c ); System.out.println( root.dump() ); /* * if( c.m_matches.size() == 0 ) System.out.println("No matches"); for( * ItemImpl ii : c.m_matches ) { System.out.println(ii); } */ System.out.println( "---" ); for( ItemImpl ii : c.m_matches ) { System.out.println( ii ); } if( root.getOrderNode() != null ) { Collections.sort( c.m_matches, new QuerySorter( root.getOrderNode() ) ); System.out.println( "+++" ); for( ItemImpl ii : c.m_matches ) { System.out.println( ii ); } } // // Figure out which columns were selected. // List<QName> columns = new ArrayList<QName>(); columns.addAll( Arrays.asList( root.getSelectProperties() ) ); // Shamelessly lifted from Jackrabbit :-) if( columns.size() == 0 ) { // use node type constraint LocationStepQueryNode[] steps = root.getLocationNode().getPathSteps(); final QName[] ntName = new QName[1]; steps[steps.length - 1].acceptOperands( new DefaultQueryNodeVisitor() { public Object visit( AndQueryNode node, Object data ) throws RepositoryException { return node.acceptOperands( this, data ); } public Object visit( NodeTypeQueryNode node, Object data ) { ntName[0] = node.getValue(); return data; } }, null ); if( ntName[0] == null ) { ntName[0] = JCRConstants.Q_NT_BASE; } QNodeType nt = QNodeTypeManager.getInstance().getNodeType( ntName[0] ); QPropertyDefinition[] propDefs = nt.getQPropertyDefinitions(); for( QPropertyDefinition propDef : propDefs ) { if( !propDef.isWildCard() && !propDef.isMultiple() ) { columns.add( propDef.getQName() ); } } } return new QueryResultImpl( c.m_matches, columns ); } @Override public Object visit( AndQueryNode node, Object data ) throws RepositoryException { QueryCollector c = (QueryCollector) data; QueryNode[] operands = node.getOperands(); for( int i = 0; i < operands.length; i++ ) { c = (QueryCollector) operands[i].accept( this, c ); // Stop at the first sign of non-match if( c == null ) return null; } return c; } @Override public Object visit( OrderQueryNode node, Object data ) throws RepositoryException { // TODO Auto-generated method stub return super.visit( node, data ); } @Override public Object visit( PathQueryNode node, Object data ) throws RepositoryException { LocationStepQueryNode[] steps = node.getPathSteps(); QueryCollector c = (QueryCollector) data; try { + ArrayList<NodeImpl> nodesToBeChecked = new ArrayList<NodeImpl>(); + + // Start with a single item + nodesToBeChecked.add( c.getCurrentItem() ); + for( int i = 0; i < steps.length; i++ ) { if( i == steps.length - 1 ) c.setLast(true); - c = (QueryCollector) steps[i].accept( this, c ); + + for( NodeImpl ni : nodesToBeChecked ) + { + c.setCurrentItem( ni ); + + c = (QueryCollector) steps[i].accept( this, c ); + } + nodesToBeChecked.clear(); + nodesToBeChecked.addAll( c.m_matches ); + c.m_matches.clear(); } + + c.m_matches = nodesToBeChecked; // Should be the final list of matches } catch( PathNotFoundException e ) { // No matches is found c.m_matches.clear(); } return c; } /** * Is used to evaluate a single Value against a constraint. */ private interface OperationResolver { public Boolean eval( Value value ) throws RepositoryException; } /** * Evaluates all values of the given property using the given * OperationResolver and returns a logical OR of the results. */ private Boolean resolveOp( PropertyImpl prop, OperationResolver resolver ) throws ValueFormatException, RepositoryException { Boolean result = false; if( prop.getDefinition().isMultiple() ) { for( Value v : prop.getValues() ) { result |= resolver.eval( v ); } } else { result = resolver.eval( prop.getValue() ); } return result; } @Override public Object visit( final RelationQueryNode node, Object data ) throws RepositoryException { Path relPath = node.getRelativePath(); QueryCollector qc = (QueryCollector) data; Boolean result = false; PropertyImpl prop = null; NodeImpl currNode = qc.getCurrentItem(); if( currNode.hasProperty( relPath.toString() ) ) { prop = currNode.getProperty( relPath.toString() ); } switch( node.getOperation() ) { case QueryConstants.OPERATION_NOT_NULL: result = (prop != null); break; case QueryConstants.OPERATION_GT_VALUE: case QueryConstants.OPERATION_GT_GENERAL: if( prop != null ) { switch( node.getValueType() ) { case QueryConstants.TYPE_DOUBLE: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDouble() > node.getDoubleValue(); } } ); break; case QueryConstants.TYPE_LONG: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getLong() > node.getLongValue(); } } ); break; case QueryConstants.TYPE_STRING: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getString().compareTo( node.getStringValue() ) > 0; } } ); break; case QueryConstants.TYPE_DATE: case QueryConstants.TYPE_TIMESTAMP: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDate().getTime().after( node.getDateValue() ); } } ); break; } } break; case QueryConstants.OPERATION_EQ_VALUE: case QueryConstants.OPERATION_EQ_GENERAL: if( prop != null ) { switch( node.getValueType() ) { case QueryConstants.TYPE_LONG: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getLong() == node.getLongValue(); } } ); break; case QueryConstants.TYPE_DOUBLE: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return (value.getDouble() - node.getDoubleValue()) < 1e-12; } } ); break; case QueryConstants.TYPE_STRING: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getString().equals( node.getStringValue() ); } } ); break; case QueryConstants.TYPE_DATE: case QueryConstants.TYPE_TIMESTAMP: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDate().getTime().compareTo( node.getDateValue() ) == 0; } } ); break; } } break; case QueryConstants.OPERATION_LT_VALUE: case QueryConstants.OPERATION_LT_GENERAL: if( prop != null ) { switch( node.getValueType() ) { case QueryConstants.TYPE_LONG: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getLong() < node.getLongValue(); } } ); break; case QueryConstants.TYPE_DOUBLE: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDouble() < node.getDoubleValue(); } } ); break; case QueryConstants.TYPE_STRING: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getString().compareTo( node.getStringValue() ) < 0; } } ); break; case QueryConstants.TYPE_DATE: case QueryConstants.TYPE_TIMESTAMP: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDate().getTime().before( node.getDateValue() ); } } ); break; } } break; case QueryConstants.OPERATION_GE_VALUE: case QueryConstants.OPERATION_GE_GENERAL: if( prop != null ) { switch( node.getValueType() ) { case QueryConstants.TYPE_LONG: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getLong() >= node.getLongValue(); } } ); break; case QueryConstants.TYPE_DOUBLE: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDouble() >= node.getDoubleValue(); } } ); break; case QueryConstants.TYPE_STRING: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getString().compareTo( node.getStringValue() ) >= 0; } } ); break; case QueryConstants.TYPE_DATE: case QueryConstants.TYPE_TIMESTAMP: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDate().getTime().compareTo( node.getDateValue() ) >= 0; } } ); break; } } break; case QueryConstants.OPERATION_LE_VALUE: case QueryConstants.OPERATION_LE_GENERAL: if( prop != null ) { switch( node.getValueType() ) { case QueryConstants.TYPE_LONG: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getLong() <= node.getLongValue(); } } ); break; case QueryConstants.TYPE_DOUBLE: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDouble() <= node.getDoubleValue(); } } ); break; case QueryConstants.TYPE_STRING: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getString().compareTo( node.getStringValue() ) <= 0; } } ); break; case QueryConstants.TYPE_DATE: case QueryConstants.TYPE_TIMESTAMP: result = resolveOp( prop, new OperationResolver() { public Boolean eval( Value value ) throws ValueFormatException, IllegalStateException, RepositoryException { return value.getDate().getTime().compareTo( node.getDateValue() ) <= 0; } } ); break; } } break; case QueryConstants.OPERATION_NULL: result = prop == null; break; default: throw new UnsupportedRepositoryOperationException( "Unknown operation " + node.getOperation() ); } return result ? qc : null; } @Override public Object visit( LocationStepQueryNode node, Object data ) throws RepositoryException { QName checkedName = node.getNameTest(); QueryCollector c = (QueryCollector) data; NodeImpl currNode = c.getCurrentItem(); System.out.println("LOC = "+currNode+", check="+checkedName); + // // If there is a named path component, then check that one. // If there isn't, then check all children. // if( checkedName != null ) { // Check if a child by this name exists. // Also include same name siblings. if( checkedName.getLocalPart().length() == 0 ) { // Root node - c.setCurrentItem( currNode ); - if( c.isLast() && checkPredicates( node, c ) ) + if( checkPredicates( node, c ) ) { c.addMatch( currNode ); + System.out.println(" MATCH"); } } else if( currNode.hasNode( checkedName ) ) { - System.out.println("XXX"); for( NodeIterator iter = currNode.getNodes( currNode.getSession().fromQName( checkedName ) ); iter.hasNext(); ) { NodeImpl ni = (NodeImpl)iter.nextNode(); - c.setCurrentItem( ni ); - - if( c.isLast() && checkPredicates( node, c ) ) + if( checkPredicates( node, c ) ) { c.addMatch( ni ); System.out.println(" MATCH"); } } } // // If required, perform also the same check to all descendants of // the current node. // if( node.getIncludeDescendants() ) { for( NodeIterator iter = currNode.getNodes(); iter.hasNext(); ) { NodeImpl child = (NodeImpl)iter.nextNode(); c.setCurrentItem( child ); visit( node, c ); } } } else { // // It is required to match all of the children. // for( NodeIterator iter = currNode.getNodes(); iter.hasNext(); ) { NodeImpl child = (NodeImpl)iter.nextNode(); c.setCurrentItem( child ); - if( c.isLast() && checkPredicates( node, c ) ) + if( checkPredicates( node, c ) ) c.addMatch( child ); if( node.getIncludeDescendants() ) visit( node, c ); } } return c; } @Override public Object visit( TextsearchQueryNode node, Object data ) throws RepositoryException { // System.out.println("Searching for "+node.getQuery()+" from path "+node.getRelativePath()); QueryCollector c = (QueryCollector) data; NodeImpl currNode = c.getCurrentItem(); int score = 0; PropertyIterator pi = currNode.getProperties(); Path checkPath = node.getRelativePath(); // // The tokens are cached in the QueryNode so that we can avoid reparsing // them // every time a node is visited. // We do this in a lazy manner. // String[] tokens = (String[]) node.getAttribute( "parsedTokens" ); if( tokens == null ) { tokens = parseLine( node.getQuery() ); node.setAttribute( "parsedTokens", tokens ); } while ( pi.hasNext() ) { PropertyImpl p = (PropertyImpl) pi.nextProperty(); if( checkPath != null && !checkPath.getLastComponent().equals( p.getQName() ) ) continue; switch( p.getType() ) { case PropertyType.STRING: String val = p.getString(); for( int i = 0; i < tokens.length; i++ ) { // FIXME: Should be cached somehow so that there's no // need to create a new String. if( tokens[i].charAt( 0 ) == '-' && val.contains( tokens[i].substring( 1 ) ) ) { score = 0; break; } else if( val.contains( tokens[i] ) ) { score++; } } break; default: // No action break; } } return score > 0 ? c : null; } /** * //element(*,"nt:base") */ @Override public Object visit( NodeTypeQueryNode node, Object data ) throws RepositoryException { QueryCollector c = (QueryCollector) data; NodeImpl currNode = c.getCurrentItem(); if( currNode.isNodeType( currNode.getSession().fromQName( node.getValue() ) ) ) return c; return null; } private boolean checkPredicates( LocationStepQueryNode node, QueryCollector data ) throws RepositoryException { Object[] result = node.acceptOperands( this, data ); if( node.getPredicates().length != 0 && result.length == 0 ) { return false; } return true; } /** * This class collects the results of the Query. */ private static class QueryCollector { private boolean m_isLast; private NodeImpl m_currentItem; private ArrayList<NodeImpl> m_matches = new ArrayList<NodeImpl>(); /** * Is this the last path component to be matched? */ public final boolean isLast() { return m_isLast; } public final void setLast( boolean b ) { m_isLast = b; } public final NodeImpl getCurrentItem() { return m_currentItem; } public final void setCurrentItem( NodeImpl item ) { m_currentItem = item; } public final void addMatch( NodeImpl ii ) { m_matches.add( ii ); } + + public final String toString() + { + StringBuilder sb = new StringBuilder(); + + try + { + sb.append("Current: "); + sb.append( m_currentItem.getPath() ); + sb.append(" matches=["); + + for( NodeImpl ni : m_matches ) + { + sb.append( ni.getPath() ); + sb.append( "," ); + } + sb.append("]"); + if( isLast() ) sb.append(" (last step processed)"); + } + catch( Exception e ) + { + sb.append( e.getMessage() ); + } + return sb.toString(); + } } /** * Parses an incoming String and returns an array of elements. * * @param nextLine the string to parse * @return the comma-tokenized list of elements, or null if nextLine is null * @throws IOException if bad things happen during the read */ /* * Copyright 2005 Bytecode Pty Ltd. Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable * law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ private String[] parseLine( String nextLine ) { if( nextLine == null ) { return null; } List<String> tokensOnThisLine = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); boolean inQuotes = false; for( int i = 0; i < nextLine.length(); i++ ) { char c = nextLine.charAt( i ); if( c == '\"' ) { // this gets complex... the quote may end a quoted block, or // escape another quote. // do a 1-char lookahead: if( inQuotes // we are in quotes, therefore there can be escaped // quotes in here. && nextLine.length() > (i + 1) // there is indeed another // character to check. && nextLine.charAt( i + 1 ) == '\"' ) { // ..and that char. is a quote also. // we have two quote chars in a row == one quote char, so // consume them both and // put one on the token. we do *not* exit the quoted text. sb.append( nextLine.charAt( i + 1 ) ); i++; } else { inQuotes = !inQuotes; // the tricky case of an embedded quote in the middle: // a,bc"d"ef,g if( i > 2 // not on the begining of the line && nextLine.charAt( i - 1 ) != ' ' // not at the // begining of an // escape sequence && nextLine.length() > (i + 1) && nextLine.charAt( i + 1 ) != ' ' )// not // at // the // end // of // an // escape // sequence { sb.append( c ); } } } else if( c == ' ' && !inQuotes ) { tokensOnThisLine.add( sb.toString() ); sb = new StringBuilder(); // start work on next token } else { sb.append( c ); } } tokensOnThisLine.add( sb.toString() ); return tokensOnThisLine.toArray( new String[0] ); } private static class QuerySorter implements Comparator<NodeImpl> { OrderSpec[] m_specs; public QuerySorter( OrderQueryNode orderNode ) { m_specs = orderNode.getOrderSpecs(); System.out.println( "Sorting by " + m_specs[0].getProperty() ); } public int compare( NodeImpl o1, NodeImpl o2 ) { for( int i = 0; i < m_specs.length; i++ ) { QName propName = m_specs[i].getProperty(); PropertyImpl p1 = null, p2 = null; int result = 0; try { p1 = o1.getProperty( propName ); p2 = o2.getProperty( propName ); result = p1.getValue().compareTo( p2.getValue() ); System.out.println( "p1 =" + p1 + ", p2=" + p2 + ", result=" + result ); } catch( PathNotFoundException e ) { if( p1 == null ) result = 1; if( p2 == null ) result = -1; } catch( RepositoryException e ) { return 0; } if( result == 0 ) continue; // Next property return m_specs[i].isAscending() ? result : -result; } return 0; } } } diff --git a/src/java/org/priha/query/aqt/LocationStepQueryNode.java b/src/java/org/priha/query/aqt/LocationStepQueryNode.java index f3faeda..7e45b29 100644 --- a/src/java/org/priha/query/aqt/LocationStepQueryNode.java +++ b/src/java/org/priha/query/aqt/LocationStepQueryNode.java @@ -1,186 +1,191 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.priha.query.aqt; import javax.jcr.RepositoryException; import org.priha.util.QName; /** * Defines a location step for querying the path of a node. * <p/> * <code> * /foo -> descendants = false, nameTest = foo<br> * //foo -> descendants = true, nameTest = foo<br> * //* -> descendants = true, nameTest = null<br> * /* -> descendants = false, nameTest = null<br> * / -> descendants = false, nameTest = "" * </code> */ public class LocationStepQueryNode extends NAryQueryNode { /** Constant value for position index = last() */ public static final int LAST = Integer.MIN_VALUE; /** Constant value to indicate no position index */ public static final int NONE = Integer.MIN_VALUE + 1; /** * The empty name used in matching the root node. This is an implementation * specific constant as the empty name is not a valid JCR name. * TODO: The root location step should be refactored somehow */ public static final QName EMPTY_NAME = new QName("", ""); /** Empty <code>QueryNode</code> array for us as return value */ private static final QueryNode[] EMPTY = new QueryNode[0]; /** * Name test for this location step. A <code>null</code> value indicates * a '*' name test. */ private QName nameTest; /** * If set to <code>true</code> this location step uses the descendant-or-self * axis. */ private boolean includeDescendants; /** * The context position <code>index</code>. Initially {@link #NONE}. */ private int index = NONE; + public String toString() + { + return "LocationStep["+(nameTest!=null ? nameTest : "*")+(includeDescendants?", include descendants": "")+"]"; + } + /** * Creates a new <code>LocationStepQueryNode</code> that matches only * the empty name (the repository root). The created location step * uses only the child axis. */ protected LocationStepQueryNode(QueryNode parent) { super(parent); this.nameTest = EMPTY_NAME; this.includeDescendants = false; } /** * Returns the label of the node for this location step, or <code>null</code> * if the name test is '*'. * @return the label of the node for this location step. */ public QName getNameTest() { return nameTest; } /** * Sets a new name test. * @param nameTest the name test or <code>null</code> to match all names. */ public void setNameTest(QName nameTest) { this.nameTest = nameTest; } /** * Returns <code>true</code> if this location step uses the * descendant-or-self axis, <code>false</code> if this step uses the child * axis. * @return <code>true</code> if this step uses the descendant-or-self axis. */ public boolean getIncludeDescendants() { return includeDescendants; } /** * Sets a new value for the includeDescendants property. * @param include the new value. * @see #getIncludeDescendants() */ public void setIncludeDescendants(boolean include) { this.includeDescendants = include; } /** * Adds a predicate node to this location step. * @param predicate the node to add. */ public void addPredicate(QueryNode predicate) { addOperand(predicate); } /** * Returns the predicate nodes for this location step. This method may * also return a position predicate. * @return the predicate nodes or an empty array if there are no predicates * for this location step. */ public QueryNode[] getPredicates() { if (operands == null) { return EMPTY; } else { return (QueryNode[]) operands.toArray(new QueryNode[operands.size()]); } } /** * Sets the position index for this step. A value of {@link #NONE} indicates * that this location step has no position index assigned. That is, the * step selects all same name siblings. * @param index the position index. */ public void setIndex(int index) { this.index = index; } /** * Returns the position index for this step. A value of {@link #NONE} indicates * that this location step has no position index assigned. That is, the * step selects all same name siblings. * @return the position index for this step. */ public int getIndex() { return index; } /** * {@inheritDoc} * @throws RepositoryException */ public Object accept(QueryNodeVisitor visitor, Object data) throws RepositoryException { return visitor.visit(this, data); } /** * {@inheritDoc} */ public int getType() { return QueryNode.TYPE_LOCATION; } /** * @inheritDoc */ public boolean equals(Object obj) { if (obj instanceof LocationStepQueryNode) { LocationStepQueryNode other = (LocationStepQueryNode) obj; return super.equals(other) && includeDescendants == other.includeDescendants && index == other.index && (nameTest == null ? other.nameTest == null : nameTest.equals(other.nameTest)); } return false; } } diff --git a/tests/java/org/priha/query/XPathTest.java b/tests/java/org/priha/query/XPathTest.java index e5c440c..cbb0083 100644 --- a/tests/java/org/priha/query/XPathTest.java +++ b/tests/java/org/priha/query/XPathTest.java @@ -1,193 +1,196 @@ package org.priha.query; +import java.util.ArrayList; + import javax.jcr.*; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.priha.RepositoryManager; import org.priha.TestUtil; import org.priha.util.ConfigurationException; -import org.priha.util.PathTest; public class XPathTest extends TestCase { private Session m_session; private QueryManager m_mgr; public void setUp() throws LoginException, ConfigurationException, RepositoryException { TestUtil.emptyRepo(RepositoryManager.getRepository()); m_session = RepositoryManager.getRepository().login(new SimpleCredentials("foo",new char[0])); Node nd = m_session.getRootNode(); nd = nd.addNode("bookstore"); nd = nd.addNode("book"); nd.setProperty("title","How to cook humans"); nd.setProperty("price",35.0); nd = nd.getParent().addNode("book2"); nd.setProperty("title","How to cook forty humans"); nd.setProperty("price",42.0); nd = nd.getParent().addNode("funbooks"); nd = nd.addNode("book"); nd.setProperty("title","How to cook for forty humans"); nd.setProperty("price",19.0); m_session.save(); m_mgr = m_session.getWorkspace().getQueryManager(); } public void tearDown() throws LoginException, RepositoryException { TestUtil.emptyRepo(m_session.getRepository()); m_session.logout(); } private void checkMatchedPaths( QueryResult qr, String... paths ) throws RepositoryException { int idx = 0; - - assertEquals("wrong number of results", paths.length, qr.getNodes().getSize() ); - for( NodeIterator ni = qr.getNodes(); ni.hasNext(); idx++ ) + for( NodeIterator ni = qr.getNodes(); ni.hasNext(); ) { Node totest = ni.nextNode(); + if( totest.getName().startsWith( "jcr:" ) ) continue; + assertEquals( paths[idx], paths[idx], totest.getPath() ); + + idx++; } } public void testNodeQuery1() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore/book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book" ); } public void testNodeQuery2() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore/book/title", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr ); } public void testQuery1() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore/book[@title]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book" ); } public void testQuery2() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*[@title]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book", "/bookstore/book2", "/bookstore/funbooks/book" ); } public void testQuery3() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore", "/bookstore/book", "/bookstore/book2", "/bookstore/funbooks", "/bookstore/funbooks/book"); } public void testQuery32() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore", "/bookstore/book", "/bookstore/book2", "/bookstore/funbooks", "/bookstore/funbooks/book"); Node nd = m_session.getRootNode().getNode("bookstore/book2"); nd.remove(); m_session.save(); q = m_mgr.createQuery( "//*", Query.XPATH ); qr = q.execute(); checkMatchedPaths( qr, "/bookstore", "/bookstore/book", "/bookstore/funbooks", "/bookstore/funbooks/book"); } public void testQuery4() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "/bookstore//book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book", "/bookstore/funbooks/book" ); } public void testQuery5() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book", "/bookstore/funbooks/book" ); } public void testQuery6() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//funbooks/book", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/funbooks/book" ); } public void testDoubleValueQuery() throws InvalidQueryException, RepositoryException { Query q = m_mgr.createQuery( "//*[price > 40.0]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book2" ); } public void testContainsQuery() throws Exception { Query q = m_mgr.createQuery("//*[jcr:contains(.,'forty')]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book2", "/bookstore/funbooks/book" ); } public void testContainsQuery2() throws Exception { Query q = m_mgr.createQuery("//*[jcr:contains(@title,'forty')]", Query.XPATH ); QueryResult qr = q.execute(); checkMatchedPaths( qr, "/bookstore/book2", "/bookstore/funbooks/book" ); } public static Test suite() { return new TestSuite( XPathTest.class ); } }
jalkanen/Priha
8668ec7535956ab6db02626312772c83dd88079e
Small improvements in logging and commentary.
diff --git a/src/java/org/priha/core/ItemImpl.java b/src/java/org/priha/core/ItemImpl.java index 40e02dd..2c589b8 100644 --- a/src/java/org/priha/core/ItemImpl.java +++ b/src/java/org/priha/core/ItemImpl.java @@ -1,338 +1,347 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.PathRef; import org.priha.util.*; +/** + * Provides a basic implementation for Items. An Item stores a reference + * to its Path, the Session, and keeps a record of its ItemState. Therefore + * it's a fairly lightweight object. + */ public abstract class ItemImpl implements Item { protected PathRef m_path; protected final SessionImpl m_session; protected ItemState m_state = ItemState.UNDEFINED; protected boolean m_isNew = false; - public ItemImpl( SessionImpl session, String path ) throws NamespaceException, RepositoryException - { - this( session, PathFactory.getPath(session,path) ); - } +// public ItemImpl( SessionImpl session, String path ) throws NamespaceException, RepositoryException +// { +// this( session, PathFactory.getPath(session,path) ); +// } public ItemImpl(SessionImpl session, Path path) { m_session = session; m_path = session.getPathManager().getPathRef(path); } public ItemImpl(ItemImpl original, SessionImpl session) { this( session, original.getInternalPath() ); m_state = original.m_state; } public PathRef getPathReference() { if( m_path == null ) throw new RuntimeException("Path reference must not be null!"); return m_path; } public ItemState getState() { return m_state; } + @SuppressWarnings("fallthrough") public void setState( ItemState state ) throws RepositoryException { if( state != m_state ) { switch( state ) { case EXISTS: m_state = state; break; case NEW: m_isNew = true; case REMOVED: case MOVED: // // Additions and removals also affect the parent. // m_state = state; m_session.markDirty(this); if( !getInternalPath().isRoot() ) { getParent().setState(ItemState.UPDATED); } break; case UPDATED: // // However, basic updates do not. // if( m_state == ItemState.REMOVED ) { // Simple UPDATED does not override REMOVED. break; } m_state = state; m_session.markDirty(this); break; + + case UNDEFINED: + throw new InvalidItemStateException("State cannot be set to UNDEFINED - that is the starting state of any Item only."); } } } public void accept(ItemVisitor visitor) throws RepositoryException { if( isNode() ) { visitor.visit( (Node) this ); } else { visitor.visit( (Property) this ); } } public Item getAncestor(int depth) throws ItemNotFoundException, AccessDeniedException, RepositoryException { try { Path ancestorPath = getInternalPath().getAncestorPath(depth); return m_session.getItem(ancestorPath); } catch( InvalidPathException e ) { throw new ItemNotFoundException(e.getMessage()); } } public int getDepth() throws RepositoryException { return getInternalPath().depth(); } public String getName() throws RepositoryException { return m_session.fromQName( getInternalPath().getLastComponent() ); } /** * Returns the QName of this item. * * @return A QName. * @throws NamespaceException If the namespace cannot be parsed. * @throws RepositoryException If something else goes wrong. */ public QName getQName() throws NamespaceException, RepositoryException { QName qname = getInternalPath().getLastComponent(); return qname; } public NodeImpl getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException { try { Path parentPath = getInternalPath().getParentPath(); NodeImpl parent = (NodeImpl)m_session.getItem(parentPath); return parent; } catch( InvalidPathException e ) { throw new ItemNotFoundException(e.getMessage()); } } public Path getInternalPath() { try { return m_session.getPath( m_path ); } catch( PathNotFoundException e ) { throw new RuntimeException("Invalid path received: "+m_path,e); } } public String getPath() throws RepositoryException { return PathFactory.getMappedPath( m_session, getInternalPath() ); // return getInternalPath().toString(m_session); } public SessionImpl getSession() throws RepositoryException { return m_session; } public boolean isModified() { // // An Item is not modified, if it's, well, not modified or it's been recently // added (then it's NEW). // return m_state != ItemState.EXISTS && m_state != ItemState.NEW; } public boolean isNew() { return m_isNew || m_state == ItemState.UNDEFINED; } public boolean isNode() { return false; } public boolean isSame(Item otherItem) throws RepositoryException { if( m_session.getRepository() == otherItem.getSession().getRepository() ) { if( getPath().equals(otherItem.getPath()) ) { if( isNode() == otherItem.isNode() ) { if( isNode() ) { return true; } else if( getParent().getPath().equals(otherItem.getParent().getPath()) ) { return true; } } } } return false; } public void refresh(boolean keepChanges) throws InvalidItemStateException, RepositoryException { if( !m_session.itemExists(getInternalPath()) ) throw new InvalidItemStateException("You cannot refresh an Item which has been deleted!"); if( getState() == ItemState.REMOVED || getState() == ItemState.MOVED ) throw new InvalidItemStateException("Node has been removed"); m_session.refresh( keepChanges, getInternalPath() ); } public abstract void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException; public abstract void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException ; // protected abstract void saveItemOnly() throws RepositoryException; public String toString() { try { return "Node["+m_session.getWorkspace().getName()+":"+getPath()+"]"; } catch( RepositoryException e ) { return "Node["+m_session.getWorkspace().getName()+":"+getInternalPath()+"]"; } } /** Marks this Node + its parent modified. * @throws RepositoryException */ // protected void markModified(boolean isModified) throws RepositoryException // { // markModified( isModified, true ); // } // // protected void markModified(boolean isModified, boolean parentToo) throws RepositoryException // { // if( m_state == ItemState.EXISTS ) m_state = ItemState.UPDATED; // // m_session.markDirty(this); // // if( !getInternalPath().isRoot() && parentToo ) // { // // // // Regardless of the state of the current Item, the parent // // shall always be marked as modified (since the state of this // // child has changed.) // // // NodeImpl parent = getParent(); // parent.markModified(true, false); // } // } @Override public int hashCode() { return getInternalPath().hashCode()-17; } /** * Performs mandatory housekeeping right before saving. * @throws RepositoryException */ protected void preSave() throws RepositoryException { if( getState() == ItemState.UNDEFINED ) { throw new IllegalStateException("Node "+getInternalPath()+" must not be in UNDEFINED state at this point (this is a bug in Priha, please report!)"); } } /** * Performs mandatory housekeeping after item state has been persisted to disk. * */ protected void postSave() { m_state = ItemState.EXISTS; m_isNew = false; } private transient long m_creationTime = System.currentTimeMillis(); public long getCreationTime() { return m_creationTime; } } diff --git a/src/java/org/priha/core/NodeImpl.java b/src/java/org/priha/core/NodeImpl.java index 4f92baa..68d4957 100644 --- a/src/java/org/priha/core/NodeImpl.java +++ b/src/java/org/priha/core/NodeImpl.java @@ -1,1213 +1,1240 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import static org.priha.core.JCRConstants.JCR_UUID; import static org.priha.core.JCRConstants.Q_JCR_BASEVERSION; import static org.priha.core.JCRConstants.Q_JCR_CREATED; import static org.priha.core.JCRConstants.Q_JCR_ISCHECKEDOUT; import static org.priha.core.JCRConstants.Q_JCR_MIXINTYPES; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import static org.priha.core.JCRConstants.Q_MIX_VERSIONABLE; import static org.priha.core.JCRConstants.Q_NT_BASE; import static org.priha.core.JCRConstants.Q_NT_UNSTRUCTURED; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.*; import javax.jcr.lock.Lock; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.version.OnParentVersionAction; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import org.priha.RepositoryManager; import org.priha.core.locks.QLock; import org.priha.core.locks.LockManager; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.nodetype.QNodeType; import org.priha.nodetype.QNodeTypeManager; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.Path.Component; import org.priha.util.*; import org.priha.version.VersionHistoryImpl; import org.priha.version.VersionImpl; import org.priha.version.VersionManager; +/** + * Implements a Node. This is one of the most heavy classes in Priha, with a lot + * of stuff happening. The NodeImpl class does some basic caching for some state + * objects, so keeping references can be faster in some cases. + */ public class NodeImpl extends ItemImpl implements Node, Comparable<Node> { private static final String JCR_PREDECESSORS = "jcr:predecessors"; private static final String JCR_SUCCESSORS = "jcr:successors"; + /** + * A compile-time flag for allowing/disallowing Same Name Sibling support. + * addNode() will throw an exception if you disallow these. This is sometimes + * useful for debugging. + */ + private static final boolean ALLOW_SNS = true; + private QNodeDefinition m_definition; private QNodeType m_primaryType; protected String m_cachedUUID; private ArrayList<Path> m_childOrder; static Logger log = Logger.getLogger( NodeImpl.class.getName() ); /** * Do not change. This is the fixed UUID for the root node for each workspace. If you * change this, horrible things may happen. * * The UUID is a standard Type 3 UUID, generated from the byte array [ 0x00 ]. */ private static final UUID ROOT_UUID = UUID.nameUUIDFromBytes( new byte[] { 0x00 } ); /** * Creates a clone of the NodeImpl, and places it to the given Session * * @param original * @param session * @throws RepositoryException * @throws IllegalStateException * @throws ValueFormatException */ protected NodeImpl( NodeImpl original, SessionImpl session ) throws ValueFormatException, IllegalStateException, RepositoryException { super( original, session ); m_primaryType = original.m_primaryType; m_definition = original.m_definition; } protected NodeImpl( SessionImpl session, Path path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { super( session, path ); m_primaryType = primaryType; m_definition = nDef; if( populateDefaults ) { setState(ItemState.NEW); PropertyImpl pt =internalSetProperty( Q_JCR_PRIMARYTYPE, session.fromQName( m_primaryType.getQName() ), // FIXME: Not very efficient PropertyType.NAME ); pt.setState( ItemState.NEW ); } } protected NodeImpl( SessionImpl session, String path, QNodeType primaryType, QNodeDefinition nDef, boolean populateDefaults ) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { this( session, PathFactory.getPath(session,path), primaryType, nDef, populateDefaults ); } /** * Figures out what type the child node should be. * * @param relpath A relative path to the child node. * @return A NodeType for the path * @throws RepositoryException If something goes wrong. */ private QNodeType assignChildType(QName relpath) throws RepositoryException { QNodeDefinition nd = m_primaryType.findNodeDefinition(relpath); if( nd == null ) { throw new ConstraintViolationException("Cannot assign a child type to this node, since there is no default type."); } QNodeType nt = nd.getDefaultPrimaryType(); return nt; } public NodeImpl addNode(String relPath) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { NodeImpl nd = addNode(relPath, null); return nd; } public NodeImpl addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { if( relPath.endsWith("]") && !m_session.isSuper() ) { throw new RepositoryException("Cannot add an indexed entry unless using a superSession"); } Path absPath = getInternalPath().resolve(m_session,relPath); NodeImpl ni = null; try { // // Are we locked without a token? // if( isLockedWithoutToken() ) throw new LockException("This node is locked and cannot add a child Node!"); // // Check out if parent is okay with the addition of this node // Path parentPath = absPath.getParentPath(); Item item = m_session.getItem(parentPath); if( !item.isNode() ) { throw new ConstraintViolationException("Trying to add a node to a Property"); } NodeImpl parent = (NodeImpl) item; if( parent.getState() == ItemState.REMOVED ) { throw new ConstraintViolationException("Parent has been removed"); } // // Parent is okay with this addition, so we'll continue with // figuring out what the node type of this node should be. // QNodeType assignedType; QNodeDefinition assignedNodeDef; if( primaryNodeTypeName == null ) { assignedType = parent.assignChildType(absPath.getLastComponent()); } else { assignedType = getNodeTypeManager().getNodeType( primaryNodeTypeName ).getQNodeType(); } assignedNodeDef = m_primaryType.findNodeDefinition( absPath.getLastComponent() ); if( assignedNodeDef == null ) { throw new ConstraintViolationException("No node definition for this node type"); } // Residual definitions if( assignedNodeDef.getQName().toString().equals("*") ) { assignedNodeDef = assignedType.findNodeDefinition( absPath.getLastComponent() ); } // // Check for same name siblings. If they are allowed, and they already // exist, we figure out the number of other existing nodes and modify the absPath // accordingly for the new path. // if( m_session.itemExists(absPath) ) { NodeDefinition nd = parent.getDefinition(); if( !nd.allowsSameNameSiblings() ) { throw new ItemExistsException("Node "+absPath+" already exists, and the parent node does not allow same name siblings!"); } NodeIterator iter = parent.getNodes( absPath.getLastComponent().toString( m_session ) ); int newPos = ((int)iter.getSize())+1; absPath = new Path( absPath.getParentPath(), new Path.Component(absPath.getLastComponent(),newPos) ); -// throw new RepositoryException("TURNED OFF FOR NOW"); + + if( !ALLOW_SNS ) throw new RepositoryException("TURNED OFF FOR NOW"); } // // Check if parent allows adding this. // QNodeType parentnt = parent.getPrimaryQNodeType(); if( !parentnt.canAddChildNode(absPath.getLastComponent(), primaryNodeTypeName != null ? m_session.toQName(primaryNodeTypeName) : null ) ) { throw new ConstraintViolationException("Parent node does not allow adding nodes of name "+absPath.getLastComponent()); } // // Node type and definition are now okay, so we'll create the node // and add it to our session. // ni = m_session.createNode(absPath, assignedType, assignedNodeDef,true); ni.sanitize(); ni.setState( ItemState.NEW ); } catch( InvalidPathException e) { throw new PathNotFoundException( e.getMessage(), e ); } return ni; } private QNodeTypeManager.Impl getNodeTypeManager() throws RepositoryException { return m_session.getWorkspace().getNodeTypeManager(); } public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException { Session internalSession = m_session.getRepository().login(workspaceName); Path correspondingPath; try { String uuid = null; NodeImpl nd = this; // // Find the nearest parent with the correct UUID // while( uuid == null && !nd.getInternalPath().isRoot() ) { try { uuid = nd.getUUID(); } catch( UnsupportedRepositoryOperationException e ) { nd = nd.getParent(); } } correspondingPath = getInternalPath().getSubpath( nd.getDepth() ); if( uuid != null ) { NodeImpl nodeInOtherWS = (NodeImpl)internalSession.getNodeByUUID(uuid); return nodeInOtherWS.getInternalPath().resolve(m_session,correspondingPath.toString()).toString(); } return ((NodeImpl)internalSession.getRootNode()).getNode(correspondingPath).getPath(); } catch( PathNotFoundException e ) { throw new ItemNotFoundException(); } finally { internalSession.logout(); } } public NodeDefinition getDefinition() throws RepositoryException { if( m_definition == null ) sanitize(); return m_definition.new Impl(m_session); } public QNodeDefinition getQDefinition() { return m_definition; } public int getIndex() throws RepositoryException { return getInternalPath().getLastComponent().getIndex(); } protected List<Path> getChildOrder() { if( m_childOrder != null ) return Collections.unmodifiableList(m_childOrder); return null; } protected void setChildOrder(List<Path> list) { if( list == null ) m_childOrder = null; else { m_childOrder = new ArrayList<Path>(); m_childOrder.addAll(list); } } public NodeImpl getNode( Path absPath ) throws PathNotFoundException, RepositoryException { Item i = m_session.getItem(absPath); if( i.isNode() ) { return (NodeImpl) i; } throw new PathNotFoundException("Path refers to a property: "+absPath.toString()); } public NodeImpl getNode(String relPath) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(m_session,relPath) ); } public NodeImpl getNode(QName name) throws PathNotFoundException, RepositoryException { return getNode( getInternalPath().resolve(name) ); } /** * Returns the children of this Node sorted according to the child order. If there * is no child order, does nothing. * * @param list * @return * @throws PathNotFoundException * @throws RepositoryException */ private List<Path> sortChildren(List<Path> list) throws PathNotFoundException, RepositoryException { if( m_childOrder != null ) { list.removeAll(m_childOrder); ArrayList<Path> newOrder = new ArrayList<Path>(); newOrder.addAll(m_childOrder); newOrder.addAll(list); list = newOrder; } return list; } + /** + * Returns a lazy iterator over the children of this Node. + */ public NodeIterator getNodes() throws RepositoryException { List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); return new LazyNodeIteratorImpl(m_session,children); } public NodeIterator getNodes(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<Path> matchedpaths = new ArrayList<Path>(); List<Path> children = m_session.listNodes( getInternalPath() ); children = sortChildren(children); for( Path path : children ) { // This crummy code turns a Path.Component to a QName, i.e. drops // the index, if it exists. String s = m_session.fromQName( new QName(path.getLastComponent().getNamespaceURI(), path.getLastComponent().getLocalPart()) ); Matcher match = p.matcher( s ); if( match.matches() ) { matchedpaths.add( path ); } } return new LazyNodeIteratorImpl(m_session,matchedpaths); } public ItemImpl getPrimaryItem() throws ItemNotFoundException, RepositoryException { NodeType nd = getPrimaryNodeType(); String primaryItem = nd.getPrimaryItemName(); if( primaryItem != null ) { return getChildProperty( primaryItem ); } throw new ItemNotFoundException( getPath()+" does not declare a primary item" ); } public QNodeType getPrimaryQNodeType() { return m_primaryType; } public QNodeType.Impl getPrimaryNodeType() throws RepositoryException { return m_primaryType.new Impl(m_session); } public PropertyIteratorImpl getProperties() throws RepositoryException { List<PropertyImpl> ls = new ArrayList<PropertyImpl>(); ls.addAll( m_session.m_provider.getProperties(getInternalPath()) ); return new PropertyIteratorImpl( ls ); } public PropertyIterator getProperties(String namePattern) throws RepositoryException { Pattern p = TextUtil.parseJCRPattern(namePattern); ArrayList<PropertyImpl> matchedpaths = new ArrayList<PropertyImpl>(); for( PropertyIterator i = getProperties(); i.hasNext(); ) { PropertyImpl prop = (PropertyImpl)i.nextProperty(); Matcher match = p.matcher( prop.getName() ); if( match.matches() ) { matchedpaths.add( prop ); } } return new PropertyIteratorImpl(matchedpaths); } public PropertyImpl getChildProperty( String name ) throws RepositoryException { ItemImpl ii = m_session.m_provider.getItem( getInternalPath().resolve(m_session,name) ); if( ii.isNode() ) throw new ItemNotFoundException("Found a Node, not a Property"); return (PropertyImpl) ii; } public PropertyImpl getProperty( QName propName ) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(propName); ItemImpl item = m_session.getItem(abspath); if( item != null && !item.isNode() && item.getState() != ItemState.REMOVED && item.getState() != ItemState.MOVED ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } public PropertyImpl getProperty(String relPath) throws PathNotFoundException, RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); Item item = m_session.getItem(abspath); if( item != null && !item.isNode() ) { return (PropertyImpl) item; } throw new PathNotFoundException( abspath.toString() ); } void autoCreateProperties() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { autoCreateProperties( getPrimaryQNodeType() ); for( NodeType nt : getMixinNodeTypes() ) { autoCreateProperties( ((QNodeType.Impl)nt).getQNodeType() ); //FIXME: Unnecessary } } /** * This method autocreates the properties for this node, which are marked to be automatically created * by the definition. * * @param nt The NodeType * @throws RepositoryException * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException */ private void autoCreateProperties(QNodeType nt) throws RepositoryException, ValueFormatException, VersionException, LockException, ConstraintViolationException { ValueFactoryImpl vfi = m_session.getValueFactory(); // // Special cases. // if( nt.getQName().equals( Q_MIX_VERSIONABLE ) ) { // VersionManager.createVersionHistory( this ); } for( QPropertyDefinition pd : nt.getQPropertyDefinitions() ) { if( pd.isAutoCreated() && !hasProperty(pd.getQName()) ) { log.finest("Autocreating property "+pd.getQName()); Path p = getInternalPath().resolve(pd.getQName()); PropertyImpl pi = new PropertyImpl(m_session, p, pd); // FIXME: Add default value generation if( Q_JCR_UUID.equals(pi.getQName()) ) { UUID uuid; if( getInternalPath().isRoot() ) uuid = ROOT_UUID; else uuid = UUID.randomUUID(); pi.loadValue( vfi.createValue( uuid.toString() ) ); } else if( Q_JCR_CREATED.equals(pi.getQName() )) { pi.loadValue( vfi.createValue( Calendar.getInstance() ) ); } else if( Q_JCR_ISCHECKEDOUT.equals(pi.getQName())) { pi.loadValue( vfi.createValue( true ) ); } else if( Q_JCR_PRIMARYTYPE.equals(pi.getQName())) { // // This is just a guess // pi.loadValue( vfi.createValue( Q_NT_UNSTRUCTURED, PropertyType.NAME ) ); } else { throw new UnsupportedRepositoryOperationException("Automatic setting of property "+pi.getPath()+ " is not supported."); } pi.setState( ItemState.NEW ); //addChildProperty( pi ); } } } public PropertyIterator getReferences() throws RepositoryException { List<PropertyImpl> references = m_session.getReferences( getUUID() ); return new PropertyIteratorImpl(references); } + /** + * Returns the UUID for this node. Utilizes an internal cache for the UUID, + * so is fast after the first call. + */ public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException { if( m_cachedUUID != null ) return m_cachedUUID; if( isNodeType("mix:referenceable") ) { try { Property uuid = getProperty(JCR_UUID); String u = uuid.getValue().getString(); m_cachedUUID = u; return u; } catch( PathNotFoundException e ) { // Fine, let's just fall through, and end up throwing an exception } } throw new UnsupportedRepositoryOperationException("No UUID defined for "+getPath()); } public VersionHistoryImpl getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException { if( isNodeType("mix:versionable") ) { // Locate version history Path versionPath = VersionManager.getVersionStoragePath( getUUID() ); VersionHistoryImpl vh = (VersionHistoryImpl)getNode( versionPath ); return vh; } throw new UnsupportedRepositoryOperationException("This node does not have a version history."); } public boolean hasNode(String relPath) throws RepositoryException { Path absPath = getInternalPath().resolve(m_session,relPath); return m_session.hasNode(absPath); } - + /** + * Returns true, if this Node has a child with the given QName. + * + * @param name A QName. + * @return True, if there is a child by this name. + * @throws RepositoryException + */ public boolean hasNode(QName name) throws RepositoryException { Path absPath = getInternalPath().resolve(name); return m_session.hasNode(absPath); } public boolean hasNodes() throws RepositoryException { + // FIXME: Slow. return getNodes().getSize() > 0; } public boolean hasProperties() throws RepositoryException { // FIXME: Slow. return getProperties().getSize() > 0; } public boolean hasProperty( QName propName ) throws RepositoryException { Path abspath = getInternalPath().resolve(propName); return m_session.hasProperty(abspath); } public boolean hasProperty(String relPath) throws RepositoryException { Path abspath = getInternalPath().resolve(m_session,relPath); return m_session.hasProperty( abspath ); } public boolean isNodeType(String nodeTypeName) throws RepositoryException { NodeType primary = getPrimaryNodeType(); if( !primary.isNodeType( nodeTypeName ) ) { NodeType[] mixins = getMixinNodeTypes(); for( int i = 0; i < mixins.length; i++ ) { if( mixins[i].isNodeType(nodeTypeName) ) return true; } // // Not a primary, nor any of the mixins // return false; } return true; } public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException { // // The usual sanity checks. // if( !getPrimaryNodeType().hasOrderableChildNodes() ) { throw new UnsupportedRepositoryOperationException("This Node does not support orderable child nodes."); } if( !isCheckedOut() ) throw new VersionException("Node not checked out"); if( isLockedWithoutToken() ) throw new LockException("Node is locked"); if( srcChildRelPath.equals( destChildRelPath ) ) return; if( srcChildRelPath.indexOf( '/' ) != -1 || (destChildRelPath != null && destChildRelPath.indexOf( '/' ) != -1 )) throw new ConstraintViolationException("Child path depth must be 1"); if( !hasNode(srcChildRelPath) ) throw new ItemNotFoundException("Source child does not exist"); if( destChildRelPath != null && !hasNode(destChildRelPath) ) throw new ItemNotFoundException("Dest child does not exist"); // // Get the current order // Path srcPath = getInternalPath().resolve(m_session,srcChildRelPath); Path dstPath = destChildRelPath != null ? getInternalPath().resolve(m_session,destChildRelPath) : null; List<Path> children; if( m_childOrder != null ) children = m_childOrder; else children = m_session.listNodes( getInternalPath() ); ArrayList<Path> newOrder = new ArrayList<Path>(); // // Figure out the new order // newOrder.addAll(children); int srcIndex = newOrder.indexOf( srcPath ); int dstIndex = newOrder.indexOf( dstPath ); if( srcIndex == -1 ) throw new ItemNotFoundException("Cannot locate source child, WTF?"); // // Removal of the node may cause a jump in the indices, so we need to subtract one sometimes. // Path p = newOrder.remove(srcIndex); if( dstIndex != -1 ) newOrder.add(dstIndex - (dstIndex > srcIndex ? 1 : 0),p); else newOrder.add(p); // // Make sure locks are also transferred. // QLock lock = m_lockManager.getLock( srcPath ); if( lock != null ) { m_lockManager.moveLock(lock, dstPath); } // // Now the not-so-fun thing; we must make sure that also any SNS's are rearranged appropriately. // // Case 1: A[1], A[2], A[3] => orderBefore("A[3]","A[1]") => A[3], A[1], A[2]. // Case 2: A[1], A[2], A[3] => orderBefore("A[1]","A[3]") => A[2], A[1], A[3]. // boolean isSuper = m_session.setSuper(true); try { int realidx = 1; for( int i = 0; i < newOrder.size(); i++ ) { Path.Component qn = newOrder.get(i).getLastComponent(); // Is this the moved path or its SNS? We check just the QName part, not the index. if( qn.getNamespaceURI().equals(srcPath.getLastComponent().getNamespaceURI()) && qn.getLocalPart().equals(srcPath.getLastComponent().getLocalPart())) { if( qn.getIndex() != realidx ) { System.out.println("Trying to reorder SNS... : "+qn); QName q = qn.getQName(); Component newName = new Component(q,realidx); Path path1 = getInternalPath().resolve(qn); Path tmppath = getInternalPath().resolve(m_session,"priha:tmpmove"); Path newPath = getInternalPath().resolve(newName); m_session.rename( path1, tmppath.getLastComponent() ); m_session.rename( newPath, path1.getLastComponent() ); m_session.rename( tmppath, newName ); int oldI = newOrder.indexOf(newPath); Path oldP = newOrder.set(i,newPath); newOrder.set(oldI, oldP); realidx++; } } } } finally { m_session.setSuper(isSuper); } // // Finish. // setState( ItemState.UPDATED ); m_childOrder = newOrder; } private PropertyImpl prepareProperty( String name, Object value ) throws PathNotFoundException, RepositoryException { return prepareProperty( m_session.toQName(name), value ); } /** * Finds a property and checks if we're supposed to remove it or not. It also creates * the property if it does not exist. The property value itself is empty until the * property is loaded with loadValue() * * @param name * @param value * @return * @throws PathNotFoundException * @throws RepositoryException */ private PropertyImpl prepareProperty( QName name, Object value ) throws PathNotFoundException, RepositoryException { PropertyImpl prop = null; if( !getSession().isSuper() ) { if( isLockedWithoutToken() ) throw new LockException("Path is locked"); if( !isCheckedOut() ) throw new VersionException("Node is not checked out."); if( name.equals( Q_JCR_MIXINTYPES ) ) throw new ConstraintViolationException("Manually setting mixinTypes is not allowed."); } // // Because we rely quite a lot on the primary property, we need to go and // handle it separately. // if( name.equals( Q_JCR_PRIMARYTYPE ) ) { if( hasProperty( Q_JCR_PRIMARYTYPE ) ) { throw new ConstraintViolationException( getInternalPath()+" has already been assigned a primary type!"); } // We know where this belongs to. QNodeType gnt = QNodeTypeManager.getInstance().getNodeType( Q_NT_BASE ); QPropertyDefinition primaryDef = gnt.findPropertyDefinition( JCRConstants.Q_JCR_PRIMARYTYPE, false); prop = new PropertyImpl( m_session, getInternalPath().resolve(name), primaryDef ); // prop.m_state = ItemState.NEW; // addChildProperty( prop ); // Again, a special case. First add the property to the lists. return prop; } try { prop = getProperty(name); } catch( PathNotFoundException e ){} catch( ItemNotFoundException e ){} if( prop == null ) { Path propertypath = getInternalPath().resolve(name); Path p = propertypath.getParentPath(); try { NodeImpl parentNode = (NodeImpl) m_session.getItem(p); boolean ismultiple = value instanceof Object[]; QNodeType parentType = parentNode.getPrimaryQNodeType(); QPropertyDefinition pd = parentType.findPropertyDefinition(name,ismultiple); if( pd == null ) { // // Let's add one of our definitions // if( name.getNamespaceURI().equals(RepositoryManager.NS_PRIHA) ) { pd = QPropertyDefinition.PRIHA_INTERNAL; } else { throw new RepositoryException("No propertydefinition found for "+parentType+" and "+name); } } prop = new PropertyImpl( m_session, propertypath, pd ); // prop.setState( ItemState.NEW ); } catch( PathNotFoundException e ) { throw new InvalidItemStateException("Parent not located; the item is in indeterminate state."); } } else { // prop.setState( ItemState.UPDATED ); } if( value == null ) { removeProperty(prop); } else { //addChildProperty( prop ); } return prop; } /** * Removes a given property from the node. * @param prop */ protected void removeProperty(PropertyImpl prop) throws RepositoryException { prop.setState( ItemState.REMOVED ); } public PropertyImpl setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // Again, setting a value to null is the same as removing the property. // if( value == null ) { PropertyImpl p = getProperty(name); p.remove(); return p; } if( value.getType() != type ) { throw new ConstraintViolationException("Type of the Value and the type parameter must match."); } PropertyImpl p = prepareProperty( name, value ); p.setValue(value); return p; } public PropertyImpl setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } PropertyImpl internalSetProperty(QName name, Value[] values, int type) throws PathNotFoundException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.loadValue( values, type ); return p; } public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { if( values == null ) { Property p = getProperty(name); p.remove(); return p; } if( values.length > 0 && values[0] != null && type != values[0].getType() ) throw new ValueFormatException("Do not know how to convert between types, sorry."); PropertyImpl p = prepareProperty( name, values ); p.setValue( values, type ); return p; } public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = prepareProperty( name, values ); p.setValue(values); return p; } public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { // // For this method, we create a proper value array according to the type information. // if( values == null ) { Property p = getProperty(name); p.remove(); return p; } PropertyImpl p = prepareProperty( name, values ); p.setValue( values ); return p; } private PropertyImpl internalSetProperty(QName name, String value, int type) throws PathNotFoundException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.loadValue( m_session.getValueFactory().createValue(value,type) ); return prop; } /** * Tag a Node with the given transient property. Priha uses this internally * to store metadata (or a property) which is never saved. Transient properties * are never saved. * * @see PropertyImpl#isTransient() * * @param name * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, Boolean.TRUE); p.setTransient(true); } /** * Tags a Node with a given transient property with a String value. In practice, * this sets a String property and marks it transient (i.e. never saved). * * @see PropertyImpl#isTransient() * @param name Name of the property to set * @param value Value for the property * @throws ValueFormatException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws RepositoryException */ public void tag(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl p = setProperty(name, value); p.setTransient(true); } /** * Returns true, if this Node has the named tag (i.e. it has a transient * Property by this name). * * @param name Tag to check for * @return True, if the tag exists. False otherwise. * @throws RepositoryException If the Repository is b0rken. * @see PropertyImpl#isTransient() */ public boolean hasTag(String name) throws RepositoryException { try { if( hasProperty( name ) ) { return getProperty(name).isTransient(); } } catch( PathNotFoundException e ) {} return false; } public PropertyImpl setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { PropertyImpl prop = prepareProperty(name,value); prop.setValue(value); diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index d8c9105..ba220ef 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -974,673 +974,673 @@ public class FileProvider implements RepositoryProvider, PerformanceReporter String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: This method is extremely speed-critical // TODO: Protect against windows special names (CON) etc. protected static String mangleName( String name ) { StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } else if( ch == ':' ) { // Colon is not allowed on NTFS or OSX. sb.append( ';' ); } else if( ch >= 'A' && ch <= 'Z' ) { // JSR-170 is case sensitive, so we have to make // sure our storage is too. sb.append( ch ); sb.append( '^' ); } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } return sb.toString(); } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } /** * Just copies all characters from <i>in</i> to <i>out</i>. */ private static void copyContents( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private static void copyContents(Reader in, Writer out) throws IOException { char[] buf = new char[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private String readContentsAsString( File file ) throws IOException { Reader in = new InputStreamReader( new FileInputStream(file), "UTF-8" ); try { StringWriter out = new StringWriter(); copyContents( in, out ); return out.toString(); } finally { in.close(); } } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; private long m_lastWrite = System.currentTimeMillis(); /* After this many writes the store is compacted. */ private static final int COMPACT_LIMIT = 100; /* But compacting is not done more often than this limit (in ms) */ private static final long COMPACT_TIME_LIMIT = 30*1000L; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); long now = System.currentTimeMillis(); if( ++m_writeCount > COMPACT_LIMIT && (now-m_lastWrite) > COMPACT_TIME_LIMIT ) { - System.out.println( now-m_lastWrite ); + //System.out.println( now-m_lastWrite ); serialize(); m_writeCount = 0; m_lastWrite = now; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { - System.out.println("++++++ COMPACTING..."); + // System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } } diff --git a/tests/java/org/priha/core/RepositoryTest.java b/tests/java/org/priha/core/RepositoryTest.java index d7ef459..529cc49 100644 --- a/tests/java/org/priha/core/RepositoryTest.java +++ b/tests/java/org/priha/core/RepositoryTest.java @@ -1,353 +1,359 @@ package org.priha.core; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.logging.Logger; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; import org.priha.RepositoryManager; import org.priha.TestUtil; public class RepositoryTest extends AbstractTest { Logger log = Logger.getLogger(RepositoryTest.class.getName()); Session m_session; protected void setUp() throws Exception { super.setUp(); TestUtil.emptyRepo(m_repository); m_session = m_repository.login(new SimpleCredentials("foo",new char[0])); } protected void tearDown() throws Exception { m_session.logout(); super.tearDown(); } public void testLogin() throws Exception { Node nd = m_session.getRootNode(); assertEquals( 0, nd.getDepth() ); } public void testShutdown() throws Exception { RepositoryImpl r = RepositoryManager.getRepository("priha_shutdown.properties"); Session s = r.login(); assertTrue("session start",s.isLive()); r.shutdown(); assertFalse("session should be closed", s.isLive()); try { r.login(); fail("Allowed login"); } catch( RepositoryException e ) { // Expected } } + /** + * Peek directly into the FileProvider repository to figure out if all the files + * are properly removed. Weeds out files which are part of the system. + * + * @throws Exception + */ public void testEmptyRepo() throws Exception { Node nd = m_session.getRootNode().addNode("testemptyrepo"); nd = nd.addNode("foo"); nd.setProperty("Barbapapa","Barbamama"); m_session.save(); TestUtil.emptyRepo(m_repository); File f = new File("/tmp/priha/fileprovider/workspaces/default/"); String[] paths = f.list(); for( String p : paths ) { - if( p.startsWith("jcr:") || p.startsWith( "priha:") || p.startsWith( "." )) continue; // This is okay + if( p.startsWith("jcr;") || p.startsWith( "priha;") || p.startsWith( "." )) continue; // This is okay fail( "This was not removed: "+p ); } } public void testRemove() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); s.getRootNode().addNode("test"); s.save(); assertTrue( "was not created", s.getRootNode().hasNode("/test") ); Node nd = s.getRootNode().getNode("/test"); nd.remove(); s.save(); assertFalse( "was not removed", s.getRootNode().hasNode("/test") ); File f = new File("/tmp/priha/fileprovider/workspaces/default/test"); assertFalse( "File was not removed", f.exists() ); } public void testSave() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); Item it = s.getItem("/test"); assertTrue( "is not node", it.isNode() ); assertEquals( "wrong property", "foo",((Node)it).getProperty("a").getString()); } public void testSave2() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); s.logout(); s = m_repository.login(); Item it = s.getItem("/test"); assertTrue( "is not node", it.isNode() ); assertEquals( "wrong property", "foo",((Node)it).getProperty("a").getString()); } public void testRemoveProperty() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); nd.setProperty("foo", "bar"); s.save(); Item i = s.getItem("/foo"); assertTrue( "wrong type", i instanceof Property ); assertEquals( "wrong content", "bar", ((Property)i).getValue().getString() ); i.remove(); s.save(); Session s2 = m_repository.login(); try { s2.getItem("/foo"); fail("Still got it"); } catch( PathNotFoundException e ) { // Expected } File f = new File("/tmp/priha/fileprovider/workspaces/default/foo.info"); assertFalse( "File was not removed", f.exists() ); } public void testTraversal() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); boolean testFound = false; for( NodeIterator it = nd.getNodes(); it.hasNext(); ) { Node n = it.nextNode(); if( n.getName().equals("test") ) { testFound = true; } else if( n.getName().equals("jcr:system") ) { // We ignore this } else { fail("Extraneous node found"); } } assertTrue( "test node not found", testFound ); } public void testBinaryProperty() throws Exception { Node nd = m_session.getRootNode(); nd = nd.addNode("binarytest"); String content = TestUtil.getUniqueID(32); InputStream in = new ByteArrayInputStream( content.getBytes() ); Property p = nd.setProperty("blob", in ); m_session.save(); Property p2 = (Property) m_session.getItem("/binarytest/blob"); assertEquals( content, p2.getString() ); } public void testMultiProviders() throws Exception { Repository r = RepositoryManager.getRepository("multiprovidertest.properties"); TestUtil.emptyRepo(r); Session s = r.login(new SimpleCredentials("foo",new char[0])); Session s2 = r.login(new SimpleCredentials("foo",new char[0]),"testworkspace"); assertFalse( "Must end up in different workspaces", s.getWorkspace().getName().equals(s2.getWorkspace().getName()) ); Node nd = s2.getRootNode().addNode("largefiles"); nd = nd.addNode("test"); nd.setProperty("reallybig", 42); nd = s.getRootNode().addNode("small"); nd.setProperty("reallysmall", "foobar"); s.save(); s2.save(); File f = new File("/tmp/priha-multi/fileprovider/workspaces/default/small/reallysmall.info"); assertTrue("small", f.exists() ); File f2 = new File("/tmp/priha-multi/fileprovider2/workspaces/testworkspace/largefiles/test/reallybig.info"); assertTrue("big", f2.exists() ); Property p = (Property)s.getItem("/small/reallysmall"); assertEquals("small content","foobar",p.getString()); p = (Property)s2.getItem("/largefiles/test/reallybig"); assertEquals("big content", p.getLong(), 42 ); s.logout(); s2.logout(); TestUtil.emptyRepo(r); assertFalse("small remove", f.exists()); assertFalse("big remove", f2.exists()); } public void testSameNameSiblings() throws Exception { Node nd = m_session.getRootNode().addNode("test", "nt:unstructured"); Node nd21 = nd.addNode( "samename", "nt:unstructured" ); nd21.setProperty( "order", 1 ); Node nd22 = nd.addNode( "samename", "nt:unstructured" ); nd22.setProperty( "order", 2 ); Node nd23 = nd.addNode( "samename", "nt:unstructured" ); nd23.setProperty( "order", 3 ); m_session.save(); nd = (Node) m_session.getItem("/test/samename[1]"); assertEquals( "one", 1, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[2]"); assertEquals( "two", 2, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[3]"); assertEquals( "three", 3, nd.getProperty( "order" ).getLong() ); } public void testSameNameSiblingsRemoval() throws Exception { Node nd = m_session.getRootNode().addNode("test", "nt:unstructured"); Node nd21 = nd.addNode( "samename", "nt:unstructured" ); nd21.setProperty( "order", 1 ); Node nd22 = nd.addNode( "samename", "nt:unstructured" ); nd22.setProperty( "order", 2 ); Node nd23 = nd.addNode( "samename", "nt:unstructured" ); nd23.setProperty( "order", 3 ); m_session.save(); nd22.remove(); m_session.save(); nd = (Node) m_session.getItem("test"); NodeIterator ni = nd.getNodes(); assertEquals( "samename1", "/test/samename", ni.nextNode().getPath() ); assertEquals( "samename2", "/test/samename[2]", ni.nextNode().getPath() ); try { ni.nextNode(); fail("Got third node!"); } catch( NoSuchElementException e ) {} nd = (Node) m_session.getItem("/test/samename[1]"); assertEquals( "one", 1, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[2]"); assertEquals( "samename[3] not moved to samename[2]", 3, nd.getProperty( "order" ).getLong() ); } public static Test suite() { return new TestSuite( RepositoryTest.class ); } }
jalkanen/Priha
8ec1b4200584056bd7896268c8fcdfd2eba04271
* Bug 7: Running perftest is now possible even when Jackrabbit does not exist. Thanks to Kees Kuip.
diff --git a/ChangeLog b/ChangeLog index cc9694c..953f818 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,523 @@ +2009-12-05 Janne Jalkanen <jalkanen@ecyrd.com> + + * Bug 7: Running perftest is now possible even when Jackrabbit + does not exist. Thanks to Kees Kuip. + + * Bug 6: compile and compiletests -targets had wrong dirsets. + Thanks to Kees Kuip pointing this out. + + * ant clean would also delete generated sources - needing a + svn update. Now fixed. + 2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.1 * Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops. * Bug fix: XML serialization in System view would generate in some cases multi-valued properties when only single values were serialized. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.4 * Fixed a number of versioning unit tests by implementing Node.isCheckedOut()... 2008-10-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.3 * Massive reoptimization of FileProvider to do reference management properly. This also meant some additions to the Provider API. 2008-10-01 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.2 * XML Import works again * Item state changes are now replicated within a Session properly. * Test fails: 115/584. 2008-09-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.1 * Massive changes to the internal workings; Priha now correctly stores QNames internally as much as it can, converting to the correct namespace mapping at the last instance. Total fail rate for tests: 130/584. 2008-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.0 diff --git a/build.xml b/build.xml index 0fb6dee..dee04f6 100644 --- a/build.xml +++ b/build.xml @@ -1,252 +1,246 @@ <?xml version="1.0"?> <!-- A rather non-fancy build file. --> <project name="Priha" default="jar"> <description> Priha build file. </description> <property name="perftest.iterations" value="100"/> <property name="perftest.blobsize" value="10"/> <path id="path.build"> <fileset dir="lib"> <include name="*.jar" /> <exclude name="jackrabbit*" /> </fileset> <fileset dir="tests/lib"> <include name="*.jar" /> </fileset> <pathelement path="tests/etc" /> <pathelement path="build" /> <pathelement path="etc" /> <pathelement path="src/java" /> <pathelement path="tests/tck" /> </path> <path id="path.tests"> <!-- <pathelement location="${jarfile}" /> <pathelement location="${testjarfile}" /> --> <path refid="path.build"/> <pathelement path="tests/build" /> - <fileset dir="${user.home}/.maven/repository/org.apache.jackrabbit/jars/"> - <include name="*-1.6.*.jar"/> - </fileset> - - <fileset dir="${user.home}/.m2/repository/"> - <include name="commons-collections/**/*3.2.jar"/> - <include name="org/apache/lucene/lucene-core/2.2.0/*.jar"/> - <include name="org/apache/derby/derby/10.2.1.6/*.jar"/> - </fileset> + + <!-- Jackrabbit is only included if it has been installed with maven --> + <fileset dir="${user.home}"> + <include name=".maven/repository/org.apache.jackrabbit/jars/*-1.6.*.jar"/> + <include name=".m2/repository/commons-collections/**/*3.2.jar"/> + <include name=".m2/repository/org/apache/lucene/lucene-core/2.2.0/*.jar"/> + <include name=".m2/repository/org/apache/derby/derby/10.2.1.6/*.jar"/> + </fileset> </path> <!-- ================================= target: jar ================================= --> <target name="jar" depends="compile" description="Builds the main JAR file"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <echo>Building priha-${version}.jar</echo> <jar destfile="build/priha-${version}.jar"> <fileset dir="build"> <include name="org/priha/**"/> <exclude name="**/*.jj"/> <exclude name="**/*Test.class"/> <exclude name="**/*Tests.class"/> </fileset> <!-- <fileset dir="src/java"> <include name="**/*.xml"/> </fileset> --> <fileset dir="etc"> <include name="priha_default.properties"/> </fileset> <fileset dir="."> <include name="LICENSE"/> </fileset> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Implementation-Vendor" value="Janne Jalkanen (jalkanen@ecyrd.com)"/> <attribute name="Implementation-Title" value="Priha Java Content Repository"/> <attribute name="Implementation-Version" value="${version}"/> <attribute name="Implementation-URL" value="http://www.priha.org/"/> <attribute name="Specification-Title" value="JSR-170 Java Content Repository"/> <attribute name="Main-Class" value="org/priha/Release"/> </manifest> </jar> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile"> <mkdir dir="build"/> <javac destdir="build" target="1.5" debug="on" optimize="on"> - <src> - <dirset dir="src/java"/> - <dirset dir="src/generated-sources"/> - </src> + <src path="src/java"/> + <src path="src/generated-sources"/> <classpath refid="path.build"/> </javac> </target> <target name="compiletests" depends="compile"> <mkdir dir="tests/build"/> <javac destdir="tests/build" target="1.5" debug="on"> - <src> - <dirset dir="tests/java"/> - <dirset dir="tests/tck"/> - </src> + <src path="tests/java"/> + <src path="tests/tck"/> <classpath refid="path.build"/> </javac> </target> <!-- Looks like this creates an invalid JJT file. It needs some manual editing, so we'll just generate it once and check it into SVN. --> <target name="xpath-jjt"> <mkdir dir="src/generated-sources"/> <xslt style="src/javacc/xpath/strip.xsl" in="src/javacc/xpath/xpath-grammar.xml" out="src/generated-sources/stripped-xpath-grammar.xml" force="yes"/> <xslt style="src/javacc/xpath/jjtree-priha.xsl" in="src/generated-sources/stripped-xpath-grammar.xml" out="src/javacc/xpath/XPath.jjt" force="yes"/> </target> <target name="generatedsources"> <delete dir="src/generated-sources/org/priha/query/aqt/xpath"/> <mkdir dir="src/generated-sources/org/priha/query/aqt/xpath"/> <jjtree target="src/javacc/xpath/XPath.jjt" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath" javacchome="${user.home}/Java/javacc-3.2" nodepackage="org.priha.query.aqt.xpath"/> <javacc target="src/generated-sources/org/priha/query/aqt/xpath/XPath.jj" javacchome="${user.home}/Java/javacc-3.2" outputdirectory="src/generated-sources/org/priha/query/aqt/xpath"/> <!-- We have our own implementation of SimpleNode --> <delete file="src/generated-sources/org/priha/query/aqt/xpath/SimpleNode.java"/> </target> <target name="clean"> <delete dir="build"/> - <delete dir="src/generated-sources/org"/> </target> <target name="javadoc"> <mkdir dir="doc/javadoc"/> <javadoc destdir="doc/javadoc"> <packageset dir="src/java"> <include name="org/priha/**" /> </packageset> <packageset dir="src/generated-sources"> <include name="org/priha/**" /> </packageset> <classpath> <fileset dir="lib"> <include name="*.jar"/> </fileset> </classpath> </javadoc> </target> <!-- Runs some performance tests. You may specify new values for the parameters via ant -Dperftest.iterations=[num] -Dperftest.blobsize=[num] perftests perftest.iterations=how large the repository should be (in Nodes) perftest.blobsize=how large blobs should be stored into the store --> <target name="perftests" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <mkdir dir="/tmp/reports"/> <delete dir="repository" /> <echo message="Running performancetests on a repository size ${perftest.iterations} nodes and ${perftest.blobsize} kB blobs"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.tests" /> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <batchtest todir="tests/reports"> <fileset dir="tests/java"> <include name="**/PerformanceTest.java" /> </fileset> </batchtest> <jvmarg line="-Xmx2048m -Dperftest.iterations=${perftest.iterations} -Dperftest.blobsize=${perftest.blobsize} -Dcom.sun.management.jmxremote"/> </junit> <junitreport todir="/tmp/reports"> <fileset dir="tests/reports"> <include name="**/TEST-*.xml" /> </fileset> <report format="noframes" todir="/tmp/reports" /> </junitreport> </target> <target name="dist" depends="jar,javadoc"> <java classpath="build" outputproperty="version" classname="org.priha.Release" args="-versiononly"> </java> <zip zipfile="build/priha-${version}.zip"> <zipfileset dir="build" includes="*.jar" prefix="priha-${version}"/> <zipfileset dir="." includes="ChangeLog README doc/**" prefix="priha-${version}"/> <zipfileset dir="lib" includes="jcr-*.jar" prefix="priha-${version}"/> </zip> </target> <!-- Runs the entire JCR test suite. --> <target name="jcrtestsuite" depends="compile,compiletests"> <mkdir dir="tests/reports"/> <junit printsummary="yes" haltonfailure="no" fork="yes"> <classpath> <path refid="path.build" /> <pathelement location="tests/build"/> </classpath> <formatter type="plain" /> <formatter type="xml" usefile="yes" /> <test todir="tests/reports" name="org.apache.jackrabbit.test.JCRTestSuite"/> <jvmarg line="-Xmx2048m"/> </junit> <junitreport todir="tests/reports"> <fileset dir="tests/reports"> <include name="TEST-org.apache.jackrabbit.test.JCRTestSuite.xml" /> </fileset> <report format="noframes" todir="tests/reports" /> </junitreport> </target> </project>
jalkanen/Priha
dafa1f7a0045c5d971be6062c02e23a05c018207
* Slightly improved FileProvider serialization algorithm - the garbage collection is only performed every 30 seconds, tops.
diff --git a/ChangeLog b/ChangeLog index 11774eb..cc9694c 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,523 @@ +2009-11-24 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.6.1 + + * Slightly improved FileProvider serialization algorithm - the + garbage collection is only performed every 30 seconds, tops. + + * Bug fix: XML serialization in System view would generate + in some cases multi-valued properties when only single values + were serialized. + 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.6.0 * Improved repository startup speed by a factor of four; replaced XPath.evaluate() with custom code. * FileProvider storage format changed slightly to avoid colons and non-letters as starting characters in file/dir names. Need someone to test this on Windows. 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.4 * Fixed a number of versioning unit tests by implementing Node.isCheckedOut()... 2008-10-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.3 * Massive reoptimization of FileProvider to do reference management properly. This also meant some additions to the Provider API. 2008-10-01 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.2 * XML Import works again * Item state changes are now replicated within a Session properly. * Test fails: 115/584. 2008-09-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.1 * Massive changes to the internal workings; Priha now correctly stores QNames internally as much as it can, converting to the correct namespace mapping at the last instance. Total fail rate for tests: 130/584. 2008-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.0 * Renamed packages to org.priha. 2008-08-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.0.30 * Turned on versioning support; still doesn't work but at least some of the classes are there. * Initial implementation of namespace remapping; something diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 2e8e706..dab9457 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,116 +1,116 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 6; /** * The current minor revision. */ - public static final int MINORREVISION = 0; + public static final int MINORREVISION = 1; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index 4968534..d8c9105 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -20,1619 +20,1627 @@ package org.priha.providers; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import java.io.*; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.core.binary.FileBinarySource; import org.priha.core.values.QValue; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.Path.Component; import org.priha.util.*; /** * A simple file system -based provider. This is not particularly optimized. * Stores UUIDs and references as journaling files which are compacted * at every N writes and on shutdown. If there is a power outage just * in the middle of this process, it's possible that the file ends up * being corrupted. Currently there is no way to rebuild the UUIDs. * <p> * The FileProvider does not support failure recovery at the moment. So it's probably not * the best provider for production systems. */ public class FileProvider implements RepositoryProvider, PerformanceReporter { private static final String PROP_NUM_PROPERTIES = "numProperties"; private static final String PROP_MULTIPLE = "multiple"; private static final String PROP_TYPE = "type"; private static final String PROP_PATH = "path"; private static final int BUFFER_SIZE = 4096; private static final String LOCKFILE = ".prihalock"; private String m_root; private String m_workspaceRoot; private Logger log = Logger.getLogger( getClass().getName() ); private long[] m_hitCount; private Path m_systemPath; private Map<String,UUIDObjectStore<Path[]>> m_references = new HashMap<String, UUIDObjectStore<Path[]>>(); private Map<String,UUIDObjectStore<Path>> m_uuids = new HashMap<String, UUIDObjectStore<Path>>(); public FileProvider() throws RepositoryException { resetCounts(); } /** * Returns the File which houses all of the workspaces. * @return */ private String getWorkspaceRoot() { if( m_workspaceRoot == null ) { m_workspaceRoot = m_root + "/workspaces"; } return m_workspaceRoot; } /** * Figures out what the filename for a Workspace is. * @param ws * @return */ // FIXME: Should escape the filename properly. private String getWorkspaceFilename( Workspace ws ) { return ws.getName(); } /** * Figures out the what the filename for a given path is. * @param path * @return * @throws RepositoryException * @throws NamespaceException */ // FIXME: Should escape the path properly private String getPathFilename( Path path ) throws NamespaceException, RepositoryException { String p = path.toString( RepositoryImpl.getGlobalNamespaceRegistry() ); return mangleName(p); } /** * Create a valid filename based on the QName and a suffix. * * @param name * @param suffix * @return */ private String makeFilename( QName name, String suffix ) { String filename; try { filename = RepositoryImpl.getGlobalNamespaceRegistry().fromQName(name); } catch( NamespaceException e ) { filename = name.getLocalPart(); } if( suffix != null ) filename = filename + suffix; return mangleName(filename); } /** * Returns the directory for a particular Workspace. * * @param wsname * @return */ private String getWorkspaceDir( String wsname ) { String wsDir = getWorkspaceRoot() + "/" + wsname; return wsDir; } /** * Returns the directory in which a particular Node in a particular workspace resides * * @param ws * @param path * @return * @throws RepositoryException * @throws NamespaceException */ private File getNodeDir( Workspace ws, Path path ) throws NamespaceException, RepositoryException { if( m_systemPath.isParentOf( path ) || m_systemPath.equals( path ) ) { return new File( m_root, getPathFilename(path) ); } String wsDir = getWorkspaceDir( getWorkspaceFilename(ws) ); File nodeDir = new File( wsDir, getPathFilename(path) ); return nodeDir; } public void addNode(StoreTransaction tx, Path path, QNodeDefinition def) throws RepositoryException { m_hitCount[Count.AddNode.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path ); nodeDir.mkdirs(); if( !path.isRoot() ) { List<String> order = getOrder(ws,path.getParentPath()); if( !order.contains( path.getLastComponent().toString() ) ) { order.add( path.getLastComponent().toString() ); saveOrder( ws, path.getParentPath(), order ); } } } private void acquirePaths( Path startPath, File dir, List<Path> list, boolean recurse ) { File[] files = dir.listFiles(); if( files == null || files.length == 0 ) return; for( File f : files ) { if( f.isDirectory() ) { try { Properties props = getPropertyInfo( f, Q_JCR_PRIMARYTYPE ); Path p = PathFactory.getPath( props.getProperty( PROP_PATH ) ); list.add( p.getParentPath() ); if( recurse ) { acquirePaths( p.getParentPath(), f, list, recurse ); } } catch( PathNotFoundException e ) { // Skip, don't include. } catch( IOException e ) { // Skip, don't include. } catch (NamespaceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidPathException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch( NullPointerException e ) { e.printStackTrace(); } } } } public List<String> listWorkspaces() { m_hitCount[Count.ListWorkspaces.ordinal()]++; ArrayList<String> list = new ArrayList<String>(); File[] dirs = new File(getWorkspaceRoot()).listFiles(); if( dirs != null ) { for( File f : dirs ) { if( f.isDirectory() ) { list.add( f.getName() ); } } } return list; } private boolean deleteContents( File dir ) { // System.out.println("Deleting "+dir.getAbsolutePath()); for( File f : dir.listFiles() ) { if( f.isDirectory() ) { deleteContents( f ); } if( !f.delete() ) return false; } return true; } public void start(RepositoryImpl rep, Properties props) throws ConfigurationException { m_hitCount[Count.Start.ordinal()]++; try { m_systemPath = PathFactory.getPath( RepositoryImpl.getGlobalNamespaceRegistry(), "/jcr:system" ); } catch( RepositoryException e ) { throw new ConfigurationException("Unable to create a /jcr:system instance: "+e.getMessage()); } String wsList = props.getProperty("workspaces", "default"); m_root = props.getProperty("directory"); // // Make sure that root exists. // File root = new File(m_root); root.mkdirs(); // // Make sure this instance is the only one using that root. // File lockFile = new File(m_root, LOCKFILE); if( lockFile.exists() ) { String msg = "Cannot use the Priha FileProvider repository while another instance of Priha is using it. "+ "If you are sure there are no other instances using this same repository, please "+ "remove the '"+lockFile.getAbsolutePath()+"' file and restart."; log.severe( msg ); throw new ConfigurationException(msg); } // // Create the lock file; and make sure it gets cleaned up properly in // most cases. // try { lockFile.createNewFile(); lockFile.deleteOnExit(); } catch( IOException e ) { throw new ConfigurationException("Cannot start Priha ",e); } // // Initializing the workspaces. // log.fine("Initializing FileProvider with root "+m_root); String[] workspaces = wsList.split("\\s"); for( String wsname : workspaces ) { File wsroot = new File(getWorkspaceDir(wsname)); if( !wsroot.exists() ) { wsroot.mkdirs(); log.finer("Created workspace directory "+wsroot); } // // Reset the workspaces. // m_references.put( wsname, new UUIDObjectStore<Path[]>(mangleName(wsname)+"-references.ser") ); m_uuids.put( wsname, new UUIDObjectStore<Path>(mangleName(wsname)+"-uuid.ser") ); } } public void stop(RepositoryImpl rep) { m_hitCount[Count.Stop.ordinal()]++; log.fine("Shutting down FileProvider..."); for( UUIDObjectStore<Path[]> s : m_references.values() ) { s.shutdown(); } for( UUIDObjectStore<Path> s : m_uuids.values() ) { s.shutdown(); } m_references.clear(); m_uuids.clear(); // // Clean up the lockfile, in case we're e.g. switching repos mid-flight. // File lockFile = new File(m_root, LOCKFILE); lockFile.delete(); } public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Copy.ordinal()]++; throw new UnsupportedRepositoryOperationException("copy()"); } public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws NamespaceException, RepositoryException { m_hitCount[Count.ListNodes.ordinal()]++; ArrayList<Path> list = new ArrayList<Path>(); File startPath = getNodeDir( ws, parentpath ); if( !startPath.exists() ) throw new PathNotFoundException("No such path found: "+parentpath); //acquirePaths( parentpath, startPath, list, false ); List<String> orderArray = getOrder( ws, parentpath ); for( String s : orderArray ) { Path childPath = parentpath.resolve( Path.Component.valueOf( s ) ); list.add( childPath ); } // // The .order -file will probably not contain the system path for anyone else // except the workspace which was created first. // if( parentpath.isRoot() && !list.contains( m_systemPath )) { list.add( 0, m_systemPath ); } return list; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.ListProperties.ordinal()]++; File nodeDir = getNodeDir( ws, path ); List<QName> proplist = new ArrayList<QName>(); try { File[] files = nodeDir.listFiles( new PropertyTypeFilter() ); if( files != null ) { for( File propertyFile : files ) { Properties props; FileInputStream in = null; try { in = new FileInputStream(propertyFile); props = FastPropertyStore.load(in); String qname = props.getProperty(PROP_PATH); proplist.add( PathFactory.getPath( qname ).getLastComponent() ); } finally { if( in != null ) in.close(); } } } } catch( IOException e ) { throw new RepositoryException("Thingy said booboo", e); } return proplist; } public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Move.ordinal()]++; throw new UnsupportedRepositoryOperationException("move()"); } /** * A Node exists only if it has a primaryType.info in the directory. */ public boolean nodeExists(WorkspaceImpl ws, Path path) { m_hitCount[Count.NodeExists.ordinal()]++; File nodeDir; try { nodeDir = getNodeDir( ws, path ); File propFile = new File( nodeDir, mangleName("jcr:primaryType.info") ); return propFile.exists(); } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_hitCount[Count.Open.ordinal()]++; List<String> wsnames = listWorkspaces(); if( wsnames.indexOf(workspaceName) == -1 ) throw new NoSuchWorkspaceException(workspaceName); log.finer("Workspace "+workspaceName+" has been opened."); } public void close(WorkspaceImpl ws) { log.finer( "Workspace "+ws.getName()+" closing..." ); m_hitCount[Count.Close.ordinal()]++; - + /* try { m_uuids.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } catch( NullPointerException e ) { log.warning( "A non-configured workspace '"+ws.getName()+"' detected. If you are using a multiprovider configuration, please check this workspace actually exists." ); return; } try { m_references.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } + */ } private void writeValue( File f, ValueImpl v ) throws IOException, IllegalStateException, RepositoryException { OutputStream out = null; InputStream in = null; try { if( v instanceof QValue.QValueInner ) { byte[] ba = ((QValue.QValueInner)v).getQValue().getString().getBytes("UTF-8"); in = new ByteArrayInputStream(ba); } else { in = v.getStream(); } out = new FileOutputStream( f ); copyContents( in, out ); } finally { // // ...and close all the streams. // if( out != null ) { try { out.close(); } finally { if( in != null ) in.close(); } } } } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc) throws RepositoryException { m_hitCount[Count.PutPropertyValue.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path.getParentPath() ); saveUuidShortcut(ws,path,vc); QName qname = path.getLastComponent(); File inf = new File( nodeDir, makeFilename( qname, ".info" ) ); Properties props = new Properties(); props.setProperty( PROP_PATH, path.toString() ); props.setProperty( PROP_TYPE, PropertyType.nameFromValue( vc.getType() ) ); props.setProperty( PROP_MULTIPLE, vc.isMultiple() ? "true" : "false" ); OutputStream out = null; try { if( vc.isMultiple() ) { props.setProperty( PROP_NUM_PROPERTIES, Integer.toString(vc.getValues().length) ); Value[] values = vc.getValues(); // // Let's clear previous references, if this is an attempt to save // a null value. // if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl[] oldval = getPropertyValue( ws, path ).getValues(); for( ValueImpl vi : oldval ) { String uuid = vi.getString(); cleanRefMapping( ws, path, uuid ); } } catch( PathNotFoundException e ){} // This is okay } for( int i = 0; i < values.length; i++ ) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); saveRefShortcut( ws, path, (ValueImpl)values[i] ); writeValue( df, (ValueImpl)values[i] ); } // Remove the rest of old values int i = values.length; while(true) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); if( df.exists() ) df.delete(); else break; } } else { if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl oldval = getPropertyValue( ws, path ).getValue(); cleanRefMapping( ws, path, oldval.getString() ); } catch(PathNotFoundException e) {} // OK saveRefShortcut( ws, path, vc.getValue() ); } File df = new File( nodeDir, makeFilename( qname, ".data" ) ); writeValue( df, vc.getValue() ); } out = new FileOutputStream(inf); FastPropertyStore.store( out, props ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * Saves a shortcut to an UUID. The contents of the file are the path of the Node. * */ private void saveUuidShortcut(WorkspaceImpl ws, Path path, ValueContainer vc) throws RepositoryException { if( path.getLastComponent().equals(Q_JCR_UUID) ) { UUIDObjectStore<Path> uuids = m_uuids.get( ws.getName() ); uuids.setObject( vc.getValue().valueAsString(), path.getParentPath() ); } } private ValueImpl prepareValue( WorkspaceImpl ws, File propFile, String propType ) throws IOException, RepositoryException { ValueFactoryImpl vf = ws.getSession().getValueFactory(); ValueImpl value; if( propType.equals(PropertyType.TYPENAME_STRING) ) { value = vf.createValue( readContentsAsString(propFile) ); } else if( propType.equals(PropertyType.TYPENAME_BOOLEAN) ) { value = vf.createValue( "true".equals(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DOUBLE) ) { value = vf.createValue( Double.parseDouble(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_LONG) ) { value = vf.createValue( Long.parseLong(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DATE) ) { value = vf.createValue( readContentsAsString( propFile ), PropertyType.DATE ); } else if( propType.equals(PropertyType.TYPENAME_NAME) ) { String qnameStr = readContentsAsString(propFile); QName qn = QName.valueOf( qnameStr ); value = vf.createValue( qn, PropertyType.NAME ); } else if( propType.equals(PropertyType.TYPENAME_PATH )) { String val = readContentsAsString(propFile); value = vf.createValue( val, PropertyType.PATH ); } else if( propType.equals(PropertyType.TYPENAME_REFERENCE ) ) { value = vf.createValue( readContentsAsString(propFile), PropertyType.REFERENCE ); } else if( propType.equals(PropertyType.TYPENAME_BINARY) ) { value = vf.createValue( new FileBinarySource(propFile) ); } else throw new RepositoryException("Cannot deserialize property type "+propType); return value; } /** * Returns the contents of the .info -file. * * @param nodeDir * @return * @throws PathNotFoundException * @throws IOException */ private Properties getPropertyInfo( File nodeDir, QName name ) throws PathNotFoundException, IOException { File inf = new File( nodeDir, makeFilename( name, ".info" ) ); if( !inf.exists() ) { throw new PathNotFoundException("The property metadata file was not found: "+inf.getAbsolutePath()); } Properties props; FileInputStream in = null; try { in = new FileInputStream( inf ); props = FastPropertyStore.load(in); } finally { if( in != null ) in.close(); } return props; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.GetPropertyValue.ordinal()]++; File nodeDir = getNodeDir( ws, path.getParentPath() ); try { Properties props = getPropertyInfo( nodeDir, path.getLastComponent() ); String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); ValueImpl[] result = new ValueImpl[items]; for( int i = 0; i < items; i++ ) { File df = new File( nodeDir, makeFilename(path.getLastComponent(),"."+i+".data") ); ValueImpl v = prepareValue( ws, df, propType ); result[i] = v; } return new ValueContainer(result, PropertyType.valueFromName( propType ) ); } File df = new File( nodeDir, makeFilename( path.getLastComponent(), ".data" ) ); ValueImpl v = prepareValue(ws, df, propType); return new ValueContainer(v); } catch( IOException e ) { throw new RepositoryException("Unable to read property file",e); } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: This method is extremely speed-critical // TODO: Protect against windows special names (CON) etc. protected static String mangleName( String name ) { StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } else if( ch == ':' ) { // Colon is not allowed on NTFS or OSX. sb.append( ';' ); } else if( ch >= 'A' && ch <= 'Z' ) { // JSR-170 is case sensitive, so we have to make // sure our storage is too. sb.append( ch ); sb.append( '^' ); } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } return sb.toString(); } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } /** * Just copies all characters from <i>in</i> to <i>out</i>. */ private static void copyContents( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private static void copyContents(Reader in, Writer out) throws IOException { char[] buf = new char[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private String readContentsAsString( File file ) throws IOException { Reader in = new InputStreamReader( new FileInputStream(file), "UTF-8" ); try { StringWriter out = new StringWriter(); copyContents( in, out ); return out.toString(); } finally { in.close(); } } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; + private long m_lastWrite = System.currentTimeMillis(); /* After this many writes the store is compacted. */ - private static final int COMPACT_LIMIT = 100; + private static final int COMPACT_LIMIT = 100; + + /* But compacting is not done more often than this limit (in ms) */ + private static final long COMPACT_TIME_LIMIT = 30*1000L; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); - if( ++m_writeCount > COMPACT_LIMIT ) + long now = System.currentTimeMillis(); + if( ++m_writeCount > COMPACT_LIMIT && (now-m_lastWrite) > COMPACT_TIME_LIMIT ) { + System.out.println( now-m_lastWrite ); serialize(); m_writeCount = 0; + m_lastWrite = now; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { -// System.out.println("++++++ COMPACTING..."); + System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } } diff --git a/src/java/org/priha/xml/XMLImport.java b/src/java/org/priha/xml/XMLImport.java index 2dc9aeb..555d46a 100644 --- a/src/java/org/priha/xml/XMLImport.java +++ b/src/java/org/priha/xml/XMLImport.java @@ -1,573 +1,584 @@ package org.priha.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import javax.jcr.nodetype.ConstraintViolationException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.priha.core.JCRConstants; import org.priha.core.NodeImpl; import org.priha.core.SessionImpl; import org.priha.core.namespace.NamespaceRegistryImpl; +import org.priha.core.values.ValueImpl; import org.priha.nodetype.QPropertyDefinition; import org.priha.path.Path; import org.priha.util.Base64; import org.priha.util.QName; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Does the chunky work of importing stuff into the repository. Always requires * a Session within which the stuff is sent to the repo; however, you can * either ask the importer to commit stuff on its own, or just skip it. */ public class XMLImport extends DefaultHandler { private SessionImpl m_session; private boolean m_immediateCommit; private Path m_currentPath; private int m_uuidBehavior; private ParserStyle m_style = ParserStyle.UNKNOWN; private NodeImpl m_currentNode; private NodeStore m_currentStore; private PropertyStore m_currentProperty; private boolean m_readingValue = false; + private StringBuilder m_charContent; private static Logger log = Logger.getLogger(XMLImport.class.getName()); public XMLImport( SessionImpl session, boolean immediateCommit, Path startPath, int uuidBehavior ) throws RepositoryException { if( !session.getRootNode().hasNode(startPath.toString()) ) - throw new PathNotFoundException("The parent path does not exist, so cannot import to it!"); + throw new PathNotFoundException("The parent path "+startPath+" does not exist, so cannot import to it!"); m_session = session; m_immediateCommit = immediateCommit; m_currentPath = startPath; m_uuidBehavior = uuidBehavior; m_currentNode = session.getRootNode().getNode( startPath.toString() ); } public void doImport( InputStream xmlDoc ) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware( true ); spf.setValidating( false ); spf.setFeature( "http://xml.org/sax/features/namespace-prefixes", true ); SAXParser parser = spf.newSAXParser(); boolean s = m_session.setSuper( true ); try { parser.parse( xmlDoc, this ); } finally { m_session.setSuper( s ); } } private void checkSystem() throws SAXException { if( m_style == ParserStyle.DOCUMENT ) throw new SAXException("System View elements found in a Document View document!"); m_style = ParserStyle.SYSTEM; } private void checkDocument() throws SAXException { if( m_style == ParserStyle.SYSTEM ) throw new SAXException("Document view elements found in a System level document."); m_style = ParserStyle.DOCUMENT; } private PropertyStore getProp(NodeStore ns, QName name) { for( PropertyStore ps : ns.m_properties ) { if( ps.m_propertyName.equals(name) ) return ps; } return null; } /** * This method takes the item which has just been read from the XML * event stream, and creates the corresponding Nodes and Properties in the repository. * * @param ns The NodeStore * @throws ValueFormatException * @throws IllegalStateException * @throws RepositoryException */ private void deserializeStore( NodeStore ns ) throws ValueFormatException, IllegalStateException, RepositoryException { PropertyStore psp = getProp(ns,JCRConstants.Q_JCR_PRIMARYTYPE); String primaryType; String uuid = null; NodeImpl uuidNode = null; if( psp != null && psp.m_values.size() > 0 ) primaryType = psp.m_values.get(0).getString(); else primaryType = "nt:unstructured"; // FIXME: Stupid guess. String path = m_currentPath.toString(); log.finest("Deserializing node at "+path); if( m_session.itemExists(path) ) { throw new ItemExistsException("There already exists a node at "+path); } // // Find the UUID and, if it exists, a possible previous Node which // has the same UUID. // PropertyStore uuidPS = ns.findProperty( JCRConstants.Q_JCR_UUID ); if( uuidPS != null ) { uuid = uuidPS.m_values.get(0).getString(); try { uuidNode = m_session.getNodeByUUID( uuid ); } catch( ItemNotFoundException e ) {} } NodeImpl nd; // // Do we need to replace an existing Node with the same UUID? // if( m_uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING && uuid != null && uuidNode != null ) { log.fine("Replacing node "+uuidNode.getPath()+" due to UUID_COLLISION_REPLACE_EXISTING"); NodeImpl parent = uuidNode.getParent(); uuidNode.remove(); m_currentNode = parent; } +// System.out.println("Adding "+m_currentStore.m_nodeName); + nd = m_currentNode.addNode( m_currentStore.m_nodeName, primaryType ); // // If there's an UUID, we have to figure out what to do with it. // if( uuid != null ) { //nd.addMixin( "mix:referenceable" ); switch( m_uuidBehavior ) { case ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW: if( uuidNode != null ) throw new ItemExistsException("UUID "+uuid+" already exists in repository, and IMPORT_UUID_COLLISION_THROW was defined."); nd.setProperty( "jcr:uuid", uuid ); break; case ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW: // Will be created automatically on save() break; case ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING: if( uuidNode != null ) { // Yes, there is a collision if( uuidNode.getInternalPath().isParentOf( m_currentPath ) ) { throw new ConstraintViolationException("Importing this node ("+nd.getPath()+") would result in one of its parents being removed - "+ "which, in general, is kinda like traveling back in time and shooting your "+ "grandparents. Most time traveling guidelines strongly recommend against this, as "+ "it will lead to paradoxes. This is also why it is not possible within JCR. Not that "+ "this is exactly time travel technology, far from it, but it just keeps stuff neat "+ "and tidy, you know."); } log.fine("Removing node "+uuidNode.getPath()+" due to UUID_COLLISION_REMOVE_EXISTING"); log.fine("New node is "+nd); uuidNode.remove(); } nd.setProperty( "jcr:uuid", uuid ); break; case ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING: nd.setProperty( "jcr:uuid", uuid ); break; } } m_currentNode = nd; for( PropertyStore ps : ns.m_properties ) { // // Known property names which need to be handled separately. // if( ps.m_propertyName.equals(JCRConstants.Q_JCR_PRIMARYTYPE) ) continue; if( ps.m_propertyName.equals(JCRConstants.Q_JCR_MIXINTYPES) ) { for( Value v : ps.m_values ) { nd.addMixin( v.getString() ); } continue; } // Already handled if( ps.m_propertyName.equals(JCRConstants.Q_JCR_UUID) ) continue; // We don't yet support exporting version histories. if( ps.m_propertyName.equals(JCRConstants.Q_JCR_BASEVERSION) ) continue; // // Start the real unmarshalling // log.finest(" Property: "+ps.m_propertyName); // // Now we try to figure out whether this should be a multi or a single property. // The problem is when it is a multi property, but it was written as a single value. // // If there is a multidefinition, but no single definition, we assume this // to be a multiproperty. If both exist, we'll assume a single property, unless // the single property is matched to be a wildcard. // QPropertyDefinition pdmulti = nd.findPropertyDefinition( ps.m_propertyName, true ); QPropertyDefinition pdsingle = nd.findPropertyDefinition( ps.m_propertyName, false ); boolean ismultiproperty = (pdmulti != null && (pdsingle == null || (pdsingle != null && pdsingle.isWildCard() && !pdmulti.isWildCard()) ) ); if( ps.m_values.size() == 1 && !ismultiproperty ) { nd.setProperty( m_session.fromQName( ps.m_propertyName ), ps.m_values.get(0) ); //System.out.println(" "+ps.m_propertyName+" => SINGLE = "+ps.m_values.get(0)); } else { nd.setProperty( m_session.fromQName( ps.m_propertyName ), ps.m_values.toArray( new Value[ps.m_values.size()] ) ); //System.out.println(" "+ps.m_propertyName+" => MULTI = "+ps.m_values.size()+" items"); } } // System.out.println("Imported new node "+nd); if( m_immediateCommit ) { m_session.save(); } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { String name = qName != null ? qName : localName; if( name.equals("sv:node") ) { checkSystem(); String nodeName = attrs.getValue("sv:name"); // Hitting a new Node means that all the properties have been read, // so we can deserialize the last store. if( m_currentStore != null ) { try { log.finest("New -> "); deserializeStore( m_currentStore ); } catch( Exception e ) { throw new SAXException("Deserialization failed",e); } } m_currentStore = new NodeStore(); if( nodeName.equals("jcr:root") ) { nodeName = "/"; } - + m_currentStore.m_nodeName = nodeName; try { m_currentPath = m_currentPath.resolve(m_session.toQName( nodeName ) ); } catch( RepositoryException e ) { throw new SAXException(e); } return; } else if( name.equals("sv:property") ) { checkSystem(); try { NamespaceRegistryImpl nr = m_session.getWorkspace().getNamespaceRegistry(); String propName = attrs.getValue("sv:name"); String propType = attrs.getValue("sv:type"); m_currentProperty = new PropertyStore(); m_currentProperty.m_propertyName = nr.toQName( propName ); m_currentProperty.m_propertyType = PropertyType.valueFromName( propType ); } catch( Exception e ) { throw new SAXException("Unable to parse property name",e); } return; } else if( name.equals("sv:value") ) { checkSystem(); m_readingValue = true; + m_charContent = new StringBuilder(); return; } // // Alright, this is then a Document view document. // checkDocument(); String nodeName = name; m_currentStore = new NodeStore(); m_currentStore.m_nodeName = nodeName; try { for( int i = 0; i < attrs.getLength(); i++ ) { String attname = attrs.getQName(i); if( attname.equals( "" ) ) attname = attrs.getLocalName(i); m_currentProperty = new PropertyStore(); String attvalue = attrs.getValue(i); NamespaceRegistryImpl nr = m_session.getWorkspace().getNamespaceRegistry(); m_currentProperty.m_propertyName = nr.toQName( attname ); m_currentProperty.m_propertyType = PropertyType.STRING; m_currentProperty.addValue( m_session.getValueFactory().createValue( attvalue ) ); m_currentStore.m_properties.add( m_currentProperty ); } m_currentPath = m_currentPath.resolve(m_session.toQName( nodeName ) ); deserializeStore( m_currentStore ); } catch( RepositoryException e ) { throw new SAXException(e); } return; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String name = qName != null ? qName : localName; if( name.equals("sv:node") ) { boolean isSuper = m_session.setSuper( true ); try { log.finest("End -> "); if( m_currentStore != null ) deserializeStore( m_currentStore ); m_currentNode = m_currentNode.getParent(); m_currentPath = m_currentPath.getParentPath(); m_currentStore = null; } catch (RepositoryException e) { log.log( Level.WARNING, "Node deserialization failed", e ); throw new SAXException("Could not deserialize node",e); } finally { m_session.setSuper( isSuper ); } } else if( name.equals("sv:value") ) { - m_readingValue = false; + if( m_readingValue ) + { + ValueImpl v; + + try + { + if( m_currentProperty.m_propertyType == PropertyType.BINARY ) + { + InputStream in = new Base64.InputStream( new ByteArrayInputStream(m_charContent.toString().getBytes("UTF-8")) ); + v = m_session.getValueFactory().createValue( in ); + } + else + { + v = m_session.getValueFactory().createValue( m_charContent.toString(), + m_currentProperty.m_propertyType ); + } + m_currentProperty.m_values.add( v ); + } + catch (Exception e) + { + log.log( Level.WARNING, "Node deserialization failed; unable to parse a variable value", e ); + throw new SAXException("Could not deserialize node",e); + } + finally + { + m_readingValue = false; + m_charContent = null; + } + } } else if( name.equals("sv:property") ) { m_currentStore.m_properties.add( m_currentProperty ); m_currentProperty = null; } else { // Document view try { m_currentPath = m_currentPath.getParentPath(); m_currentNode = m_currentNode.getParent(); } catch( Exception e ) { throw new SAXException(e); } } } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { // System.out.println(prefix + " = " + uri ); try { NamespaceRegistry r = m_session.getWorkspace().getNamespaceRegistry(); r.registerNamespace( prefix, uri ); } catch( NamespaceException e ) { // Ignore quietly; this is usually because there are mappings in the // document which are known to us. // e.printStackTrace(); } catch( RepositoryException e ) { throw new SAXException(e); } } /** * Parse the character data coming in; that is, create the Values which are put * into the properties. * <p> * Unfortunately, this method handles Binary properties by reading them completely * into memory as a String, and turning that into a byte array, essentially taking * 3x the amount of memory that what it should. Better solutions are welcomed... */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if( m_style == ParserStyle.DOCUMENT ) { try { String valueString = new String(ch,start,length); + // FIXME: Should not do this yet NodeImpl xmlText = m_currentNode.addNode( "jcr:xmltext" ); xmlText.setProperty( "jcr:xmlcharacters", valueString ); } catch( RepositoryException e ) { throw new SAXException(e); } return; } // System if( m_readingValue ) { - try - { - Value v; - String valueString = new String(ch,start,length); - if( m_currentProperty.m_propertyType == PropertyType.BINARY ) - { - InputStream in = new Base64.InputStream( new ByteArrayInputStream(valueString.getBytes("UTF-8")) ); - v = m_session.getValueFactory().createValue( in ); - } - else - { - v = m_session.getValueFactory().createValue( valueString, - m_currentProperty.m_propertyType ); - } - m_currentProperty.m_values.add( v ); - } - catch (ValueFormatException e) - { - throw new SAXException("Value creation failed",e); - } - catch (UnsupportedEncodingException e) - { - throw new SAXException("You can't be serious that your platform does not support UTF-8!?!"); - } - catch( RepositoryException e ) - { - throw new SAXException("Something horrible happened",e); - } + String valueString = new String(ch,start,length); + + if( m_charContent == null ) m_charContent = new StringBuilder(); + + m_charContent.append(valueString); } } /** Just stores the state of the parser. */ private static enum ParserStyle { DOCUMENT, SYSTEM, UNKNOWN } private static class NodeStore { public String m_nodeName; public List<PropertyStore> m_properties = new ArrayList<PropertyStore>(); public PropertyStore findProperty( QName name ) { for( PropertyStore ps : m_properties ) { if( ps.m_propertyName.equals(name) ) return ps; } return null; } @Override public String toString() { return m_nodeName; } } private static class PropertyStore { public QName m_propertyName; public int m_propertyType; private List<Value> m_values = new ArrayList<Value>(); public void addValue(Value v) { m_values.add( v ); } @Override public String toString() { return m_propertyName.toString(); } } }
jalkanen/Priha
22e2afe66df7942cefbfc1d7c35a1267b78ee8c5
QNodeTypeManager now uses custom code instead of XPath.evaluate(), resulting in 4x startup speed. FileProvider now is a bit more fussy when determining filenames.
diff --git a/ChangeLog b/ChangeLog index 6586170..11774eb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,523 @@ +2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.6.0 + + * Improved repository startup speed by a factor of four; replaced + XPath.evaluate() with custom code. + + * FileProvider storage format changed slightly to avoid colons + and non-letters as starting characters in file/dir names. Need + someone to test this on Windows. + 2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.7 * FileProvider is now case-sensitive even on case-insensitive file systems. 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.4 * Fixed a number of versioning unit tests by implementing Node.isCheckedOut()... 2008-10-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.3 * Massive reoptimization of FileProvider to do reference management properly. This also meant some additions to the Provider API. 2008-10-01 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.2 * XML Import works again * Item state changes are now replicated within a Session properly. * Test fails: 115/584. 2008-09-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.1 * Massive changes to the internal workings; Priha now correctly stores QNames internally as much as it can, converting to the correct namespace mapping at the last instance. Total fail rate for tests: 130/584. 2008-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.0 * Renamed packages to org.priha. 2008-08-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.0.30 * Turned on versioning support; still doesn't work but at least some of the classes are there. * Initial implementation of namespace remapping; something is still missing though. 2008-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.0.29 * XML Import now works for System View. All SerializationTest tests now pass. Total fail rate for tests is 110 / 584. 2008-08-11 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index b4a3c2d..2e8e706 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,116 +1,116 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ - public static final int REVISION = 5; + public static final int REVISION = 6; /** * The current minor revision. */ - public static final int MINORREVISION = 7; + public static final int MINORREVISION = 0; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/core/RepositoryImpl.java b/src/java/org/priha/core/RepositoryImpl.java index 337f77b..cc11214 100644 --- a/src/java/org/priha/core/RepositoryImpl.java +++ b/src/java/org/priha/core/RepositoryImpl.java @@ -1,388 +1,398 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.core; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; +import java.util.logging.Level; import java.util.logging.Logger; import javax.jcr.*; import org.priha.Release; import org.priha.core.namespace.NamespaceRegistryImpl; import org.priha.util.ConfigurationException; import org.priha.util.FileUtil; /** * Provides the main Repository class for Priha. You may use this * by simply instantiating it with a suitable Properties object. */ public class RepositoryImpl implements Repository { public static final String DEFAULT_WORKSPACE = "default"; private static NamespaceRegistryImpl c_namespaceRegistry = new NamespaceRegistryImpl(); private RepositoryState m_state = RepositoryState.DEAD; /** * Defines which paths are attempted to locate the default property file. */ private static final String[] DEFAULT_PROPERTIES = { "/priha_default.properties", "/WEB-INF/priha_default.properties" }; private Properties m_properties; private Logger log = Logger.getLogger( getClass().getName() ); private SessionManager m_sessionManager; private ProviderManager m_providerManager; /** * Create a new Repository using the given properties. Any property which is not * set will be read from the default properties (priha_default.properties). * * @param prefs Properties to use. Must not be null. * @throws ConfigurationException If the properties are wrong. */ public RepositoryImpl( Properties prefs ) throws ConfigurationException { m_state = RepositoryState.STARTING; try { Properties defaultProperties = FileUtil.findProperties(DEFAULT_PROPERTIES); if( defaultProperties.isEmpty() ) throw new ConfigurationException("Default properties not found - broken distribution!?!"); m_properties = new Properties(defaultProperties); } catch (IOException e) { throw new ConfigurationException("Loading of default properties failed"); } if( prefs.isEmpty() ) log.warning("No \"priha.properties\" found, using just the default properties"); m_properties.putAll( prefs ); Runtime.getRuntime().addShutdownHook( new ShutdownThread() ); log.info( "G'day, Matilda! Priha "+Release.VERSTR+" has been initialized." ); log.fine( "Using configuration from "+prefs.toString() ); m_state = RepositoryState.LIVE; } public String getProperty(String key) { return m_properties.getProperty(key); } public String getProperty( String key, String defValue ) { return m_properties.getProperty(key,defValue); } protected ProviderManager getProviderManager() throws ConfigurationException { if( m_providerManager == null ) { log.info( "Initializing providers..." ); + long start = System.currentTimeMillis(); m_providerManager = new ProviderManager(this); + long end = System.currentTimeMillis(); + log.info( "Repository initialization took "+(end-start)+" ms." ); } return m_providerManager; } protected SessionManager getSessionManager() { if( m_sessionManager == null ) { log.info( "Initializing SessionManager..." ); m_sessionManager = new SessionManager(); } return m_sessionManager; } /** * Set transient properties for this repository. These are not saved anywhere, but they * might be something that you can use to control the Repository behaviour with. * @param key * @param property */ public void setProperty(String key, String property) { m_properties.setProperty(key,property); } @SuppressWarnings("unchecked") public Enumeration<String> getPropertyNames() { return (Enumeration<String>)m_properties.propertyNames(); } public String getDescriptor(String key) { for( int i = 0; i < Release.DESCRIPTORS.length; i += 2 ) { if( Release.DESCRIPTORS[i].equals(key) ) { return Release.DESCRIPTORS[i+1]; } } return null; } public String[] getDescriptorKeys() { String[] keys = new String[Release.DESCRIPTORS.length/2]; for( int i = 0; i < Release.DESCRIPTORS.length; i += 2 ) { keys[i/2] = Release.DESCRIPTORS[i]; } return keys; } private String getDefaultWorkspace() throws ConfigurationException { return getProviderManager().getDefaultWorkspace(); } public synchronized SessionImpl login(Credentials credentials, String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { if( m_state != RepositoryState.LIVE ) { throw new RepositoryException("Repository is not alive. It is "+m_state); } + long start = System.currentTimeMillis(); if( workspaceName == null ) workspaceName = getDefaultWorkspace(); getProviderManager().open( credentials, workspaceName ); SessionImpl session = getSessionManager().openSession( credentials, workspaceName ); session.refresh(false); + long end = System.currentTimeMillis(); + + if( log.isLoggable(Level.FINER) ) + log.finer("Login completed and new Session created; took "+(end-start)+" ms."); + return session; } public SessionImpl login(Credentials credentials) throws LoginException, RepositoryException { return login( credentials, null ); } public SessionImpl login(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { return login( null, workspaceName ); } public SessionImpl login() throws LoginException, RepositoryException { return login( null, null ); } /** * Shuts down the entire repository, stops all providers and releases * resources. After this call you can restart the repository by either * calling login(), or creating a new RepositoryImpl instance. */ public void shutdown() { m_state = RepositoryState.SHUTTING; // // Close all open sessions. // visit( new SessionVisitor() { public void visit(SessionImpl session) { session.logout(); } }); // // Stop the ProviderManager and release providers. // if( m_providerManager != null ) { m_providerManager.stop(); } m_providerManager = null; m_sessionManager = null; m_state = RepositoryState.DEAD; } /** * Returns a Session which has write permissions to the repository. Normally, the * user has no reason to use this method - it is used internally to sometimes modify * the repo. * <p> * This method is guaranteed to always return a Session which has all permissions * into the repository - assuming the underlying repository implementation does not * have any limitations (which it normally should not have). * * @param workspaceName The workspace to which the login is done. * @return A Priha SessionImpl object. * @throws LoginException * @throws NoSuchWorkspaceException * @throws RepositoryException */ public SessionImpl superUserLogin(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { SessionImpl s = login( null, workspaceName ); s.setSuper(true); return s; } public static NamespaceRegistryImpl getGlobalNamespaceRegistry() { return c_namespaceRegistry; } /** * Visits all current Sessions * * @param v */ protected void visit( SessionVisitor v ) { synchronized( getSessionManager().m_sessions ) { for( Iterator<WeakReference<SessionImpl>> i = getSessionManager().m_sessions.iterator(); i.hasNext(); ) { WeakReference<SessionImpl> wr = i.next(); SessionImpl si = wr.get(); if( si != null ) v.visit(si); else i.remove(); } } } protected void removeSession(SessionImpl s) { getSessionManager().closeSession(s); } /** * The SessionManager holds a list of Sessions currently owned by this Repository. This * is used to manage the proper shutdown of the Sessions. * */ // FIXME: Should probably have a ReferenceQueue for cleaning away things like locks, etc. private class SessionManager { private ArrayList<WeakReference<SessionImpl>> m_sessions = new ArrayList<WeakReference<SessionImpl>>(); public SessionImpl openSession( Credentials credentials, String workspaceName ) throws RepositoryException { synchronized(m_sessions) { SessionImpl session = new SessionImpl( RepositoryImpl.this, credentials, workspaceName ); m_sessions.add( new WeakReference<SessionImpl>(session) ); return session; } } public void closeSession( SessionImpl s ) { // // Make sure that if we're in the midst of shutdown, these get removed // automatically. // if( m_state == RepositoryImpl.RepositoryState.SHUTTING ) return; synchronized(m_sessions) { for( Iterator<WeakReference<SessionImpl>> i = m_sessions.iterator(); i.hasNext(); ) { WeakReference<SessionImpl> wr = i.next(); SessionImpl si = wr.get(); if( si == null || si == s ) { i.remove(); break; } } // FIXME: Should really check if there is a Session for this workspace // so that we can call ProviderManager.close(); } } } protected interface SessionVisitor { public void visit( SessionImpl session ); } /** * Stops the Provider which stores all the things in this Repository. This is used to * manage a sane shutdown. */ private class ShutdownThread extends Thread { @Override public void run() { log.info( "Running shutdown process (repository closed due to JVM termination)" ); shutdown(); } } private enum RepositoryState { LIVE, SHUTTING, STARTING, DEAD }; } diff --git a/src/java/org/priha/nodetype/QNodeTypeManager.java b/src/java/org/priha/nodetype/QNodeTypeManager.java index bb1b684..e73efa8 100644 --- a/src/java/org/priha/nodetype/QNodeTypeManager.java +++ b/src/java/org/priha/nodetype/QNodeTypeManager.java @@ -1,485 +1,505 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.nodetype; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.logging.Logger; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeIterator; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.version.OnParentVersionAction; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.priha.core.RepositoryImpl; import org.priha.core.SessionImpl; import org.priha.core.WorkspaceImpl; import org.priha.core.namespace.NamespaceMapper; import org.priha.util.ConfigurationException; import org.priha.util.QName; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * This class is essentially a singleton per repository. * * @author jalkanen * */ public class QNodeTypeManager { private SortedMap<QName,QNodeType> m_primaryTypes = new TreeMap<QName,QNodeType>(); private SortedMap<QName,QNodeType> m_mixinTypes = new TreeMap<QName,QNodeType>(); private Logger log = Logger.getLogger( getClass().getName() ); private static QNodeTypeManager c_instance; // TODO: When created, there is no Session object available. private QNodeTypeManager() throws RepositoryException { try { initializeNodeTypeList(); } catch( Exception e ) { e.printStackTrace(); throw new RepositoryException("Cannot start NodeTypeManager",e); } } public static synchronized QNodeTypeManager getInstance() throws RepositoryException { if( c_instance == null ) { c_instance = new QNodeTypeManager(); } return c_instance; } public static synchronized Impl getManager(WorkspaceImpl ws) throws RepositoryException { QNodeTypeManager mgr = getInstance(); return new Impl(mgr,ws.getSession()); } private void initializeNodeTypeList() throws ParserConfigurationException, IOException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputStream in = null; try { in = getClass().getClassLoader().getResourceAsStream( "org/priha/nodetype/builtin_nodetypes.xml" ); Document doc = builder.parse( in ); XPathFactory xpf = XPathFactory.newInstance(); XPath xp = xpf.newXPath(); NodeList types = (NodeList)xp.evaluate( "/nodetypes/nodetype", doc, XPathConstants.NODESET ); if( types.getLength() < 1 ) { log.severe("No default nodes were found! Everything is likely to be broken!"); } for( int i = 0; i < types.getLength(); i++ ) { parseSingleNodeType( types.item(i) ); } } catch( SAXException e ) { e.printStackTrace(); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchNodeTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) try { in.close(); } catch( Exception e ) {} } } private void parseSingleNodeType(Node node) throws XPathExpressionException, NoSuchNodeTypeException, RepositoryException { XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceMapper nsm = RepositoryImpl.getGlobalNamespaceRegistry(); - String name = xpath.evaluate( "name", node ); + String name = getStringProperty( xpath, "name", node ); log.finest( "Loading nodetype "+name ); QNodeType gnt = new QNodeType( nsm.toQName( name ) ); // // Basic Node Type properties // gnt.m_ismixin = getBooleanProperty(xpath,"isMixin", node ); gnt.m_hasOrderableChildNodes = getBooleanProperty(xpath, "hasOrderableChildNodes", node ); - String primaryItemName = xpath.evaluate( "primaryItemName", node ); + String primaryItemName = getStringProperty( xpath, "primaryItemName", node ); if( primaryItemName != null && primaryItemName.length() > 0 ) gnt.m_primaryItemName = nsm.toQName( primaryItemName ); - String superNode = xpath.evaluate( "supertypes", node ); + String superNode = getStringProperty( xpath, "supertypes", node ); if( superNode != null && superNode.length() > 0 ) { String[] nodes = parseList( superNode ); gnt.m_parents = new QNodeType[nodes.length]; for( int i = 0; i < nodes.length; i++ ) { gnt.m_parents[i] = getNodeType( nsm.toQName( nodes[i] ) ); } } // // Property definitions // NodeList propertyDefinitions = (NodeList) xpath.evaluate( "propertyDefinition", node, XPathConstants.NODESET ); ArrayList<QPropertyDefinition> pdlist = new ArrayList<QPropertyDefinition>(); for( int i = 0; i < propertyDefinitions.getLength(); i++ ) { QPropertyDefinition p = parsePropertyDefinition( gnt, propertyDefinitions.item(i) ); pdlist.add( p ); } gnt.m_declaredPropertyDefinitions = pdlist.toArray(new QPropertyDefinition[0]); // Add parent definitions if( gnt.m_parents != null ) { for( QNodeType nt : gnt.m_parents ) { for( QPropertyDefinition p : nt.m_propertyDefinitions ) { pdlist.add( p ); } } } gnt.m_propertyDefinitions = pdlist.toArray(new QPropertyDefinition[0]); // // Child node definitions NodeList nodeDefinitions = (NodeList) xpath.evaluate( "childNodeDefinition", node, XPathConstants.NODESET ); ArrayList<QNodeDefinition> ndlist = new ArrayList<QNodeDefinition>(); for( int i = 0; i < nodeDefinitions.getLength(); i++ ) { QNodeDefinition p = parseChildNodeDefinition( gnt, nodeDefinitions.item(i) ); ndlist.add( p ); } gnt.m_childNodeDefinitions = ndlist.toArray(new QNodeDefinition[0]); // // Add it to the proper place // if( gnt.m_ismixin ) m_mixinTypes.put( nsm.toQName( name ), gnt ); else m_primaryTypes.put( nsm.toQName( name ), gnt ); } private boolean getBooleanProperty( XPath xpath, String expression, Node node ) throws XPathExpressionException { - String res = xpath.evaluate( expression, node ); - - return "true".equals(res); + return "true".equals(getStringProperty(xpath,expression,node)); } + private String getStringProperty( XPath xpath, String expression, Node node ) throws XPathExpressionException + { + // + // For speed reasons, we use this iterator; XPath is really slow. This should give + // about 4x the performance for initial startup time overall. + // + if( true ) + { + for( Node child = node.getFirstChild(); child != null; child = child.getNextSibling() ) + { + if( child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(expression) ) + return child.getTextContent(); + } + + return null; + } + else + { + return xpath.evaluate(expression, node); + } + } + private QPropertyDefinition parsePropertyDefinition( QNodeType parent, Node node ) throws XPathExpressionException, RepositoryException { XPath xpath = XPathFactory.newInstance().newXPath(); - String name = xpath.evaluate( "name", node ); + String name = getStringProperty( xpath, "name", node ); log.finest( "Loading propertyDefinition "+name ); QPropertyDefinition pdi = new QPropertyDefinition(parent, RepositoryImpl.getGlobalNamespaceRegistry().toQName( name ) ); pdi.m_isAutoCreated = getBooleanProperty(xpath, "autoCreated", node); pdi.m_isMandatory = getBooleanProperty(xpath, "mandatory", node); pdi.m_isMultiple = getBooleanProperty(xpath, "multiple", node); pdi.m_isProtected = getBooleanProperty(xpath, "protected", node); - String requiredType = xpath.evaluate( "requiredType", node ); + String requiredType = getStringProperty( xpath, "requiredType", node ); pdi.m_requiredType = PropertyType.valueFromName( requiredType ); - String onParentVersion = xpath.evaluate( "onParentVersion", node ); + String onParentVersion = getStringProperty( xpath, "onParentVersion", node ); pdi.m_onParentVersion = OnParentVersionAction.valueFromName( onParentVersion ); - String valueConstraints = xpath.evaluate( "valueConstraints", node ); + String valueConstraints = getStringProperty( xpath, "valueConstraints", node ); pdi.m_valueConstraints = parseList( valueConstraints ); - String defaultValue = xpath.evaluate( "defaultValues", node ); + String defaultValue = getStringProperty( xpath, "defaultValues", node ); pdi.m_defaults = parseList(defaultValue); return pdi; } private QNodeDefinition parseChildNodeDefinition( QNodeType parent, Node node) throws XPathExpressionException, NoSuchNodeTypeException, RepositoryException { NamespaceMapper nsm = RepositoryImpl.getGlobalNamespaceRegistry(); XPath xpath = XPathFactory.newInstance().newXPath(); - String name = xpath.evaluate( "name", node ); + String name = getStringProperty( xpath, "name", node ); log.finest("Loading node definition "+name); QNodeDefinition nd = new QNodeDefinition( parent, nsm.toQName( name ) ); - String requiredType = xpath.evaluate( "requiredPrimaryTypes", node ); + String requiredType = getStringProperty( xpath, "requiredPrimaryTypes", node ); if( requiredType != null && requiredType.length() > 0 ) { String[] types = requiredType.split( "[\\[\\] ,]" ); ArrayList<QNodeType> list = new ArrayList<QNodeType>(); for( int i = 0; i < types.length; i++ ) { // The split operation might end up with empty thingies if( types[i].length() > 0 ) { QName requiredQType = nsm.toQName( types[i] ); if( requiredQType.equals( parent.getQName() ) ) list.add( parent ); else list.add( getNodeType( requiredQType ) ); } } nd.m_requiredPrimaryTypes = list.toArray( new QNodeType[0] ); } else { throw new ConfigurationException("Mandatory element 'requiredPrimaryTypes' is missing for "+name); } - String defaultType = xpath.evaluate( "defaultPrimaryType", node ); + String defaultType = getStringProperty( xpath, "defaultPrimaryType", node ); if( defaultType != null && defaultType.length() > 0 ) { QName defaultQType = nsm.toQName( defaultType ); if( defaultQType.equals(parent.getQName()) ) nd.m_defaultPrimaryType = parent; else nd.m_defaultPrimaryType = getNodeType( defaultQType ); } nd.m_isAutoCreated = getBooleanProperty(xpath, "autoCreated", node); nd.m_isMandatory = getBooleanProperty(xpath, "mandatory", node); nd.m_isProtected = getBooleanProperty(xpath, "protected", node); nd.m_allowsSameNameSiblings = getBooleanProperty(xpath, "sameNameSiblings", node); - String onParentVersion = xpath.evaluate( "onParentVersion", node ); + String onParentVersion = getStringProperty( xpath, "onParentVersion", node ); nd.m_onParentVersion = OnParentVersionAction.valueFromName( onParentVersion ); return nd; } /** * Finds a node definition from the complete array of all definitions * * @param type * @return */ public QNodeDefinition findNodeDefinition(QName type) { for( QNodeType nt : m_primaryTypes.values() ) { for( QNodeDefinition nd : nt.m_childNodeDefinitions ) { if( nd.getQName().equals( type ) ) return nd; } } for( QNodeType nt : m_mixinTypes.values() ) { for( QNodeDefinition nd : nt.m_childNodeDefinitions ) { if( nd.getQName().equals( type ) ) return nd; } } // // Find the default // for( QNodeType nt : m_primaryTypes.values() ) { for( QNodeDefinition nd : nt.m_childNodeDefinitions ) { if( nd.getQName().toString().equals( "*" ) ) return nd; } } return null; } private String[] parseList( String list ) { StringTokenizer st = new StringTokenizer(list,", []\""); String[] result = new String[st.countTokens()]; for( int i = 0; i < result.length; i++ ) { result[i] = st.nextToken(); } return result; } /** * Find a QNodeType by this QName. * * @param qn QName to look for * @return A QNodeType corresponding to this QName * @throws NoSuchNodeTypeException If it could not be located. */ public QNodeType getNodeType( QName qn ) throws NoSuchNodeTypeException { if( qn == null ) throw new NoSuchNodeTypeException("No null node type"); QNodeType n = m_primaryTypes.get(qn); if( n == null ) { n = m_mixinTypes.get(qn); } if( n == null ) throw new NoSuchNodeTypeException("No such node type: "+qn); return n; } /** * Implements the actual NodeTypeManager class, which, again, is * Session-specific. */ public static class Impl implements NodeTypeManager { private SessionImpl m_mapper; private QNodeTypeManager m_mgr; public Impl( QNodeTypeManager qm, SessionImpl nsm ) { m_mgr = qm; m_mapper = nsm; } public NodeTypeIterator getAllNodeTypes() throws RepositoryException { List<NodeType> ls = new ArrayList<NodeType>(); for( NodeTypeIterator ni = getPrimaryNodeTypes(); ni.hasNext(); ) { ls.add( ni.nextNodeType() ); } for( NodeTypeIterator ni = getMixinNodeTypes(); ni.hasNext(); ) { ls.add( ni.nextNodeType() ); } return new NodeTypeIteratorImpl(ls); } public NodeTypeIterator getMixinNodeTypes() throws RepositoryException { List<NodeType> ls = new ArrayList<NodeType>(); for( QNodeType qnt : m_mgr.m_mixinTypes.values() ) { ls.add( qnt.new Impl(m_mapper) ); } return new NodeTypeIteratorImpl(ls); } public QNodeType.Impl getNodeType(String nodeTypeName) throws NoSuchNodeTypeException, RepositoryException { QName qn = m_mapper.toQName( nodeTypeName ); QNodeType qnt = m_mgr.getNodeType(qn); return qnt.new Impl(m_mapper); } public NodeTypeIterator getPrimaryNodeTypes() throws RepositoryException { List<NodeType> ls = new ArrayList<NodeType>(); for( QNodeType qnt : m_mgr.m_primaryTypes.values() ) { ls.add( qnt.new Impl(m_mapper) ); } return new NodeTypeIteratorImpl(ls); } } } diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index 1b7c3eb..4968534 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -744,887 +744,895 @@ public class FileProvider implements RepositoryProvider, PerformanceReporter { value = vf.createValue( readContentsAsString( propFile ), PropertyType.DATE ); } else if( propType.equals(PropertyType.TYPENAME_NAME) ) { String qnameStr = readContentsAsString(propFile); QName qn = QName.valueOf( qnameStr ); value = vf.createValue( qn, PropertyType.NAME ); } else if( propType.equals(PropertyType.TYPENAME_PATH )) { String val = readContentsAsString(propFile); value = vf.createValue( val, PropertyType.PATH ); } else if( propType.equals(PropertyType.TYPENAME_REFERENCE ) ) { value = vf.createValue( readContentsAsString(propFile), PropertyType.REFERENCE ); } else if( propType.equals(PropertyType.TYPENAME_BINARY) ) { value = vf.createValue( new FileBinarySource(propFile) ); } else throw new RepositoryException("Cannot deserialize property type "+propType); return value; } /** * Returns the contents of the .info -file. * * @param nodeDir * @return * @throws PathNotFoundException * @throws IOException */ private Properties getPropertyInfo( File nodeDir, QName name ) throws PathNotFoundException, IOException { File inf = new File( nodeDir, makeFilename( name, ".info" ) ); if( !inf.exists() ) { throw new PathNotFoundException("The property metadata file was not found: "+inf.getAbsolutePath()); } Properties props; FileInputStream in = null; try { in = new FileInputStream( inf ); props = FastPropertyStore.load(in); } finally { if( in != null ) in.close(); } return props; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.GetPropertyValue.ordinal()]++; File nodeDir = getNodeDir( ws, path.getParentPath() ); try { Properties props = getPropertyInfo( nodeDir, path.getLastComponent() ); String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); ValueImpl[] result = new ValueImpl[items]; for( int i = 0; i < items; i++ ) { File df = new File( nodeDir, makeFilename(path.getLastComponent(),"."+i+".data") ); ValueImpl v = prepareValue( ws, df, propType ); result[i] = v; } return new ValueContainer(result, PropertyType.valueFromName( propType ) ); } File df = new File( nodeDir, makeFilename( path.getLastComponent(), ".data" ) ); ValueImpl v = prepareValue(ws, df, propType); return new ValueContainer(v); } catch( IOException e ) { throw new RepositoryException("Unable to read property file",e); } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; - private static final String APPROVED_PUNCTUATION = " ./_,-+:[]"; + private static final String APPROVED_PUNCTUATION = " ./_,-+[]"; /** * This makes sure that the name * is still readable by the file system. The basic algorithm is * as follows: * <ul> * <li>All lower-case ASCII characters and digits are passed as-is. - * <li>All upper-case ASCII characters are preceded with '!'. This is + * <li>All upper-case ASCII characters are postfixed with '^'. This is * to make sure it all works on a case-insensitive file system such * as Windows or OSX. * <li>Approved punctuation characters are passed as-is. * <li>All other-characters are transformed into their unicode presentation formats * preceded with a '='. E.g. =00e5. * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: This method is extremely speed-critical // TODO: Protect against windows special names (CON) etc. protected static String mangleName( String name ) { StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } + else if( ch == ':' ) + { + // Colon is not allowed on NTFS or OSX. + sb.append( ';' ); + } else if( ch >= 'A' && ch <= 'Z' ) { - sb.append( '!' ); + // JSR-170 is case sensitive, so we have to make + // sure our storage is too. + sb.append( ch ); + sb.append( '^' ); } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } return sb.toString(); } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } /** * Just copies all characters from <i>in</i> to <i>out</i>. */ private static void copyContents( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private static void copyContents(Reader in, Writer out) throws IOException { char[] buf = new char[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private String readContentsAsString( File file ) throws IOException { Reader in = new InputStreamReader( new FileInputStream(file), "UTF-8" ); try { StringWriter out = new StringWriter(); copyContents( in, out ); return out.toString(); } finally { in.close(); } } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; /* After this many writes the store is compacted. */ private static final int COMPACT_LIMIT = 100; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); if( ++m_writeCount > COMPACT_LIMIT ) { serialize(); m_writeCount = 0; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { // System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } } diff --git a/tests/java/org/priha/core/RepositoryTest.java b/tests/java/org/priha/core/RepositoryTest.java index ec76e3f..d7ef459 100644 --- a/tests/java/org/priha/core/RepositoryTest.java +++ b/tests/java/org/priha/core/RepositoryTest.java @@ -1,353 +1,353 @@ package org.priha.core; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.logging.Logger; import javax.jcr.*; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; import org.priha.RepositoryManager; import org.priha.TestUtil; public class RepositoryTest extends AbstractTest { Logger log = Logger.getLogger(RepositoryTest.class.getName()); Session m_session; protected void setUp() throws Exception { super.setUp(); TestUtil.emptyRepo(m_repository); m_session = m_repository.login(new SimpleCredentials("foo",new char[0])); } protected void tearDown() throws Exception { m_session.logout(); super.tearDown(); } public void testLogin() throws Exception { Node nd = m_session.getRootNode(); assertEquals( 0, nd.getDepth() ); } - + public void testShutdown() throws Exception { RepositoryImpl r = RepositoryManager.getRepository("priha_shutdown.properties"); Session s = r.login(); assertTrue("session start",s.isLive()); r.shutdown(); assertFalse("session should be closed", s.isLive()); try { r.login(); fail("Allowed login"); } catch( RepositoryException e ) { // Expected } } public void testEmptyRepo() throws Exception { Node nd = m_session.getRootNode().addNode("testemptyrepo"); nd = nd.addNode("foo"); nd.setProperty("Barbapapa","Barbamama"); m_session.save(); TestUtil.emptyRepo(m_repository); File f = new File("/tmp/priha/fileprovider/workspaces/default/"); String[] paths = f.list(); for( String p : paths ) { if( p.startsWith("jcr:") || p.startsWith( "priha:") || p.startsWith( "." )) continue; // This is okay fail( "This was not removed: "+p ); } } public void testRemove() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); s.getRootNode().addNode("test"); s.save(); assertTrue( "was not created", s.getRootNode().hasNode("/test") ); Node nd = s.getRootNode().getNode("/test"); nd.remove(); s.save(); assertFalse( "was not removed", s.getRootNode().hasNode("/test") ); File f = new File("/tmp/priha/fileprovider/workspaces/default/test"); assertFalse( "File was not removed", f.exists() ); } public void testSave() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); Item it = s.getItem("/test"); assertTrue( "is not node", it.isNode() ); assertEquals( "wrong property", "foo",((Node)it).getProperty("a").getString()); } public void testSave2() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); s.logout(); s = m_repository.login(); Item it = s.getItem("/test"); assertTrue( "is not node", it.isNode() ); assertEquals( "wrong property", "foo",((Node)it).getProperty("a").getString()); } public void testRemoveProperty() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); nd.setProperty("foo", "bar"); s.save(); Item i = s.getItem("/foo"); assertTrue( "wrong type", i instanceof Property ); assertEquals( "wrong content", "bar", ((Property)i).getValue().getString() ); i.remove(); s.save(); Session s2 = m_repository.login(); try { s2.getItem("/foo"); fail("Still got it"); } catch( PathNotFoundException e ) { // Expected } File f = new File("/tmp/priha/fileprovider/workspaces/default/foo.info"); assertFalse( "File was not removed", f.exists() ); } public void testTraversal() throws Exception { Session s = m_repository.login(new SimpleCredentials("foo",new char[0])); Node nd = s.getRootNode(); Node newnode = nd.addNode("test"); newnode.setProperty( "a", "foo" ); s.save(); boolean testFound = false; for( NodeIterator it = nd.getNodes(); it.hasNext(); ) { Node n = it.nextNode(); if( n.getName().equals("test") ) { testFound = true; } else if( n.getName().equals("jcr:system") ) { // We ignore this } else { fail("Extraneous node found"); } } assertTrue( "test node not found", testFound ); } public void testBinaryProperty() throws Exception { Node nd = m_session.getRootNode(); nd = nd.addNode("binarytest"); String content = TestUtil.getUniqueID(32); InputStream in = new ByteArrayInputStream( content.getBytes() ); Property p = nd.setProperty("blob", in ); m_session.save(); Property p2 = (Property) m_session.getItem("/binarytest/blob"); assertEquals( content, p2.getString() ); } public void testMultiProviders() throws Exception { Repository r = RepositoryManager.getRepository("multiprovidertest.properties"); TestUtil.emptyRepo(r); Session s = r.login(new SimpleCredentials("foo",new char[0])); Session s2 = r.login(new SimpleCredentials("foo",new char[0]),"testworkspace"); assertFalse( "Must end up in different workspaces", s.getWorkspace().getName().equals(s2.getWorkspace().getName()) ); Node nd = s2.getRootNode().addNode("largefiles"); nd = nd.addNode("test"); nd.setProperty("reallybig", 42); nd = s.getRootNode().addNode("small"); nd.setProperty("reallysmall", "foobar"); s.save(); s2.save(); File f = new File("/tmp/priha-multi/fileprovider/workspaces/default/small/reallysmall.info"); assertTrue("small", f.exists() ); File f2 = new File("/tmp/priha-multi/fileprovider2/workspaces/testworkspace/largefiles/test/reallybig.info"); assertTrue("big", f2.exists() ); Property p = (Property)s.getItem("/small/reallysmall"); assertEquals("small content","foobar",p.getString()); p = (Property)s2.getItem("/largefiles/test/reallybig"); assertEquals("big content", p.getLong(), 42 ); s.logout(); s2.logout(); TestUtil.emptyRepo(r); assertFalse("small remove", f.exists()); assertFalse("big remove", f2.exists()); } public void testSameNameSiblings() throws Exception { Node nd = m_session.getRootNode().addNode("test", "nt:unstructured"); Node nd21 = nd.addNode( "samename", "nt:unstructured" ); nd21.setProperty( "order", 1 ); Node nd22 = nd.addNode( "samename", "nt:unstructured" ); nd22.setProperty( "order", 2 ); Node nd23 = nd.addNode( "samename", "nt:unstructured" ); nd23.setProperty( "order", 3 ); m_session.save(); nd = (Node) m_session.getItem("/test/samename[1]"); assertEquals( "one", 1, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[2]"); assertEquals( "two", 2, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[3]"); assertEquals( "three", 3, nd.getProperty( "order" ).getLong() ); } public void testSameNameSiblingsRemoval() throws Exception { Node nd = m_session.getRootNode().addNode("test", "nt:unstructured"); Node nd21 = nd.addNode( "samename", "nt:unstructured" ); nd21.setProperty( "order", 1 ); Node nd22 = nd.addNode( "samename", "nt:unstructured" ); nd22.setProperty( "order", 2 ); Node nd23 = nd.addNode( "samename", "nt:unstructured" ); nd23.setProperty( "order", 3 ); m_session.save(); nd22.remove(); m_session.save(); nd = (Node) m_session.getItem("test"); NodeIterator ni = nd.getNodes(); assertEquals( "samename1", "/test/samename", ni.nextNode().getPath() ); assertEquals( "samename2", "/test/samename[2]", ni.nextNode().getPath() ); try { ni.nextNode(); fail("Got third node!"); } catch( NoSuchElementException e ) {} nd = (Node) m_session.getItem("/test/samename[1]"); assertEquals( "one", 1, nd.getProperty( "order" ).getLong() ); nd = (Node) m_session.getItem("/test/samename[2]"); assertEquals( "samename[3] not moved to samename[2]", 3, nd.getProperty( "order" ).getLong() ); } public static Test suite() { return new TestSuite( RepositoryTest.class ); } }
jalkanen/Priha
b9a4daf30cb4c878483d36565b44b9a578e3032a
Added JdbcProviderTest. Fixed FileProvider to be case-sensitive even on case-insensitive file systems.
diff --git a/ChangeLog b/ChangeLog index b3e4aec..6586170 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,512 +1,519 @@ +2009-10-30 Janne Jalkanen <jalkanen@ecyrd.com> + + * 0.5.7 + + * FileProvider is now case-sensitive even on case-insensitive file + systems. + 2009-10-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.6 * SessionProvider.checkSanity() was using the moved path for sanity checks, not the originator path. Oops. 2009-10-25 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.5 * Added RepositoryImpl.shutdown() to facilitate repository restarts. 2009-10-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.4 * Bug fix: Item.isNew() was returning false when a mixin was added. Reported by Andrew Jaquith. * Same-name-siblings added again; however, Node.orderBefore() does not work at the moment. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.3 * Fixed ValueFactoryImpl.createValue(Value) to make proper clones also for Calendar values. 2009-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.2 * Fixed a number of leftover problems; again down to 8 failures on TCK. SNS support still disabled, but all failing tests are related to SNS... This version should fix most of the problems introduced in 0.5.0. * 0.5.1 * Moved Path* classes to its own package: org.priha.path, since util-package was perhaps growing a bit too much. 2009-10-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.5.0 * Rewrote changes handling since there were a couple of fairly serious dataloss bugs in it. It's now a bit more robust, and it uncovered a number of other issues as well. Unfortunately, the work is not yet complete, and SNS support is disabled for now. This commit is considerably more unstable than 0.4.1, so upgrading not recommended. * RepositoryProvider.putProperyValue() signature changed; therefore new minor version bump. 2009-10-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.1 * Orderable child nodes now implemented in JdbcProvider as well. * Fixed issue with FileProvider accidentally losing the index of the SNS. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.4.0 * Implemented orderable child nodes (though not yet for same name siblings) with FileProvider. This caused some minor changes in the Provider API. * Fixed minor problem in XML import which was failing a number of test cases. We no longer import jcr:baseVersion as a reference since we don't yet support importing version histories. 2009-09-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.5 * Added nt:folder nodetype, which was missing for some reason. * MemoryProvider now supports changing the workspace name. 2009-09-26 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.4 * Made most of our providers really thread-safe by enabling MultiThreadTest. * 0.3.3 * PathManager is now a singleton; which solves quite a few XML import problems - sharing Paths between multiple Sessions did not work (I have no idea what I was thinking when I made PathManager depend on a Session...) * 0.3.2 * Workspace.copy() did not allow copying to nodes with same name siblings enabled. Now fixed. * Fixed addNode() to support adding to indexed nodes; it was erroneusly thinking that /foo/bar[2]/blat is an illegal Node name... 2009-09-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.1 * Vastly improved speeds for MemoryProvider by redesigning the memory structure. For example, removal is no longer an O(N^2) operation, but O(log N). 2009-09-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.3.0 * FileProvider now stores the order in which Nodes are stored to support orderable child nodes. JDBCProvider does not do so yet. * Bigger changes in the Provider API - introduced StoreTransaction for making sure that changes can be rolled back in case there is a failure (for those providers which support it). * JDBC supports now references * Fixed issues with JDBC startup (was recreating the database on every single startup, oops) * Fixed Date format stream format. 2009-09-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.2.2 * Enhanced RepositoryProvider.getPropertyValue() to also transmit the type of the Value. The API changed again. * 0.2.1 * Rewrote Lock implementation, and introduced QLock. This got rid of some annoying lock errors relating to session expiration. Only TCK tests failing at this point relate to same-name siblings. * 0.2.0 * Rewrote JDBC Provider a bit to keep it compatible with JDK5 & 6. For future reference: Implementing JDK interfaces is not a good idea. * Changed the signatures of some of the RepositoryProvider interfaces, therefore causing a bump in version number. The changes were just some exceptions being added so that all methods can now throw RepositoryExceptions. 2009-09-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.40 * Implemented JDBC connection pooling for JdbcProvider. * Changed JDBC setup script location; it's now based on the result of Connection.getMetaData().getDatabaseProductName(). 2009-09-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.39 * JdbcProvider now has separate SQL setup scripts based on the driver class. * Added support for H2 database * Replaced HSQLDB with H2 database in tests; seems more reliable. * 0.1.38 * Path operations now avoid Path.toString() to provide some speedups. * Overall speedups, tweaks and code cleanup. 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.37 * Fixed a couple of locking tests. Introduced Node tagging (see NodeImpl.tag()). 2009-08-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.36 * Some cleanup around EhCachingProvider. Now has a new setting "maxSize" for determining how large objects should be cached. * 0.1.35 * Introduced PathRef to make Items no longer tied to a particular Path. This incidentally also improves performance quite a bit for inter-Session fetches. 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.34 * Fixed child lock tests; misunderstanding of JCR spec, oops :) 2009-08-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.33 * Fixed Path.Component.equals() - this unfortunately meant duplication of the QName class. * Added FastPropertyStore, which is not yet completely optimized. 2009-08-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.32 * Path.resolve() is now optimized for the most common cases. * Workspace init sped up. * PerformanceTest improved to allow for command-line arguments. Also removed Session leaks from emptyRepo(); 2009-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.31 * Fixed some leaking filehandles from FileProvider. 2009-08-18 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.30 * Fixed QueryImpl.getColumnNames() to default to the proper node constraint; was happily returning everything that was found... (JCR spec not too specific about this part, had to dig through some Jackrabbit mailing lists...) * Implemented multivalue matching. 2009-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.29 * Fixed a number of issues on queries; including range queries and queries on same-name siblings. * Improved repository layout for JCR TCK tests to actually have content for queries... 2009-08-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.28 * Fixed some issues with XML importing; the determination whether a property was multi or single was confused in quite a few cases. * Fixed issue where Session.move() constraints were not observed - now you no longer can save a target node without saving the source node and vice versa. * Fixed issue with NodeType.canAddChildNode() which was not properly adhering to JSR-170, but was being overly lenient. 2009-08-02 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.27 * Implemented initial same name sibling support; clone and move still do not work. 2009-07-30 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.26 * Implemented query ordering. 2009-07-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.25 * Workspace.clone() now works as well, completing support for corresponding nodes and workspace cloning. Yay! * Implemented rudimentary access control - calling Repository.login() now creates a readonly session. Any credentials (even empty) create a read-write session. * Implemented Document view import * Fixed some caching issues with SessionProvider. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.24 * Node.update() now works. Also, all root nodes are now also mix:referenceable with a known UUID. 2009-07-28 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.23 * FileProvider now properly stores UUIDs per workspace, as opposed to being global (oops - but the JCR spec *is* confusing in this regard; Univerally Unique IDs are not actually unique...) * Session.move() was checking for a wrong lock. 2009-07-27 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.22 * Massively improved FileProvider save speed by implementing journaling for the UUID and Reference storage. 2009-07-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.21 * Stored query support added. 2009-07-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.20 * A fairly massive update on versioning; cleaned up a lots of strangeness relating to deletion. 2009-06-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.19 * Implemented Version.getAllVersions(). 2009-06-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.18 * The basic query language is now supported mostly. ORring queries are not yet supported. 2009-05-16 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.17 * Workspace.move() implemented. Also cleaned some TCK failures relating to locks. 2009-05-10 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.16 * FileProvider was reading strings in platform encoding, not UTF-8. Oops. * StringValueImpl no longer forces SCALAR interpretation of the value, thus immensely easing debugging by making toString() idempotent. 2009-03-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.15 * Implemented jcr:contains() function in XPath queries. 2009-02-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.14 * Massive speed optimizations by improving caching in SessionProvider. 2009-02-15 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.13 * Session is now a bit more fussy about when it's live. 2008-12-07 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.12 * XPath queries now work. We now use the Apache Jackrabbit Abstract Query Tree parser, but provide our own resolvers. Thanks heaps :-). Not all of the predicates work, and neither do any of the functions yet. But the core is there. 2008-11-24 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.11 * Added org.priha.j2ee.JNDIRegistrationServlet to allow for JNDI-based initialization in a J2EE application. 2008-11-14 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.10 * Fixed most of locking tests (now we actually remove locks when you delete a node). 2008-10-23 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.9 * Fixed a few failing nodetype unit tests. 2008-10-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.8 * Implemented XPath query API. It kind of works, but it is pretty slow and does not yet support any of the JCR functions. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.7 * Fixed issue with wrong exception if the Node was moved by another session and then saved. * Test failures at 55 out of 584. 2008-10-13 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.6 * Implemented Workspace.copy(). 2008-10-12 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.5 * Document view export is now supported. Versioning also seems to mostly work. * Test failures now 83/584. 2008-10-09 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.4 * Fixed a number of versioning unit tests by implementing Node.isCheckedOut()... 2008-10-06 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.3 * Massive reoptimization of FileProvider to do reference management properly. This also meant some additions to the Provider API. 2008-10-01 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.2 * XML Import works again * Item state changes are now replicated within a Session properly. * Test fails: 115/584. 2008-09-29 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.1 * Massive changes to the internal workings; Priha now correctly stores QNames internally as much as it can, converting to the correct namespace mapping at the last instance. Total fail rate for tests: 130/584. 2008-08-22 Janne Jalkanen <jalkanen@ecyrd.com> * 0.1.0 * Renamed packages to org.priha. 2008-08-21 Janne Jalkanen <jalkanen@ecyrd.com> * 0.0.30 * Turned on versioning support; still doesn't work but at least some of the classes are there. * Initial implementation of namespace remapping; something is still missing though. 2008-08-17 Janne Jalkanen <jalkanen@ecyrd.com> * 0.0.29 * XML Import now works for System View. All SerializationTest tests now pass. Total fail rate for tests is 110 / 584. 2008-08-11 Janne Jalkanen <jalkanen@ecyrd.com> * 0.0.28 * Fixed a number of issues with XML import (still does not work yet). * New pass rate for TCK tests is 126 fails out of 584 tests. 2008-08-03 Janne Jalkanen <jalkanen@ecyrd.com> diff --git a/src/java/org/priha/Release.java b/src/java/org/priha/Release.java index 2a0b6e7..b4a3c2d 100644 --- a/src/java/org/priha/Release.java +++ b/src/java/org/priha/Release.java @@ -1,116 +1,116 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha; import javax.jcr.Repository; /** * Details the release information. This class is executable, i.e. * you can run * <pre> * % java -jar priha.jar org.priha.Release * Priha Content Repository * 1.0.2 * (C) Janne Jalkanen 2007-2009 * </pre> * The first line is the application name, the second line is the version, * and the third line is the copyright. * <p> * You may also use the argument "-versiononly" which will only print * the version string. E.g. * * <pre> * % java -jar priha.jar org.priha.Release -versiononly * 1.0.2 * </pre> * */ public class Release { /** * The application name. Value is {@value}. */ public static final String APPNAME = "Priha Content Repository"; /** * The copyright string. Value is {@value}. */ public static final String COPYRIGHT = "(C) Janne Jalkanen 2007-2009"; /** * The current major version. */ public static final int VERSION = 0; /** * The current minor version. */ public static final int REVISION = 5; /** * The current minor revision. */ - public static final int MINORREVISION = 6; + public static final int MINORREVISION = 7; /** * The version string of the form version.revision.minorrevision. At * the time of the generation of this documentation, it was {@value}. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION; private static final String STR_TRUE = "true"; private static final String STR_FALSE = "false"; /** * Contains the JCR Descriptors. Essentially lists the different * features that the repository supports. Use {@link Repository#getDescriptor(String)} */ public static String[] DESCRIPTORS = { Repository.SPEC_NAME_DESC, "Content Repository for Java Technology API", Repository.SPEC_VERSION_DESC, "1.0", Repository.REP_NAME_DESC, APPNAME, Repository.REP_VENDOR_DESC, "Janne Jalkanen", Repository.REP_VENDOR_URL_DESC, "http://www.priha.org/", Repository.REP_VERSION_DESC, VERSTR, Repository.LEVEL_1_SUPPORTED, STR_TRUE, Repository.LEVEL_2_SUPPORTED, STR_TRUE, Repository.OPTION_TRANSACTIONS_SUPPORTED, STR_FALSE, Repository.OPTION_VERSIONING_SUPPORTED, STR_FALSE, Repository.OPTION_LOCKING_SUPPORTED, STR_TRUE, Repository.OPTION_OBSERVATION_SUPPORTED, STR_FALSE, Repository.OPTION_QUERY_SQL_SUPPORTED, STR_FALSE, Repository.QUERY_XPATH_POS_INDEX, STR_FALSE, Repository.QUERY_XPATH_DOC_ORDER, STR_FALSE }; /** * A static method which can be run to print the version information. */ public static final void main(String[] argv) { if( argv.length > 0 && argv[0].equals("-versiononly") ) System.out.println(VERSTR); else { System.out.println(APPNAME); System.out.println(VERSTR); System.out.println(COPYRIGHT); } } } diff --git a/src/java/org/priha/providers/FileProvider.java b/src/java/org/priha/providers/FileProvider.java index caa5ed1..1b7c3eb 100644 --- a/src/java/org/priha/providers/FileProvider.java +++ b/src/java/org/priha/providers/FileProvider.java @@ -1,1615 +1,1630 @@ /* Priha - A JSR-170 implementation library. Copyright (C) 2007 Janne Jalkanen (Janne.Jalkanen@iki.fi) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.priha.providers; import static org.priha.core.JCRConstants.Q_JCR_PRIMARYTYPE; import static org.priha.core.JCRConstants.Q_JCR_UUID; import java.io.*; import java.util.*; import java.util.logging.Logger; import javax.jcr.*; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.core.binary.FileBinarySource; import org.priha.core.values.QValue; import org.priha.core.values.ValueFactoryImpl; import org.priha.core.values.ValueImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.InvalidPathException; import org.priha.path.Path; import org.priha.path.PathFactory; import org.priha.path.Path.Component; import org.priha.util.*; /** * A simple file system -based provider. This is not particularly optimized. * Stores UUIDs and references as journaling files which are compacted * at every N writes and on shutdown. If there is a power outage just * in the middle of this process, it's possible that the file ends up * being corrupted. Currently there is no way to rebuild the UUIDs. * <p> * The FileProvider does not support failure recovery at the moment. So it's probably not * the best provider for production systems. */ public class FileProvider implements RepositoryProvider, PerformanceReporter { private static final String PROP_NUM_PROPERTIES = "numProperties"; private static final String PROP_MULTIPLE = "multiple"; private static final String PROP_TYPE = "type"; private static final String PROP_PATH = "path"; private static final int BUFFER_SIZE = 4096; private static final String LOCKFILE = ".prihalock"; private String m_root; private String m_workspaceRoot; private Logger log = Logger.getLogger( getClass().getName() ); private long[] m_hitCount; private Path m_systemPath; private Map<String,UUIDObjectStore<Path[]>> m_references = new HashMap<String, UUIDObjectStore<Path[]>>(); private Map<String,UUIDObjectStore<Path>> m_uuids = new HashMap<String, UUIDObjectStore<Path>>(); public FileProvider() throws RepositoryException { resetCounts(); } /** * Returns the File which houses all of the workspaces. * @return */ private String getWorkspaceRoot() { if( m_workspaceRoot == null ) { m_workspaceRoot = m_root + "/workspaces"; } return m_workspaceRoot; } /** * Figures out what the filename for a Workspace is. * @param ws * @return */ // FIXME: Should escape the filename properly. private String getWorkspaceFilename( Workspace ws ) { return ws.getName(); } /** * Figures out the what the filename for a given path is. * @param path * @return * @throws RepositoryException * @throws NamespaceException */ // FIXME: Should escape the path properly private String getPathFilename( Path path ) throws NamespaceException, RepositoryException { String p = path.toString( RepositoryImpl.getGlobalNamespaceRegistry() ); return mangleName(p); } /** * Create a valid filename based on the QName and a suffix. * * @param name * @param suffix * @return */ private String makeFilename( QName name, String suffix ) { String filename; try { filename = RepositoryImpl.getGlobalNamespaceRegistry().fromQName(name); } catch( NamespaceException e ) { filename = name.getLocalPart(); } if( suffix != null ) filename = filename + suffix; return mangleName(filename); } /** * Returns the directory for a particular Workspace. * * @param wsname * @return */ private String getWorkspaceDir( String wsname ) { String wsDir = getWorkspaceRoot() + "/" + wsname; return wsDir; } /** * Returns the directory in which a particular Node in a particular workspace resides * * @param ws * @param path * @return * @throws RepositoryException * @throws NamespaceException */ private File getNodeDir( Workspace ws, Path path ) throws NamespaceException, RepositoryException { if( m_systemPath.isParentOf( path ) || m_systemPath.equals( path ) ) { return new File( m_root, getPathFilename(path) ); } String wsDir = getWorkspaceDir( getWorkspaceFilename(ws) ); File nodeDir = new File( wsDir, getPathFilename(path) ); return nodeDir; } public void addNode(StoreTransaction tx, Path path, QNodeDefinition def) throws RepositoryException { m_hitCount[Count.AddNode.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path ); nodeDir.mkdirs(); if( !path.isRoot() ) { List<String> order = getOrder(ws,path.getParentPath()); if( !order.contains( path.getLastComponent().toString() ) ) { order.add( path.getLastComponent().toString() ); saveOrder( ws, path.getParentPath(), order ); } } } private void acquirePaths( Path startPath, File dir, List<Path> list, boolean recurse ) { File[] files = dir.listFiles(); if( files == null || files.length == 0 ) return; for( File f : files ) { if( f.isDirectory() ) { try { Properties props = getPropertyInfo( f, Q_JCR_PRIMARYTYPE ); Path p = PathFactory.getPath( props.getProperty( PROP_PATH ) ); list.add( p.getParentPath() ); if( recurse ) { acquirePaths( p.getParentPath(), f, list, recurse ); } } catch( PathNotFoundException e ) { // Skip, don't include. } catch( IOException e ) { // Skip, don't include. } catch (NamespaceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidPathException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch( NullPointerException e ) { e.printStackTrace(); } } } } public List<String> listWorkspaces() { m_hitCount[Count.ListWorkspaces.ordinal()]++; ArrayList<String> list = new ArrayList<String>(); File[] dirs = new File(getWorkspaceRoot()).listFiles(); if( dirs != null ) { for( File f : dirs ) { if( f.isDirectory() ) { list.add( f.getName() ); } } } return list; } private boolean deleteContents( File dir ) { // System.out.println("Deleting "+dir.getAbsolutePath()); for( File f : dir.listFiles() ) { if( f.isDirectory() ) { deleteContents( f ); } if( !f.delete() ) return false; } return true; } public void start(RepositoryImpl rep, Properties props) throws ConfigurationException { m_hitCount[Count.Start.ordinal()]++; try { m_systemPath = PathFactory.getPath( RepositoryImpl.getGlobalNamespaceRegistry(), "/jcr:system" ); } catch( RepositoryException e ) { throw new ConfigurationException("Unable to create a /jcr:system instance: "+e.getMessage()); } String wsList = props.getProperty("workspaces", "default"); m_root = props.getProperty("directory"); // // Make sure that root exists. // File root = new File(m_root); root.mkdirs(); // // Make sure this instance is the only one using that root. // File lockFile = new File(m_root, LOCKFILE); if( lockFile.exists() ) { String msg = "Cannot use the Priha FileProvider repository while another instance of Priha is using it. "+ "If you are sure there are no other instances using this same repository, please "+ "remove the '"+lockFile.getAbsolutePath()+"' file and restart."; log.severe( msg ); throw new ConfigurationException(msg); } // // Create the lock file; and make sure it gets cleaned up properly in // most cases. // try { lockFile.createNewFile(); lockFile.deleteOnExit(); } catch( IOException e ) { throw new ConfigurationException("Cannot start Priha ",e); } // // Initializing the workspaces. // log.fine("Initializing FileProvider with root "+m_root); String[] workspaces = wsList.split("\\s"); for( String wsname : workspaces ) { File wsroot = new File(getWorkspaceDir(wsname)); if( !wsroot.exists() ) { wsroot.mkdirs(); log.finer("Created workspace directory "+wsroot); } // // Reset the workspaces. // m_references.put( wsname, new UUIDObjectStore<Path[]>(mangleName(wsname)+"-references.ser") ); m_uuids.put( wsname, new UUIDObjectStore<Path>(mangleName(wsname)+"-uuid.ser") ); } } public void stop(RepositoryImpl rep) { m_hitCount[Count.Stop.ordinal()]++; log.fine("Shutting down FileProvider..."); for( UUIDObjectStore<Path[]> s : m_references.values() ) { s.shutdown(); } for( UUIDObjectStore<Path> s : m_uuids.values() ) { s.shutdown(); } m_references.clear(); m_uuids.clear(); // // Clean up the lockfile, in case we're e.g. switching repos mid-flight. // File lockFile = new File(m_root, LOCKFILE); lockFile.delete(); } public void copy(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Copy.ordinal()]++; throw new UnsupportedRepositoryOperationException("copy()"); } public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws NamespaceException, RepositoryException { m_hitCount[Count.ListNodes.ordinal()]++; ArrayList<Path> list = new ArrayList<Path>(); File startPath = getNodeDir( ws, parentpath ); if( !startPath.exists() ) throw new PathNotFoundException("No such path found: "+parentpath); //acquirePaths( parentpath, startPath, list, false ); List<String> orderArray = getOrder( ws, parentpath ); for( String s : orderArray ) { Path childPath = parentpath.resolve( Path.Component.valueOf( s ) ); list.add( childPath ); } // // The .order -file will probably not contain the system path for anyone else // except the workspace which was created first. // if( parentpath.isRoot() && !list.contains( m_systemPath )) { list.add( 0, m_systemPath ); } return list; } public List<QName> listProperties(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.ListProperties.ordinal()]++; File nodeDir = getNodeDir( ws, path ); List<QName> proplist = new ArrayList<QName>(); try { File[] files = nodeDir.listFiles( new PropertyTypeFilter() ); if( files != null ) { for( File propertyFile : files ) { Properties props; FileInputStream in = null; try { in = new FileInputStream(propertyFile); props = FastPropertyStore.load(in); String qname = props.getProperty(PROP_PATH); proplist.add( PathFactory.getPath( qname ).getLastComponent() ); } finally { if( in != null ) in.close(); } } } } catch( IOException e ) { throw new RepositoryException("Thingy said booboo", e); } return proplist; } public void move(WorkspaceImpl ws, Path srcpath, Path destpath) throws RepositoryException { m_hitCount[Count.Move.ordinal()]++; throw new UnsupportedRepositoryOperationException("move()"); } /** * A Node exists only if it has a primaryType.info in the directory. */ public boolean nodeExists(WorkspaceImpl ws, Path path) { m_hitCount[Count.NodeExists.ordinal()]++; File nodeDir; try { nodeDir = getNodeDir( ws, path ); - File propFile = new File( nodeDir, "jcr:primaryType.info" ); + File propFile = new File( nodeDir, mangleName("jcr:primaryType.info") ); return propFile.exists(); } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public void open(RepositoryImpl rep, Credentials credentials, String workspaceName) throws RepositoryException, NoSuchWorkspaceException { m_hitCount[Count.Open.ordinal()]++; List<String> wsnames = listWorkspaces(); if( wsnames.indexOf(workspaceName) == -1 ) throw new NoSuchWorkspaceException(workspaceName); log.finer("Workspace "+workspaceName+" has been opened."); } public void close(WorkspaceImpl ws) { log.finer( "Workspace "+ws.getName()+" closing..." ); m_hitCount[Count.Close.ordinal()]++; try { m_uuids.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } catch( NullPointerException e ) { log.warning( "A non-configured workspace '"+ws.getName()+"' detected. If you are using a multiprovider configuration, please check this workspace actually exists." ); return; } try { m_references.get( ws.getName() ).serialize(); } catch( IOException e ) { log.info( "Unable to store UUID references upon workspace logout."+e.getMessage() ); } } private void writeValue( File f, ValueImpl v ) throws IOException, IllegalStateException, RepositoryException { OutputStream out = null; InputStream in = null; try { if( v instanceof QValue.QValueInner ) { byte[] ba = ((QValue.QValueInner)v).getQValue().getString().getBytes("UTF-8"); in = new ByteArrayInputStream(ba); } else { in = v.getStream(); } out = new FileOutputStream( f ); copyContents( in, out ); } finally { // // ...and close all the streams. // if( out != null ) { try { out.close(); } finally { if( in != null ) in.close(); } } } } public void putPropertyValue(StoreTransaction tx, Path path, ValueContainer vc) throws RepositoryException { m_hitCount[Count.PutPropertyValue.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeDir = getNodeDir( ws, path.getParentPath() ); saveUuidShortcut(ws,path,vc); QName qname = path.getLastComponent(); File inf = new File( nodeDir, makeFilename( qname, ".info" ) ); Properties props = new Properties(); props.setProperty( PROP_PATH, path.toString() ); props.setProperty( PROP_TYPE, PropertyType.nameFromValue( vc.getType() ) ); props.setProperty( PROP_MULTIPLE, vc.isMultiple() ? "true" : "false" ); OutputStream out = null; try { if( vc.isMultiple() ) { props.setProperty( PROP_NUM_PROPERTIES, Integer.toString(vc.getValues().length) ); Value[] values = vc.getValues(); // // Let's clear previous references, if this is an attempt to save // a null value. // if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl[] oldval = getPropertyValue( ws, path ).getValues(); for( ValueImpl vi : oldval ) { String uuid = vi.getString(); cleanRefMapping( ws, path, uuid ); } } catch( PathNotFoundException e ){} // This is okay } for( int i = 0; i < values.length; i++ ) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); saveRefShortcut( ws, path, (ValueImpl)values[i] ); writeValue( df, (ValueImpl)values[i] ); } // Remove the rest of old values int i = values.length; while(true) { File df = new File( nodeDir, makeFilename( qname, "."+i+".data" ) ); if( df.exists() ) df.delete(); else break; } } else { if( vc.getType() == PropertyType.REFERENCE ) { try { ValueImpl oldval = getPropertyValue( ws, path ).getValue(); cleanRefMapping( ws, path, oldval.getString() ); } catch(PathNotFoundException e) {} // OK saveRefShortcut( ws, path, vc.getValue() ); } File df = new File( nodeDir, makeFilename( qname, ".data" ) ); writeValue( df, vc.getValue() ); } out = new FileOutputStream(inf); FastPropertyStore.store( out, props ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * Saves a shortcut to an UUID. The contents of the file are the path of the Node. * */ private void saveUuidShortcut(WorkspaceImpl ws, Path path, ValueContainer vc) throws RepositoryException { if( path.getLastComponent().equals(Q_JCR_UUID) ) { UUIDObjectStore<Path> uuids = m_uuids.get( ws.getName() ); uuids.setObject( vc.getValue().valueAsString(), path.getParentPath() ); } } private ValueImpl prepareValue( WorkspaceImpl ws, File propFile, String propType ) throws IOException, RepositoryException { ValueFactoryImpl vf = ws.getSession().getValueFactory(); ValueImpl value; if( propType.equals(PropertyType.TYPENAME_STRING) ) { value = vf.createValue( readContentsAsString(propFile) ); } else if( propType.equals(PropertyType.TYPENAME_BOOLEAN) ) { value = vf.createValue( "true".equals(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DOUBLE) ) { value = vf.createValue( Double.parseDouble(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_LONG) ) { value = vf.createValue( Long.parseLong(readContentsAsString(propFile)) ); } else if( propType.equals(PropertyType.TYPENAME_DATE) ) { value = vf.createValue( readContentsAsString( propFile ), PropertyType.DATE ); } else if( propType.equals(PropertyType.TYPENAME_NAME) ) { String qnameStr = readContentsAsString(propFile); QName qn = QName.valueOf( qnameStr ); value = vf.createValue( qn, PropertyType.NAME ); } else if( propType.equals(PropertyType.TYPENAME_PATH )) { String val = readContentsAsString(propFile); value = vf.createValue( val, PropertyType.PATH ); } else if( propType.equals(PropertyType.TYPENAME_REFERENCE ) ) { value = vf.createValue( readContentsAsString(propFile), PropertyType.REFERENCE ); } else if( propType.equals(PropertyType.TYPENAME_BINARY) ) { value = vf.createValue( new FileBinarySource(propFile) ); } else throw new RepositoryException("Cannot deserialize property type "+propType); return value; } /** * Returns the contents of the .info -file. * * @param nodeDir * @return * @throws PathNotFoundException * @throws IOException */ private Properties getPropertyInfo( File nodeDir, QName name ) throws PathNotFoundException, IOException { File inf = new File( nodeDir, makeFilename( name, ".info" ) ); if( !inf.exists() ) { throw new PathNotFoundException("The property metadata file was not found: "+inf.getAbsolutePath()); } Properties props; FileInputStream in = null; try { in = new FileInputStream( inf ); props = FastPropertyStore.load(in); } finally { if( in != null ) in.close(); } return props; } public ValueContainer getPropertyValue(WorkspaceImpl ws, Path path) throws RepositoryException { m_hitCount[Count.GetPropertyValue.ordinal()]++; File nodeDir = getNodeDir( ws, path.getParentPath() ); try { Properties props = getPropertyInfo( nodeDir, path.getLastComponent() ); String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); ValueImpl[] result = new ValueImpl[items]; for( int i = 0; i < items; i++ ) { File df = new File( nodeDir, makeFilename(path.getLastComponent(),"."+i+".data") ); ValueImpl v = prepareValue( ws, df, propType ); result[i] = v; } return new ValueContainer(result, PropertyType.valueFromName( propType ) ); } File df = new File( nodeDir, makeFilename( path.getLastComponent(), ".data" ) ); ValueImpl v = prepareValue(ws, df, propType); return new ValueContainer(v); } catch( IOException e ) { throw new RepositoryException("Unable to read property file",e); } } private List<String> getOrder( WorkspaceImpl ws, Path path ) { File order; ArrayList<String> result = new ArrayList<String>(); try { order = new File(getNodeDir(ws,path), ".order"); String o = FileUtil.readContents( new FileInputStream(order), "UTF-8" ); String[] oo = o.split( "\n" ); // // Clean away any empty Strings. // List<String> res = Arrays.asList( oo ); for( String s : res ) { if( s.length() > 0 ) result.add( s ); } return result; } catch( IOException e ) { } catch( NamespaceException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( RepositoryException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private void saveOrder( WorkspaceImpl ws, Path path, List<String> list) { FileOutputStream out = null; try { File order = new File(getNodeDir(ws,path),".order"); out = new FileOutputStream(order); for( String s : list ) { out.write( s.getBytes("UTF-8") ); out.write( '\n' ); } } catch(Exception e) { e.printStackTrace(); } finally { if( out != null ) { try { out.close(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void remove(final StoreTransaction tx, final Path path) throws RepositoryException { m_hitCount[Count.Remove.ordinal()]++; WorkspaceImpl ws = tx.getWorkspace(); File nodeFile = getNodeDir( ws, path ); if( nodeFile != null ) { if( nodeFile.exists() ) { // OK, so this is a Node (i.e. a subdir) and we can just remove everything // from underneath it if( deleteContents( nodeFile ) ) { if( !nodeFile.delete() ) { log.warning("Unable to delete path "+path); } } else { log.warning("Failed to delete contents of path "+path); } List<String> order = getOrder(ws,path.getParentPath()); order.remove( path.getLastComponent().toString() ); saveOrder(ws, path.getParentPath(), order); } else { // Must be a property File infoFile = new File( nodeFile.getParentFile(), makeFilename(path.getLastComponent(),".info") ); DataContent dc = new DataContent( path, nodeFile.getParentFile(), path.getLastComponent() ); try { dc.iterate( new DataVisitor(){ public void visit(Path p, Properties props, File dataFile) throws IOException { int type = PropertyType.valueFromName( props.getProperty( PROP_TYPE ) ); if( type == PropertyType.REFERENCE ) { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing refs "+uuid); cleanRefMapping( tx.getWorkspace(), p, uuid ); } if( p.getLastComponent().equals( Q_JCR_UUID ) ) { try { String uuid = readContentsAsString( dataFile ); //System.out.println("Removing UUID "+uuid); cleanUuidMapping( tx.getWorkspace(), uuid ); } catch( IOException e ) { // Fail quietly; it might be that the UUID file does not exist for some reason. } } //System.out.println("Deleting datafile "+dataFile.getAbsolutePath()); dataFile.delete(); } } ); infoFile.delete(); } catch( Exception ex ) { log.warning( "Oh noes, removal failed! "+ex.getMessage() ); } } } } private interface DataVisitor { public void visit(Path path, Properties properties, File dataFile) throws IOException; } private class DataContent { private Path m_path; private File m_dir; private QName m_basename; public DataContent(Path path, File dir, QName basename ) { m_path = path; m_dir = dir; m_basename = basename; } /** * Visits over each property value file in this content. * * @param visitor * @throws PathNotFoundException * @throws IOException */ public void iterate( DataVisitor visitor ) throws PathNotFoundException, IOException { Properties props = getPropertyInfo( m_dir, m_basename ); // String propType = props.getProperty(PROP_TYPE); Boolean isMultiple = new Boolean(props.getProperty(PROP_MULTIPLE)); if( isMultiple ) { int items = Integer.parseInt( props.getProperty( PROP_NUM_PROPERTIES ) ); for( int i = 0; i < items; i++ ) { File df = new File( m_dir, makeFilename(m_basename,"."+i+".data") ); visitor.visit( m_path, props, df ); } } else { File df = new File( m_dir, makeFilename(m_basename, ".data") ); visitor.visit( m_path, props, df ); } } } /** * The UUID in question is removed, so we'll clear it now. * * @param uuid */ private void cleanUuidMapping( WorkspaceImpl ws, String uuid ) { m_uuids.get(ws.getName()).setObject( uuid, null ); } private void cleanRefMapping( WorkspaceImpl ws, Path path, String uuid ) throws IOException { Path[] refs = m_references.get(ws.getName()).getObject( uuid ); //System.out.println("Removing "+path+" ==> "+uuid ); ArrayList<Path> newrefs = new ArrayList<Path>(); if(refs == null) { /* refs = new Path[1]; refs[0] = path; */ } else { for( Path p : refs ) { if( !p.equals(path) ) { newrefs.add( p ); } } } m_references.get(ws.getName()).setObject( uuid, newrefs.size() > 0 ? newrefs.toArray( new Path[newrefs.size()] ) : null ); } private void saveRefShortcut( WorkspaceImpl ws, Path path, ValueImpl v ) throws ValueFormatException, IllegalStateException, RepositoryException, IOException { if( v.getType() == PropertyType.REFERENCE ) { String uuid = v.getString(); Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs == null ) refs = new Path[0]; Path[] newrefs = new Path[refs.length+1]; for( int i = 0; i < refs.length; i++ ) newrefs[i] = refs[i]; newrefs[newrefs.length-1] = path; m_references.get(ws.getName()).setObject( uuid, newrefs ); } } /* private Path findUUIDFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Check child nodes // Path res = findUUIDFromPath( ws, uuid, p ); if( res != null ) return res; // // Check properties of this node // List<String> propList = listProperties( ws, p ); for( String property : propList ) { if( property.equals( NodeImpl.JCR_UUID ) ) { Value v = (Value)getPropertyValue( ws, p.resolve(property) ); if( uuid.equals(v.getString()) ) return p; } } } return null; } */ public Path findByUUID(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindByUUID.ordinal()]++; Path cachedPath = m_uuids.get(ws.getName()).getObject( uuid ); if( cachedPath == null ) { throw new ItemNotFoundException( "There is no item with UUID "+uuid+" in the repository."); } return cachedPath; } private static class PropertyTypeFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".info"); } } private List<Path> findReferencesFromPath( WorkspaceImpl ws, String uuid, Path path ) throws RepositoryException { List<Path> response = new ArrayList<Path>(); List<Path> list = listNodes( ws, path ); for( Path p : list ) { // // Depth-first. // response.addAll( findReferencesFromPath( ws, uuid, p ) ); // // List the properties // List<QName> propList = listProperties( ws, p ); for( QName property : propList ) { Path propertyPath = p.resolve(property); Object o = getPropertyValue(ws, propertyPath ); if( o instanceof Value ) { Value v = (Value) o; if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } else if( o instanceof Value[] ) { for( Value v : (Value[])o ) { if( v.getType() == PropertyType.REFERENCE && v.getString().equals( uuid ) ) { response.add( propertyPath ); } } } } } return response; } public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException { m_hitCount[Count.FindReferences.ordinal()]++; Path[] refs = m_references.get(ws.getName()).getObject( uuid ); if( refs != null ) { return Arrays.asList( refs ); } return new ArrayList<Path>(); } public long getCount(Count item) { return m_hitCount[item.ordinal()]; } public void resetCounts() { m_hitCount = new long[Count.values().length]; } private static final String[] WINDOWS_DEVICE_NAMES = { "con", "prn", "nul", "aux", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9" }; - private static final String APPROVED_PUNCTUATION = " ./_,-+:"; + private static final String APPROVED_PUNCTUATION = " ./_,-+:[]"; /** - * This makes sure that the queried page name - * is still readable by the file system. For example, all XML entities - * and slashes are encoded with the percent notation. + * This makes sure that the name + * is still readable by the file system. The basic algorithm is + * as follows: + * <ul> + * <li>All lower-case ASCII characters and digits are passed as-is. + * <li>All upper-case ASCII characters are preceded with '!'. This is + * to make sure it all works on a case-insensitive file system such + * as Windows or OSX. + * <li>Approved punctuation characters are passed as-is. + * <li>All other-characters are transformed into their unicode presentation formats + * preceded with a '='. E.g. =00e5. + * </ul> * * @param pagename The name to mangle * @return The mangled name. */ // TODO: This method is extremely speed-critical + // TODO: Protect against windows special names (CON) etc. protected static String mangleName( String name ) { StringBuilder sb = new StringBuilder(name.length()+32); int len = name.length(); for( int i = 0; i < len; i++ ) { char ch = name.charAt( i ); - if( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z' ) || + if( (ch >= 'a' && ch <= 'z') || (APPROVED_PUNCTUATION.indexOf(ch) != -1) || (ch >= '0' && ch <= '9') ) { sb.append( ch ); } + else if( ch >= 'A' && ch <= 'Z' ) + { + sb.append( '!' ); + sb.append( ch ); + } else { sb.append( '=' ); String xa = Integer.toHexString( ch ); for( int j = 0; j < 4-xa.length(); j++ ) sb.append("0"); sb.append(xa); } } return sb.toString(); } // FIXME: FileProvider does not support recovery. Bummer. public void storeFinished( StoreTransaction tx ) { } public void storeCancelled( StoreTransaction tx ) { } public StoreTransaction storeStarted( WorkspaceImpl ws ) { return new BaseStoreTransaction(ws); } /** * Just copies all characters from <i>in</i> to <i>out</i>. */ private static void copyContents( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private static void copyContents(Reader in, Writer out) throws IOException { char[] buf = new char[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } out.flush(); } private String readContentsAsString( File file ) throws IOException { Reader in = new InputStreamReader( new FileInputStream(file), "UTF-8" ); try { StringWriter out = new StringWriter(); copyContents( in, out ); return out.toString(); } finally { in.close(); } } /*---------------------------------------------------------------------------*/ /** * Stores something based on UUIDs in an internal map, and * always serializes the map on disk upon addition of new objects. * * @param <T> A class to store - MUST implement Serializable. */ // FIXME: Should be faster by storing the map in a separate thread to collect multiple changes. // FIXME: Should create a new file each time and not overwrite a previous one; then remove // the old one. private class UUIDObjectStore<T extends Serializable> { private String m_name; private Map<String,T> m_map; private ObjectOutputStream m_journal; private int m_writeCount; /* After this many writes the store is compacted. */ private static final int COMPACT_LIMIT = 100; public UUIDObjectStore( String name ) { m_name = name; try { m_journal = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( new File(m_root, m_name), true ))); } catch( FileNotFoundException e ) { // FIXME: Should do something sane. e.printStackTrace(); } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void shutdown() { try { if( m_journal != null ) { serialize(); m_journal.close(); m_journal = null; } } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized String toString() { return "UUIDObjectStore["+m_name+", "+(m_map != null ? m_map.size() : "no")+" objs]"; } public synchronized T getObject( String uuid ) { if( m_map == null ) unserialize(); return m_map.get( uuid ); } public synchronized void setObject( String uuid, T object ) { if( m_map == null ) unserialize(); try { if( object != null ) { m_map.put( uuid, object ); writeAddedObject( uuid, object ); // System.out.println(" ADD "+uuid+" = "+object); } else { m_map.remove( uuid ); writeRemovedObject( uuid ); // System.out.println(" REMOVE "+uuid); } m_journal.flush(); if( ++m_writeCount > COMPACT_LIMIT ) { serialize(); m_writeCount = 0; } } catch( IOException e ) { // FIXME: Should do something sane. e.printStackTrace(); } } private void writeRemovedObject( String uuid ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( false ); } private void writeAddedObject( String uuid, T object ) throws IOException { m_journal.writeUTF( uuid ); m_journal.writeBoolean( true ); m_journal.writeObject( object ); } @SuppressWarnings("unchecked") private synchronized void unserialize() { File objFile = new File(m_root, m_name); m_map = new HashMap<String,T>(); // System.out.println("------ UNSERIALIZE()"); if( !objFile.exists() ) return; long start = System.currentTimeMillis(); ObjectInputStream in = null; try { in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(objFile)) ); while( in.available() > 0 ) { String uuid = in.readUTF(); Boolean addRemove = in.readBoolean(); if( addRemove ) { T o = (T) in.readObject(); // System.out.println(" >>> read in "+uuid+" = "+o); m_map.put( uuid, o ); } else { // System.out.println(" >>> removing "+uuid); m_map.remove( uuid ); } } } catch( EOFException e ) { // S'okay; it's just empty when we open it. } catch( FileNotFoundException e ) { // Fine, the journal just did not exist. } catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( in != null ) { try { in.close(); } catch( IOException e ) { e.printStackTrace(); } } log.fine( "Unserialized UUID store "+m_name+" in "+(System.currentTimeMillis()-start)+" ms" ); } } private synchronized void serialize() throws IOException { // System.out.println("++++++ COMPACTING..."); long start = System.currentTimeMillis(); if( m_map == null ) return; try { File fout = new File( m_root, m_name ); // // Close the old journal and create a new one. // if( m_journal != null ) { try { m_journal.close(); } catch( Exception e ) { // May happen, but we'll continue anyway. log.warning( "Unable to close journal: "+e.getMessage() ); } m_journal = null; } m_journal = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(fout,false)) ); for( Map.Entry<String, T> i : m_map.entrySet() ) { writeAddedObject( i.getKey(), i.getValue() ); } } finally { m_journal.flush(); long stop = System.currentTimeMillis(); log.fine("Compacted UUID store "+m_name+" in "+(stop-start)+" ms"); } } } public void reorderNodes(StoreTransaction tx, Path internalPath, List<Path> childOrder) { ArrayList<String> newOrder = new ArrayList<String>(); for( Path p : childOrder ) { newOrder.add( p.getLastComponent().toString() ); } saveOrder(tx.getWorkspace(), internalPath, newOrder); } public void rename(StoreTransaction tx, Path path, Component newName) throws RepositoryException { throw new UnsupportedRepositoryOperationException(); } } diff --git a/tests/java/org/priha/providers/AllTests.java b/tests/java/org/priha/providers/AllTests.java index f31ae16..50978bb 100644 --- a/tests/java/org/priha/providers/AllTests.java +++ b/tests/java/org/priha/providers/AllTests.java @@ -1,20 +1,21 @@ package org.priha.providers; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; public class AllTests extends AbstractTest { public static Test suite() { TestSuite suite = new TestSuite("Provider tests"); suite.addTest( FileProviderTest.suite() ); + suite.addTest( JdbcProviderTest.suite() ); return suite; } } diff --git a/tests/java/org/priha/providers/FileProviderTest.java b/tests/java/org/priha/providers/FileProviderTest.java index ca9f39f..073abfb 100644 --- a/tests/java/org/priha/providers/FileProviderTest.java +++ b/tests/java/org/priha/providers/FileProviderTest.java @@ -1,133 +1,136 @@ package org.priha.providers; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; +import org.priha.TestUtil; import org.priha.core.SessionImpl; public class FileProviderTest extends AbstractTest { SessionImpl m_session; public void setUp() throws Exception { super.setUp(); m_session = getNewSession(); } public void tearDown() throws Exception { + TestUtil.emptyRepo(m_session.getRepository()); m_session.logout(); + super.tearDown(); } private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { Node nd = m_session.getRootNode().addNode(UTF8_NAME); nd.setProperty(UTF8_NAME, UTF8_NAME); m_session.save(); Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); Property p2 = nd2.getProperty(UTF8_NAME); assertEquals(UTF8_NAME,nd2.getName()); assertEquals(UTF8_NAME,p2.getName()); assertEquals(UTF8_NAME,p2.getString()); } /** * JCR names are case-sensitive, so let's check that all these work. */ public void testCase1() throws Exception { Node nd = m_session.getRootNode().addNode("Test One"); nd.setProperty("Property One","KILL"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/test one"); fail("Found with wrong case"); } - catch( ItemNotFoundException e ) {} + catch( PathNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/Test One/property one"); fail("Found property with wrong case"); } - catch( ItemNotFoundException e ) {} + catch( PathNotFoundException e ) {} } public void testCase2() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("B", "foo"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/a"); fail("Found with wrong case"); } - catch( ItemNotFoundException e ) {} + catch( PathNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/A/b"); fail("Found property with wrong case"); } - catch( ItemNotFoundException e ) {} + catch( PathNotFoundException e ) {} } public void testCase3() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); Node nd2 = m_session.getRootNode().addNode("a"); nd2.setProperty("x","foo-b"); m_session.save(); assertFalse("same",nd.isSame(nd2)); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); Node ndb = (Node) m_session.getItem("/a"); assertEquals("foo-b",ndb.getProperty("x").getString()); } public void testPropertyCase1() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); nd.setProperty("X","foo-b"); m_session.save(); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); assertEquals("foo-b",nda.getProperty("X").getString()); } public static Test suite() { return new TestSuite( FileProviderTest.class ); } } diff --git a/tests/java/org/priha/providers/JdbcProviderTest.java b/tests/java/org/priha/providers/JdbcProviderTest.java new file mode 100644 index 0000000..e4951b2 --- /dev/null +++ b/tests/java/org/priha/providers/JdbcProviderTest.java @@ -0,0 +1,141 @@ +package org.priha.providers; + +import javax.jcr.*; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.version.VersionException; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.priha.RepositoryManager; +import org.priha.TestUtil; +import org.priha.core.RepositoryImpl; +import org.priha.core.SessionImpl; + +public class JdbcProviderTest extends TestCase +{ + SessionImpl m_session; + + public void setUp() throws Exception + { + super.setUp(); + RepositoryImpl rep = RepositoryManager.getRepository("jdbcnocache.properties"); + m_session = rep.login(new SimpleCredentials("foo",new char[0])); + } + + public void tearDown() throws Exception + { + Repository rep = m_session.getRepository(); + m_session.logout(); + + TestUtil.emptyRepo(rep); + + super.tearDown(); + } + + private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU + + public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException + { + Node nd = m_session.getRootNode().addNode(UTF8_NAME); + nd.setProperty(UTF8_NAME, UTF8_NAME); + + m_session.save(); + + Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); + Property p2 = nd2.getProperty(UTF8_NAME); + + assertEquals(UTF8_NAME,nd2.getName()); + assertEquals(UTF8_NAME,p2.getName()); + assertEquals(UTF8_NAME,p2.getString()); + } + + /** + * JCR names are case-sensitive, so let's check that all these work. + */ + public void testCase1() throws Exception + { + Node nd = m_session.getRootNode().addNode("Test One"); + nd.setProperty("Property One","KILL"); + + m_session.save(); + + try + { + Node nd2 = (Node)m_session.getItem("/test one"); + fail("Found with wrong case"); + } + catch( PathNotFoundException e ) {} + + + try + { + Property p2 = (Property)m_session.getItem("/Test One/property one"); + fail("Found property with wrong case"); + } + catch( PathNotFoundException e ) {} + } + + public void testCase2() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("B", "foo"); + m_session.save(); + + try + { + Node nd2 = (Node)m_session.getItem("/a"); + fail("Found with wrong case"); + } + catch( PathNotFoundException e ) {} + + + try + { + Property p2 = (Property)m_session.getItem("/A/b"); + fail("Found property with wrong case"); + } + catch( PathNotFoundException e ) {} + + } + + public void testCase3() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("x","foo-a"); + + Node nd2 = m_session.getRootNode().addNode("a"); + nd2.setProperty("x","foo-b"); + + m_session.save(); + + assertFalse("same",nd.isSame(nd2)); + + Node nda = (Node) m_session.getItem("/A"); + assertEquals("foo-a",nda.getProperty("x").getString()); + + Node ndb = (Node) m_session.getItem("/a"); + assertEquals("foo-b",ndb.getProperty("x").getString()); + } + + public void testPropertyCase1() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("x","foo-a"); + nd.setProperty("X","foo-b"); + + m_session.save(); + + Node nda = (Node) m_session.getItem("/A"); + assertEquals("foo-a",nda.getProperty("x").getString()); + assertEquals("foo-b",nda.getProperty("X").getString()); + } + public static Test suite() + { + return new TestSuite( JdbcProviderTest.class ); + } + +}
jalkanen/Priha
541d8c2643047e91bf92e9e741ed3694d83714fb
Added testPropertyCase1
diff --git a/tests/java/org/priha/providers/FileProviderTest.java b/tests/java/org/priha/providers/FileProviderTest.java index df5f873..ca9f39f 100644 --- a/tests/java/org/priha/providers/FileProviderTest.java +++ b/tests/java/org/priha/providers/FileProviderTest.java @@ -1,122 +1,133 @@ package org.priha.providers; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import junit.framework.Test; import junit.framework.TestSuite; import org.priha.AbstractTest; import org.priha.core.SessionImpl; public class FileProviderTest extends AbstractTest { SessionImpl m_session; public void setUp() throws Exception { super.setUp(); m_session = getNewSession(); } public void tearDown() throws Exception { m_session.logout(); super.tearDown(); } private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { Node nd = m_session.getRootNode().addNode(UTF8_NAME); nd.setProperty(UTF8_NAME, UTF8_NAME); m_session.save(); Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); Property p2 = nd2.getProperty(UTF8_NAME); assertEquals(UTF8_NAME,nd2.getName()); assertEquals(UTF8_NAME,p2.getName()); assertEquals(UTF8_NAME,p2.getString()); } /** * JCR names are case-sensitive, so let's check that all these work. */ public void testCase1() throws Exception { Node nd = m_session.getRootNode().addNode("Test One"); nd.setProperty("Property One","KILL"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/test one"); fail("Found with wrong case"); } catch( ItemNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/Test One/property one"); fail("Found property with wrong case"); } catch( ItemNotFoundException e ) {} } public void testCase2() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("B", "foo"); m_session.save(); try { Node nd2 = (Node)m_session.getItem("/a"); fail("Found with wrong case"); } catch( ItemNotFoundException e ) {} try { Property p2 = (Property)m_session.getItem("/A/b"); fail("Found property with wrong case"); } catch( ItemNotFoundException e ) {} } public void testCase3() throws Exception { Node nd = m_session.getRootNode().addNode("A"); nd.setProperty("x","foo-a"); Node nd2 = m_session.getRootNode().addNode("a"); nd2.setProperty("x","foo-b"); m_session.save(); assertFalse("same",nd.isSame(nd2)); Node nda = (Node) m_session.getItem("/A"); assertEquals("foo-a",nda.getProperty("x").getString()); Node ndb = (Node) m_session.getItem("/a"); assertEquals("foo-b",ndb.getProperty("x").getString()); } - + public void testPropertyCase1() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("x","foo-a"); + nd.setProperty("X","foo-b"); + + m_session.save(); + + Node nda = (Node) m_session.getItem("/A"); + assertEquals("foo-a",nda.getProperty("x").getString()); + assertEquals("foo-b",nda.getProperty("X").getString()); + } public static Test suite() { return new TestSuite( FileProviderTest.class ); } }
jalkanen/Priha
4e7c659cf3aac3527d4e282124b513c6ac2438c1
Added FileProviderTest.
diff --git a/tests/java/org/priha/AbstractTest.java b/tests/java/org/priha/AbstractTest.java index 0befd81..b5d1dc4 100644 --- a/tests/java/org/priha/AbstractTest.java +++ b/tests/java/org/priha/AbstractTest.java @@ -1,50 +1,53 @@ package org.priha; -import javax.jcr.Node; -import javax.jcr.NodeIterator; -import javax.jcr.PropertyIterator; +import javax.jcr.*; import junit.framework.TestCase; import org.priha.core.RepositoryImpl; import org.priha.core.SessionImpl; public abstract class AbstractTest extends TestCase { protected RepositoryImpl m_repository; protected static final String WORKSPACE = "default"; @Override protected void setUp() throws Exception { super.setUp(); m_repository = RepositoryManager.getRepository(); } + protected SessionImpl getNewSession() throws LoginException, RepositoryException + { + return m_repository.login( new SimpleCredentials("foo", new char[0]) ); + } + protected void tearDown() throws Exception { super.tearDown(); TestUtil.emptyRepo( m_repository ); SessionImpl session = m_repository.superUserLogin( WORKSPACE ); try { Node nd = session.getRootNode(); NodeIterator ni = nd.getNodes(); // jcr:system assertTrue("Repository not empty: "+ni.getSize()+" Nodes left", ni.getSize() == 1); PropertyIterator pi = nd.getProperties(); // jcr:uuid, jcr:mixinTypes and jcr:primaryType assertTrue("Properties not removed: "+pi.getSize()+" Props left", pi.getSize() == 3); } finally { session.logout(); } } } diff --git a/tests/java/org/priha/AllTests.java b/tests/java/org/priha/AllTests.java index 13bda53..1e02e19 100644 --- a/tests/java/org/priha/AllTests.java +++ b/tests/java/org/priha/AllTests.java @@ -1,21 +1,22 @@ package org.priha; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class AllTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite("Priha unit tests"); suite.addTest( org.priha.nodetype.AllTests.suite() ); suite.addTest( org.priha.core.AllTests.suite() ); suite.addTest( org.priha.util.AllTests.suite() ); suite.addTest( org.priha.xml.AllTests.suite() ); suite.addTest( org.priha.query.AllTests.suite() ); + suite.addTest( org.priha.providers.AllTests.suite() ); return suite; } } diff --git a/tests/java/org/priha/providers/AllTests.java b/tests/java/org/priha/providers/AllTests.java new file mode 100644 index 0000000..f31ae16 --- /dev/null +++ b/tests/java/org/priha/providers/AllTests.java @@ -0,0 +1,20 @@ +package org.priha.providers; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.priha.AbstractTest; + +public class AllTests extends AbstractTest +{ + + public static Test suite() + { + TestSuite suite = new TestSuite("Provider tests"); + + suite.addTest( FileProviderTest.suite() ); + + return suite; + } + +} diff --git a/tests/java/org/priha/providers/FileProviderTest.java b/tests/java/org/priha/providers/FileProviderTest.java new file mode 100644 index 0000000..df5f873 --- /dev/null +++ b/tests/java/org/priha/providers/FileProviderTest.java @@ -0,0 +1,122 @@ +package org.priha.providers; + +import javax.jcr.*; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.version.VersionException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.priha.AbstractTest; +import org.priha.core.SessionImpl; + +public class FileProviderTest extends AbstractTest +{ + SessionImpl m_session; + + public void setUp() throws Exception + { + super.setUp(); + m_session = getNewSession(); + } + + public void tearDown() throws Exception + { + m_session.logout(); + super.tearDown(); + } + + private static final String UTF8_NAME = "\u00e5\u304f"; // HIRAGANA KU + + public void testUTF8_1() throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException + { + Node nd = m_session.getRootNode().addNode(UTF8_NAME); + nd.setProperty(UTF8_NAME, UTF8_NAME); + + m_session.save(); + + Node nd2 = (Node)m_session.getItem("/"+UTF8_NAME); + Property p2 = nd2.getProperty(UTF8_NAME); + + assertEquals(UTF8_NAME,nd2.getName()); + assertEquals(UTF8_NAME,p2.getName()); + assertEquals(UTF8_NAME,p2.getString()); + } + + /** + * JCR names are case-sensitive, so let's check that all these work. + */ + public void testCase1() throws Exception + { + Node nd = m_session.getRootNode().addNode("Test One"); + nd.setProperty("Property One","KILL"); + + m_session.save(); + + try + { + Node nd2 = (Node)m_session.getItem("/test one"); + fail("Found with wrong case"); + } + catch( ItemNotFoundException e ) {} + + + try + { + Property p2 = (Property)m_session.getItem("/Test One/property one"); + fail("Found property with wrong case"); + } + catch( ItemNotFoundException e ) {} + } + + public void testCase2() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("B", "foo"); + m_session.save(); + + try + { + Node nd2 = (Node)m_session.getItem("/a"); + fail("Found with wrong case"); + } + catch( ItemNotFoundException e ) {} + + + try + { + Property p2 = (Property)m_session.getItem("/A/b"); + fail("Found property with wrong case"); + } + catch( ItemNotFoundException e ) {} + + } + + public void testCase3() throws Exception + { + Node nd = m_session.getRootNode().addNode("A"); + nd.setProperty("x","foo-a"); + + Node nd2 = m_session.getRootNode().addNode("a"); + nd2.setProperty("x","foo-b"); + + m_session.save(); + + assertFalse("same",nd.isSame(nd2)); + + Node nda = (Node) m_session.getItem("/A"); + assertEquals("foo-a",nda.getProperty("x").getString()); + + Node ndb = (Node) m_session.getItem("/a"); + assertEquals("foo-b",ndb.getProperty("x").getString()); + } + + + public static Test suite() + { + return new TestSuite( FileProviderTest.class ); + } + +}
binaryage/totalfinder-i18n
93d764e02ccfc2192d28d58df05d3db16d00bbc8
Re-save all remaining XIBs with Xcode 14.2 (14C18). See below for more information.
diff --git a/plugin/XIBs/CutAndPaste.xib b/plugin/XIBs/CutAndPaste.xib index f559850..44f271e 100644 --- a/plugin/XIBs/CutAndPaste.xib +++ b/plugin/XIBs/CutAndPaste.xib @@ -1,80 +1,80 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="19528" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="19528"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="AHEditMenuController"> <connections> <outlet property="$copyButton" destination="32" id="89"/> <outlet property="$cutButton" destination="33" id="88"/> <outlet property="$editMenuItemView" destination="26" id="86"/> <outlet property="$pasteButton" destination="31" id="87"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView autoresizesSubviews="NO" horizontalCompressionResistancePriority="1000" placeholderIntrinsicWidth="400" placeholderIntrinsicHeight="19" id="26" userLabel="EditMenuItemView" customClass="MenuTrackedRootView"> <rect key="frame" x="0.0" y="0.0" width="218" height="34"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <button verticalHuggingPriority="750" tag="36000" translatesAutoresizingMaskIntoConstraints="NO" id="33" userLabel="Cut Button" customClass="MenuTrackedButton"> <rect key="frame" x="20" y="7" width="40" height="20"/> <constraints> <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="40" id="FzI-0D-1ou"/> </constraints> <buttonCell key="cell" type="smallSquare" title="^Cut" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="34" customClass="WrenchMenuButtonCell"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="menu" size="11"/> </buttonCell> <connections> <action selector="$commandsDispatcher:" target="-2" id="48"/> </connections> </button> <button verticalHuggingPriority="750" tag="36001" translatesAutoresizingMaskIntoConstraints="NO" id="32" userLabel="Copy Button" customClass="MenuTrackedButton"> - <rect key="frame" x="62" y="7" width="42" height="20"/> + <rect key="frame" x="62" y="7" width="41" height="20"/> <constraints> <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="40" id="d4f-XI-OAS"/> </constraints> <buttonCell key="cell" type="smallSquare" title="^Copy" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="35" customClass="WrenchMenuButtonCell"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="menu" size="11"/> </buttonCell> <connections> <action selector="$commandsDispatcher:" target="-2" id="49"/> </connections> </button> <button verticalHuggingPriority="750" tag="36003" translatesAutoresizingMaskIntoConstraints="NO" id="31" userLabel="Paste Button" customClass="MenuTrackedButton"> - <rect key="frame" x="106" y="7" width="44" height="20"/> + <rect key="frame" x="105" y="7" width="43" height="20"/> <constraints> <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="40" id="pac-Hw-Vb6"/> </constraints> <buttonCell key="cell" type="smallSquare" title="^Paste" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="36" customClass="WrenchMenuButtonCell"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="menu" size="11"/> </buttonCell> <connections> <action selector="$commandsDispatcher:" target="-2" id="50"/> </connections> </button> </subviews> <constraints> <constraint firstItem="31" firstAttribute="top" secondItem="26" secondAttribute="top" constant="8" id="E61-8i-P6f"/> <constraint firstItem="33" firstAttribute="leading" secondItem="26" secondAttribute="leading" constant="20" id="EUC-Cr-oI9"/> <constraint firstItem="32" firstAttribute="leading" secondItem="33" secondAttribute="trailing" constant="2" id="EwJ-Ao-4Tl"/> <constraint firstItem="33" firstAttribute="top" secondItem="26" secondAttribute="top" constant="8" id="UH3-Rg-fM6"/> <constraint firstItem="31" firstAttribute="leading" secondItem="32" secondAttribute="trailing" constant="2" id="b9r-11-MRS"/> <constraint firstItem="32" firstAttribute="top" secondItem="26" secondAttribute="top" constant="8" id="pLU-J8-D33"/> </constraints> <point key="canvasLocation" x="139" y="179"/> </customView> <customObject id="40" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="26" id="V6l-BM-FdS"/> <outlet property="owner_" destination="-2" id="qpW-gu-vRm"/> </connections> </customObject> </objects> </document> diff --git a/plugin/XIBs/Licensing.xib b/plugin/XIBs/Licensing.xib index 2ce1513..79e6836 100644 --- a/plugin/XIBs/Licensing.xib +++ b/plugin/XIBs/Licensing.xib @@ -1,346 +1,346 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="19528" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="19528"/> - <plugIn identifier="com.apple.WebKit2IBPlugin" version="19528"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/> + <plugIn identifier="com.apple.WebKit2IBPlugin" version="21507"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="XMLicensingWindowController"> <connections> <outlet property="$currentView" destination="5" id="87"/> <outlet property="$licenseKey" destination="22" id="Zmd-9G-7hA"/> <outlet property="$licenseName" destination="20" id="X6N-3o-BmH"/> <outlet property="$licensingInfo" destination="fFG-VH-nDv" id="9xr-9b-FNb"/> <outlet property="$viewA" destination="5" id="107"/> <outlet property="$viewB" destination="24" id="105"/> <outlet property="$viewC" destination="54" id="106"/> <outlet property="window" destination="1" id="44"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customObject id="120" userLabel="Localizer -&gt; Window" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="wqR-T4-xos"/> <outlet property="owner_" destination="-2" id="pA3-Cu-pmQ"/> </connections> </customObject> <customObject id="127" userLabel="Localizer -&gt; RegistrationA" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="5" id="07e-6r-2Je"/> <outlet property="owner_" destination="-2" id="3Gn-E2-FUa"/> </connections> </customObject> <customObject id="130" userLabel="Localizer -&gt; RegistrationB" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="24" id="g7L-Qr-5XU"/> <outlet property="owner_" destination="-2" id="BIt-ac-LuS"/> </connections> </customObject> <customObject id="133" userLabel="Localizer -&gt; RegistrationC" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="54" id="lmA-1y-DCZ"/> <outlet property="owner_" destination="-2" id="YJ7-YF-9wV"/> </connections> </customObject> <userDefaultsController id="45" customClass="TotalUserDefaultsController"/> <window title="^TotalFinder Registration" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" animationBehavior="default" titlebarAppearsTransparent="YES" titleVisibility="hidden" id="1"> <windowStyleMask key="styleMask" titled="YES" closable="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="525" y="500" width="480" height="300"/> - <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1415"/> + <rect key="screenRect" x="0.0" y="0.0" width="1728" height="1055"/> <view key="contentView" id="2"> <rect key="frame" x="0.0" y="0.0" width="480" height="300"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="97"> <rect key="frame" x="20" y="184" width="100" height="100"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="LicensingDialogIcon" id="98"/> </imageView> </subviews> </view> <point key="canvasLocation" x="1755" y="-1401"/> </window> <customView id="5" userLabel="RegistrationA" customClass="MSZLinkedView"> <rect key="frame" x="0.0" y="0.0" width="480" height="300"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="6"> - <rect key="frame" x="373" y="13" width="94" height="32"/> + <rect key="frame" x="374" y="13" width="93" height="32"/> <buttonCell key="cell" type="push" title="^Register" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="19"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$registerApp:" target="-2" id="67"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="158"> - <rect key="frame" x="207" y="13" width="168" height="32"/> + <rect key="frame" x="209" y="13" width="167" height="32"/> <buttonCell key="cell" type="push" title="^Buy TotalFinder Now" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="159"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$visitStore:" target="-2" id="160"/> </connections> </button> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="22"> <rect key="frame" x="156" y="60" width="304" height="98"/> <constraints> <constraint firstAttribute="height" constant="98" id="h6r-OO-9HS"/> </constraints> <textFieldCell key="cell" controlSize="small" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" placeholderString="^License Key" drawsBackground="YES" id="23"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="45" name="value" keyPath="values.TotalFinderLicenseKey" id="113"> <dictionary key="options"> <string key="NSNullPlaceholder">License Key</string> </dictionary> </binding> <outlet property="nextKeyView" destination="20" id="109"/> </connections> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="20"> <rect key="frame" x="156" y="171" width="304" height="19"/> <textFieldCell key="cell" controlSize="small" lineBreakMode="truncatingTail" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" placeholderString="^License Name" drawsBackground="YES" usesSingleLineMode="YES" id="21"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="45" name="value" keyPath="values.TotalFinderLicenseName" id="112"> <dictionary key="options"> <string key="NSNullPlaceholder">License Name</string> </dictionary> </binding> <outlet property="nextKeyView" destination="22" id="108"/> </connections> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="8"> <rect key="frame" x="154" y="220" width="296" height="32"/> <constraints> <constraint firstAttribute="width" constant="292" id="ncC-34-f0l"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Please enter your license details from the email we have sent you:" id="17"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="7"> <rect key="frame" x="154" y="260" width="115" height="20"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Registration" id="18"> <font key="font" metaFont="systemBold" size="17"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="20" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="156" id="2Vq-Yk-et4"/> <constraint firstItem="8" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="156" id="5uc-9c-Zkz"/> <constraint firstAttribute="trailing" secondItem="22" secondAttribute="trailing" constant="20" symbolic="YES" id="8vK-FE-ZON"/> <constraint firstItem="22" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="156" id="VKa-Rv-5IX"/> <constraint firstItem="6" firstAttribute="leading" secondItem="158" secondAttribute="trailing" constant="12" symbolic="YES" id="Ykb-iT-qIr"/> <constraint firstItem="20" firstAttribute="top" secondItem="5" secondAttribute="top" constant="110" id="a9F-7W-XME"/> <constraint firstItem="8" firstAttribute="top" secondItem="7" secondAttribute="bottom" constant="8" id="ask-F6-yc6"/> <constraint firstItem="7" firstAttribute="top" secondItem="5" secondAttribute="top" constant="20" id="hu4-Ul-vI7"/> <constraint firstAttribute="bottom" secondItem="158" secondAttribute="bottom" constant="20" id="kCP-tj-YL8"/> <constraint firstAttribute="trailing" secondItem="20" secondAttribute="trailing" constant="20" symbolic="YES" id="lR1-RS-BNv"/> <constraint firstItem="7" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="156" id="to7-RV-17q"/> <constraint firstAttribute="trailing" secondItem="6" secondAttribute="trailing" constant="20" symbolic="YES" id="u6W-fi-6XP"/> <constraint firstItem="6" firstAttribute="baseline" secondItem="158" secondAttribute="baseline" id="zdI-O0-mQ5"/> <constraint firstItem="22" firstAttribute="top" secondItem="20" secondAttribute="bottom" constant="13" id="zzm-1V-gER"/> </constraints> <connections> <outlet property="$nextView" destination="54" id="90"/> </connections> <point key="canvasLocation" x="2303" y="-1000"/> </customView> <customView id="24" userLabel="RegistrationB" customClass="MSZLinkedView"> <rect key="frame" x="0.0" y="0.0" width="480" height="300"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="26"> <rect key="frame" x="154" y="196" width="41" height="19"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" sendsActionOnEndEditing="YES" state="on" placeholderString="Name" id="37"> <font key="font" size="15" name="Monaco"/> <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="45" name="value" keyPath="values.TotalFinderLicenseName" id="114"/> </connections> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="29"> <rect key="frame" x="154" y="236" width="296" height="16"/> <constraints> <constraint firstAttribute="width" constant="292" id="7Yx-2Q-2Gm"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^This TotalFinder copy is licensed to:" id="34"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="196" translatesAutoresizingMaskIntoConstraints="NO" id="30"> <rect key="frame" x="154" y="260" width="200" height="20"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Thanks for registering!" id="33"> <font key="font" metaFont="systemBold" size="17"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <wkWebView wantsLayer="YES" allowsLinkPreview="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fFG-VH-nDv"> <rect key="frame" x="20" y="60" width="440" height="115"/> <wkWebViewConfiguration key="configuration" allowsAirPlayForMediaPlayback="NO"> <audiovisualMediaTypes key="mediaTypesRequiringUserActionForPlayback" none="YES"/> <wkPreferences key="preferences"/> </wkWebViewConfiguration> <connections> <outlet property="navigationDelegate" destination="-2" id="JYc-yi-pmF"/> </connections> </wkWebView> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="27"> - <rect key="frame" x="251" y="13" width="140" height="32"/> + <rect key="frame" x="253" y="13" width="139" height="32"/> <buttonCell key="cell" type="push" title="^Change License" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="36"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent"></string> </buttonCell> <connections> <action selector="$previousView:" target="-2" id="52"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="31"> - <rect key="frame" x="389" y="13" width="78" height="32"/> + <rect key="frame" x="390" y="13" width="77" height="32"/> <buttonCell key="cell" type="push" title="^Close" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="32"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$close:" target="-2" id="93"/> </connections> </button> </subviews> <constraints> <constraint firstItem="29" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="156" id="9X5-RU-fob"/> <constraint firstItem="fFG-VH-nDv" firstAttribute="top" secondItem="26" secondAttribute="bottom" constant="21" id="NRH-vD-4Ol"/> <constraint firstAttribute="trailing" secondItem="31" secondAttribute="trailing" constant="20" symbolic="YES" id="OBN-R4-ktR"/> <constraint firstItem="26" firstAttribute="top" secondItem="29" secondAttribute="bottom" constant="21" id="S4e-bh-zej"/> <constraint firstAttribute="trailing" secondItem="fFG-VH-nDv" secondAttribute="trailing" constant="20" symbolic="YES" id="Yjg-c8-Gri"/> <constraint firstItem="26" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="156" id="Yl3-jd-O7T"/> <constraint firstItem="31" firstAttribute="baseline" secondItem="27" secondAttribute="baseline" id="dnL-zQ-mAP"/> <constraint firstItem="27" firstAttribute="top" secondItem="fFG-VH-nDv" secondAttribute="bottom" constant="20" symbolic="YES" id="ejw-Sh-sB8"/> <constraint firstItem="31" firstAttribute="leading" secondItem="27" secondAttribute="trailing" constant="12" symbolic="YES" id="fmX-jq-gTh"/> <constraint firstItem="30" firstAttribute="top" secondItem="24" secondAttribute="top" constant="20" symbolic="YES" id="hre-1f-90Q"/> <constraint firstItem="fFG-VH-nDv" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="20" symbolic="YES" id="jng-OY-WZl"/> <constraint firstItem="29" firstAttribute="top" secondItem="30" secondAttribute="bottom" constant="8" symbolic="YES" id="jri-M5-TFy"/> <constraint firstAttribute="bottom" secondItem="27" secondAttribute="bottom" constant="20" symbolic="YES" id="lMT-Ou-PIX"/> <constraint firstItem="30" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="156" id="nCL-PZ-PUh"/> </constraints> <connections> <outlet property="$previousView" destination="5" id="92"/> </connections> <point key="canvasLocation" x="1754" y="-999"/> </customView> <customView id="54" userLabel="RegistrationC" customClass="MSZLinkedView"> <rect key="frame" x="0.0" y="0.0" width="480" height="300"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="74"> <rect key="frame" x="154" y="124" width="308" height="32"/> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^To purchase a license for TotalFinder, please visit BinaryAge web store." id="75"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="56"> <rect key="frame" x="154" y="236" width="308" height="16"/> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Please go back and try again." id="63"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="58"> <rect key="frame" x="154" y="260" width="174" height="20"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Invalid license code" id="61"> <font key="font" metaFont="systemBold" size="17"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="72"> - <rect key="frame" x="229" y="13" width="168" height="32"/> + <rect key="frame" x="230" y="13" width="167" height="32"/> <buttonCell key="cell" type="push" title="^Buy TotalFinder Now" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="73"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$visitStore:" target="-2" id="117"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="57"> <rect key="frame" x="395" y="13" width="72" height="32"/> <buttonCell key="cell" type="push" title="^Back" bezelStyle="rounded" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="62"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$previousView:" target="-2" id="83"/> </connections> </button> </subviews> <constraints> <constraint firstItem="56" firstAttribute="top" secondItem="58" secondAttribute="bottom" constant="8" id="03G-Ol-XXa"/> <constraint firstAttribute="trailing" secondItem="57" secondAttribute="trailing" constant="20" symbolic="YES" id="0hM-DT-P8t"/> <constraint firstItem="72" firstAttribute="baseline" secondItem="57" secondAttribute="baseline" id="41I-MV-t68"/> <constraint firstItem="58" firstAttribute="top" secondItem="54" secondAttribute="top" constant="20" id="FCW-1I-RUz"/> <constraint firstItem="57" firstAttribute="leading" secondItem="72" secondAttribute="trailing" constant="12" symbolic="YES" id="GyW-kP-C9Z"/> <constraint firstAttribute="trailing" secondItem="56" secondAttribute="trailing" constant="20" symbolic="YES" id="KE2-ls-SZG"/> <constraint firstItem="58" firstAttribute="leading" secondItem="54" secondAttribute="leading" constant="156" id="LwA-nz-YkU"/> <constraint firstItem="56" firstAttribute="leading" secondItem="54" secondAttribute="leading" constant="156" id="QkL-qk-15h"/> <constraint firstItem="74" firstAttribute="top" secondItem="56" secondAttribute="bottom" constant="80" id="XJ3-I8-IZN"/> <constraint firstItem="74" firstAttribute="leading" secondItem="54" secondAttribute="leading" constant="156" id="fRu-SJ-Pjt"/> <constraint firstAttribute="trailing" secondItem="74" secondAttribute="trailing" constant="20" symbolic="YES" id="nGO-Lc-j5N"/> <constraint firstAttribute="bottom" secondItem="72" secondAttribute="bottom" constant="20" symbolic="YES" id="zkX-d8-3q1"/> </constraints> <connections> <outlet property="$previousView" destination="5" id="95"/> </connections> <point key="canvasLocation" x="1204" y="-998"/> </customView> </objects> <resources> <image name="LicensingDialogIcon" width="512" height="512"/> </resources> </document> diff --git a/plugin/XIBs/ShellPreferences.xib b/plugin/XIBs/ShellPreferences.xib index 3a080a3..2936f26 100644 --- a/plugin/XIBs/ShellPreferences.xib +++ b/plugin/XIBs/ShellPreferences.xib @@ -1,318 +1,321 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="19528" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="19528"/> - <plugIn identifier="com.apple.WebKit2IBPlugin" version="19528"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/> + <plugIn identifier="com.apple.WebKit2IBPlugin" version="21507"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="TFShellPreferencesController"> <connections> <outlet property="$aboutContent" destination="Eql-JN-ZhJ" id="oqr-Ms-hyJ"/> <outlet property="$aboutPreferences" destination="1" id="229"/> <outlet property="$dockPreferences" destination="333" id="365"/> <outlet property="$menusPreferences" destination="316" id="366"/> <outlet property="$registerButton" destination="96" id="233"/> <outlet property="$registeredTo" destination="95" id="232"/> <outlet property="$registrationPreferences" destination="7" id="230"/> <outlet property="$tabsPreferences" destination="8uq-4v-kht" id="iLo-k4-P2D"/> <outlet property="$titleInAbout" destination="293" id="303"/> <outlet property="$titleInRegistration" destination="97" id="304"/> <outlet property="$titleInUpdates" destination="258" id="305"/> <outlet property="$updatesPreferences" destination="87" id="231"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="7" userLabel="Registration Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="101"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="440" translatesAutoresizingMaskIntoConstraints="NO" id="97"> <rect key="frame" x="18" y="53" width="444" height="28"/> <constraints> <constraint firstAttribute="width" constant="440" id="hTq-0b-4ws"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="98"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="96"> - <rect key="frame" x="20" y="2" width="62" height="19"/> + <rect key="frame" x="20" y="2" width="61" height="19"/> <buttonCell key="cell" type="roundRect" title="Register" bezelStyle="roundedRect" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="99"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="cellTitle"/> </buttonCell> <connections> <action selector="$showLicensingWindow:" target="-2" id="306"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="95"> <rect key="frame" x="18" y="29" width="146" height="16"/> <textFieldCell key="cell" lineBreakMode="truncatingTail" sendsActionOnEndEditing="YES" title="Registered to John Doe" usesSingleLineMode="YES" id="100"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="97" firstAttribute="top" secondItem="7" secondAttribute="top" constant="20" symbolic="YES" id="120"/> <constraint firstItem="97" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="121"/> <constraint firstItem="95" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="128"/> <constraint firstItem="96" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="130"/> <constraint firstItem="95" firstAttribute="top" secondItem="97" secondAttribute="bottom" constant="8" symbolic="YES" id="246"/> <constraint firstItem="96" firstAttribute="top" secondItem="95" secondAttribute="bottom" constant="8" symbolic="YES" id="247"/> </constraints> <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="215" userLabel="Registration Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="7" id="217"/> <outlet property="owner_" destination="-2" id="216"/> </connections> </customObject> <customView id="87" userLabel="Updates Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="140"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="152"> <rect key="frame" x="38" y="44" width="205" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Automatically check the website for updates" id="162"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="154"> <rect key="frame" x="38" y="5" width="153" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Participate in TotalFinder testing" id="161"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button translatesAutoresizingMaskIntoConstraints="NO" id="155" userLabel="Check Box"> <rect key="frame" x="18" y="19" width="159" height="18"/> <buttonCell key="cell" type="check" title="^Include pre-releases" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="160"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderUsePreReleases" id="211"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="156"> <rect key="frame" x="18" y="58" width="148" height="18"/> <buttonCell key="cell" type="check" title="^Check for Updates" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="159"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderCheckForUpdates" id="Mgr-b0-keU"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="157"> <rect key="frame" x="172" y="57" width="74" height="16"/> <buttonCell key="cell" type="push" title="^Check Now" bezelStyle="rounded" alignment="center" controlSize="mini" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="158"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="miniSystem"/> </buttonCell> <connections> <action selector="$checkForUpdates:" target="-2" id="235"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="258"> <rect key="frame" x="18" y="92" width="191" height="28"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="259"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="156" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="196"/> <constraint firstItem="157" firstAttribute="leading" secondItem="156" secondAttribute="trailing" constant="8" symbolic="YES" id="197"/> <constraint firstItem="155" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="204"/> <constraint firstItem="154" firstAttribute="leading" secondItem="152" secondAttribute="leading" id="205"/> <constraint firstItem="155" firstAttribute="top" secondItem="152" secondAttribute="bottom" constant="8" symbolic="YES" id="248"/> <constraint firstItem="258" firstAttribute="top" secondItem="87" secondAttribute="top" constant="20" symbolic="YES" id="262"/> <constraint firstItem="157" firstAttribute="bottom" secondItem="156" secondAttribute="bottom" id="267"/> <constraint firstItem="258" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="268"/> <constraint firstItem="157" firstAttribute="top" secondItem="87" secondAttribute="top" constant="68" id="269"/> <constraint firstItem="154" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="40" id="277"/> <constraint firstAttribute="bottom" secondItem="155" secondAttribute="bottom" constant="20" symbolic="YES" id="278"/> <constraint firstAttribute="bottom" secondItem="154" secondAttribute="bottom" constant="5" id="283"/> <constraint firstItem="154" firstAttribute="top" secondItem="155" secondAttribute="bottom" constant="4" id="284"/> <constraint firstItem="152" firstAttribute="top" secondItem="156" secondAttribute="bottom" constant="4" id="285"/> </constraints> + <point key="canvasLocation" x="547" y="-72"/> </customView> <customObject id="218" userLabel="Updates Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="87" id="224"/> <outlet property="owner_" destination="-2" id="219"/> </connections> </customObject> <customView id="1" userLabel="About Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="227"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <wkWebView wantsLayer="YES" allowsLinkPreview="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Eql-JN-ZhJ"> <rect key="frame" x="20" y="26" width="440" height="121"/> <wkWebViewConfiguration key="configuration" allowsAirPlayForMediaPlayback="NO"> <audiovisualMediaTypes key="mediaTypesRequiringUserActionForPlayback" none="YES"/> <wkPreferences key="preferences"/> </wkWebViewConfiguration> <connections> <outlet property="navigationDelegate" destination="-2" id="Vbx-6W-if8"/> </connections> </wkWebView> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="440" translatesAutoresizingMaskIntoConstraints="NO" id="134"> <rect key="frame" x="18" y="155" width="207" height="16"/> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Thank you for using TotalFinder!" usesSingleLineMode="YES" id="135"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="293"> <rect key="frame" x="18" y="179" width="444" height="28"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="294"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="308"> <rect key="frame" x="20" y="-1" width="184" height="19"/> <buttonCell key="cell" type="roundRect" title="^Reset TotalFinder to defaults" bezelStyle="roundedRect" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="309"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="cellTitle"/> </buttonCell> <connections> <action selector="$resetToDefaults:" target="-2" id="315"/> </connections> </button> </subviews> <constraints> <constraint firstItem="293" firstAttribute="top" secondItem="1" secondAttribute="top" constant="20" symbolic="YES" id="297"/> <constraint firstItem="293" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="298"/> <constraint firstItem="308" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="312"/> <constraint firstItem="308" firstAttribute="bottom" secondItem="1" secondAttribute="bottom" id="314"/> <constraint firstItem="134" firstAttribute="leading" secondItem="293" secondAttribute="leading" id="Cxh-45-C83"/> <constraint firstItem="134" firstAttribute="top" secondItem="293" secondAttribute="bottom" constant="8" symbolic="YES" id="Omi-6z-SoP"/> <constraint firstItem="Eql-JN-ZhJ" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="gfi-IP-7vv"/> <constraint firstAttribute="trailing" secondItem="293" secondAttribute="trailing" constant="20" symbolic="YES" id="h8U-fO-ZuI"/> <constraint firstAttribute="trailing" secondItem="Eql-JN-ZhJ" secondAttribute="trailing" constant="20" symbolic="YES" id="hwM-lS-swU"/> <constraint firstItem="Eql-JN-ZhJ" firstAttribute="top" secondItem="134" secondAttribute="bottom" constant="8" symbolic="YES" id="iw5-5v-851"/> <constraint firstItem="308" firstAttribute="top" secondItem="Eql-JN-ZhJ" secondAttribute="bottom" constant="8" symbolic="YES" id="klM-UO-YWF"/> </constraints> <point key="canvasLocation" x="139" y="150"/> </customView> <customObject id="221" userLabel="About Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="225"/> <outlet property="owner_" destination="-2" id="222"/> </connections> </customObject> <customView id="333" userLabel="Dock Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="34"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="348"> <rect key="frame" x="18" y="8" width="177" height="18"/> <buttonCell key="cell" type="check" title="^Keep original Dock icon" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="349"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderDontCustomizeDockIcon" id="369"/> </connections> </button> </subviews> <constraints> <constraint firstItem="348" firstAttribute="leading" secondItem="333" secondAttribute="leading" constant="20" symbolic="YES" id="356"/> <constraint firstItem="348" firstAttribute="centerY" secondItem="333" secondAttribute="centerY" id="370"/> </constraints> + <point key="canvasLocation" x="104" y="-133"/> </customView> <customView id="8uq-4v-kht" userLabel="Tabs Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="64"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="J6d-M3-FOb"> <rect key="frame" x="18" y="36" width="180" height="18"/> <buttonCell key="cell" type="check" title="^Disable tabs completely" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="eeg-k4-55d"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <action selector="$disableTabsCompletely:" target="-2" id="OeT-jd-1nq"/> <binding destination="94" name="value" keyPath="values.TotalFinderTabsDisabled" id="xA9-mr-Dgn"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="wo8-mU-gzk"> <rect key="frame" x="39" y="18" width="358" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^This will effectively disable tabs, dual mode and visor. Finder restart is needed." id="2MQ-dx-5TV"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="J6d-M3-FOb" firstAttribute="leading" secondItem="8uq-4v-kht" secondAttribute="leading" constant="20" symbolic="YES" id="J6s-HG-TwS"/> <constraint firstItem="J6d-M3-FOb" firstAttribute="top" secondItem="8uq-4v-kht" secondAttribute="top" constant="11" id="LbD-yg-Erj"/> <constraint firstItem="wo8-mU-gzk" firstAttribute="leading" secondItem="J6d-M3-FOb" secondAttribute="leading" constant="21" id="lfA-yT-amC"/> <constraint firstItem="wo8-mU-gzk" firstAttribute="top" secondItem="J6d-M3-FOb" secondAttribute="bottom" constant="8" id="pO7-UY-2E2"/> </constraints> <point key="canvasLocation" x="139" y="151"/> </customView> <customObject id="345" userLabel="Dock Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="333" id="358"/> <outlet property="owner_" destination="-2" id="347"/> </connections> </customObject> <customObject id="mbL-Rz-ge5" userLabel="Tabs Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="8uq-4v-kht" id="ahm-Fv-KC7"/> <outlet property="owner_" destination="-2" id="4OD-Ed-CB4"/> </connections> </customObject> <customView id="316" userLabel="Menus Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="34"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="317"> <rect key="frame" x="18" y="8" width="167" height="18"/> <buttonCell key="cell" type="check" title="^Hide icon in Menu Bar" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="318"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderShowStatusItem" id="367"> <dictionary key="options"> <string key="NSValueTransformerName">NSNegateBoolean</string> </dictionary> </binding> </connections> </button> </subviews> <constraints> <constraint firstItem="317" firstAttribute="leading" secondItem="316" secondAttribute="leading" constant="20" symbolic="YES" id="322"/> <constraint firstItem="317" firstAttribute="centerY" secondItem="316" secondAttribute="centerY" id="371"/> </constraints> + <point key="canvasLocation" x="-547" y="-72"/> </customView> <customObject id="342" userLabel="Menus Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="316" id="357"/> <outlet property="owner_" destination="-2" id="344"/> </connections> </customObject> <userDefaultsController id="94" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document>
binaryage/totalfinder-i18n
23237e1b112ba246c694a7cd92f8918824284e45
TotalFinderIconGrey: Add properly prescaled asset for use as a toolbar icon to avoid ugly unfiltered downscaling artifacts at runtime.
diff --git a/plugin/Icons/TotalFinderIconGrey.icns b/plugin/Icons/TotalFinderIconGrey.icns new file mode 100644 index 0000000..a1fc78c Binary files /dev/null and b/plugin/Icons/TotalFinderIconGrey.icns differ
binaryage/totalfinder-i18n
44e93d99cab5971d56d569884eb53d2f91cedc71
installer/readme: Update contents of the bundled readme to reflect the current state of TotalFinder as of 1.15.0.
diff --git a/installer/readme.html b/installer/readme.html index cfdd51f..74f309b 100644 --- a/installer/readme.html +++ b/installer/readme.html @@ -1,353 +1,353 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>TotalFinder from BinaryAge</title> <style type="text/css"> /* ----------------------------------------------------------------------- Blueprint CSS Framework 0.9 http://blueprintcss.org * Copyright (c) 2007-Present. See LICENSE for more info. * See README for instructions on how to use Blueprint. * For credits and origins, see AUTHORS. * This is a compressed file. See the sources in the 'src' directory. ----------------------------------------------------------------------- */ /* reset.css */ html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, dialog, figure, footer, header, hgroup, nav, section {margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;} article, aside, dialog, figure, footer, header, hgroup, nav, section {display:block;} body {line-height:1.5;} table {border-collapse:separate;border-spacing:0;} caption, th, td {text-align:left;font-weight:normal;} table, td, th {vertical-align:middle;} blockquote:before, blockquote:after, q:before, q:after {content:"";} blockquote, q {quotes:"" "";} a img {border:none;} /* typography.css */ html {font-size:100.01%;} h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111;} h1 {font-size:3em;line-height:1;margin-bottom:0.5em;} h2 {font-size:2em;margin-bottom:0.75em;} h3 {font-size:1.5em;line-height:1;margin-bottom:1em;} h4 {font-size:1.2em;line-height:1.25;margin-bottom:1.25em;} h5 {font-size:1em;font-weight:bold;margin-bottom:1.5em;} h6 {font-size:1em;font-weight:bold;} h1 img, h2 img, h3 img, h4 img, h5 img, h6 img {margin:0;} p {margin:0 0 1.5em;} p img.left {float:left;margin:1.5em 1.5em 1.5em 0;padding:0;} p img.right {float:right;margin:1.5em 0 1.5em 1.5em;} a:focus, a:hover {color:#000;} a {color:#009;text-decoration:underline;} blockquote {margin:1.5em;color:#666;font-style:italic;} strong {font-weight:bold;} em, dfn {font-style:italic;} dfn {font-weight:bold;} sup, sub {line-height:0;} abbr, acronym {border-bottom:1px dotted #666;} address {margin:0 0 1.5em;font-style:italic;} del {color:#666;} pre {margin:1.5em 0;white-space:pre;} pre, code, tt {font:1em 'andale mono', 'lucida console', monospace;line-height:1.5;} li ul, li ol {margin:0;} ul, ol {margin:0 1.5em 1.5em 0;padding-left:3.333em;} ul {list-style-type:disc;} ol {list-style-type:decimal;} dl {margin:0 0 1.5em 0;} dl dt {font-weight:bold;} dd {margin-left:1.5em;} table {margin-bottom:1.4em;width:100%;} th {font-weight:bold;} thead th {background:#c3d9ff;} th, td, caption {padding:4px 10px 4px 5px;} tr.even td {background:#e5ecf9;} tfoot {font-style:italic;} caption {background:#eee;} .small {font-size:.8em;margin-bottom:1.875em;line-height:1.875em;} .large {font-size:1.2em;line-height:2.5em;margin-bottom:1.25em;} .hide {display:none;} .quiet {color:#666;} .loud {color:#000;} .highlight {background:#ff0;} .added {background:#060;color:#fff;} .removed {background:#900;color:#fff;} .first {margin-left:0;padding-left:0;} .last {margin-right:0;padding-right:0;} .top {margin-top:0;padding-top:0;} .bottom {margin-bottom:0;padding-bottom:0;} /* forms.css */ label {font-weight:bold;} fieldset {padding:1.4em;margin:0 0 1.5em 0;border:1px solid #ccc;} legend {font-weight:bold;font-size:1.2em;} input[type=text], input[type=password], input.text, input.title, textarea, select {background-color:#fff;border:1px solid #bbb;} input[type=text]:focus, input[type=password]:focus, input.text:focus, input.title:focus, textarea:focus, select:focus {border-color:#666;} input[type=text], input[type=password], input.text, input.title, textarea, select {margin:0.5em 0;} input.text, input.title {width:300px;padding:5px;} input.title {font-size:1.5em;} textarea {width:390px;height:250px;padding:5px;} input[type=checkbox], input[type=radio], input.checkbox, input.radio {position:relative;top:.25em;} form.inline {line-height:3;} form.inline p {margin-bottom:0;} .error, .notice, .success {padding:.8em;margin-bottom:1em;border:2px solid #ddd;} .error {background:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;} .notice {background:#FFF6BF;color:#514721;border-color:#FFD324;} .success {background:#E6EFC2;color:#264409;border-color:#C6D880;} .error a {color:#8a1f11;} .notice a {color:#514721;} .success a {color:#264409;} /* grid.css */ .container {width:950px;margin:0 auto;} .showgrid {background:url(/shared/img/grid.png);} .column, .span-1, .span-2, .span-3, .span-4, .span-5, .span-6, .span-7, .span-8, .span-9, .span-10, .span-11, .span-12, .span-13, .span-14, .span-15, .span-16, .span-17, .span-18, .span-19, .span-20, .span-21, .span-22, .span-23, .span-24 {float:left;margin-right:10px;} .last {margin-right:0;} .span-1 {width:30px;} .span-2 {width:70px;} .span-3 {width:110px;} .span-4 {width:150px;} .span-5 {width:190px;} .span-6 {width:230px;} .span-7 {width:270px;} .span-8 {width:310px;} .span-9 {width:350px;} .span-10 {width:390px;} .span-11 {width:430px;} .span-12 {width:470px;} .span-13 {width:510px;} .span-14 {width:550px;} .span-15 {width:590px;} .span-16 {width:630px;} .span-17 {width:670px;} .span-18 {width:710px;} .span-19 {width:750px;} .span-20 {width:790px;} .span-21 {width:830px;} .span-22 {width:870px;} .span-23 {width:910px;} .span-24 {width:950px;margin-right:0;} input.span-1, textarea.span-1, input.span-2, textarea.span-2, input.span-3, textarea.span-3, input.span-4, textarea.span-4, input.span-5, textarea.span-5, input.span-6, textarea.span-6, input.span-7, textarea.span-7, input.span-8, textarea.span-8, input.span-9, textarea.span-9, input.span-10, textarea.span-10, input.span-11, textarea.span-11, input.span-12, textarea.span-12, input.span-13, textarea.span-13, input.span-14, textarea.span-14, input.span-15, textarea.span-15, input.span-16, textarea.span-16, input.span-17, textarea.span-17, input.span-18, textarea.span-18, input.span-19, textarea.span-19, input.span-20, textarea.span-20, input.span-21, textarea.span-21, input.span-22, textarea.span-22, input.span-23, textarea.span-23, input.span-24, textarea.span-24 {border-left-width:1px!important;border-right-width:1px!important;padding-left:5px!important;padding-right:5px!important;} input.span-1, textarea.span-1 {width:18px!important;} input.span-2, textarea.span-2 {width:58px!important;} input.span-3, textarea.span-3 {width:98px!important;} input.span-4, textarea.span-4 {width:138px!important;} input.span-5, textarea.span-5 {width:178px!important;} input.span-6, textarea.span-6 {width:218px!important;} input.span-7, textarea.span-7 {width:258px!important;} input.span-8, textarea.span-8 {width:298px!important;} input.span-9, textarea.span-9 {width:338px!important;} input.span-10, textarea.span-10 {width:378px!important;} input.span-11, textarea.span-11 {width:418px!important;} input.span-12, textarea.span-12 {width:458px!important;} input.span-13, textarea.span-13 {width:498px!important;} input.span-14, textarea.span-14 {width:538px!important;} input.span-15, textarea.span-15 {width:578px!important;} input.span-16, textarea.span-16 {width:618px!important;} input.span-17, textarea.span-17 {width:658px!important;} input.span-18, textarea.span-18 {width:698px!important;} input.span-19, textarea.span-19 {width:738px!important;} input.span-20, textarea.span-20 {width:778px!important;} input.span-21, textarea.span-21 {width:818px!important;} input.span-22, textarea.span-22 {width:858px!important;} input.span-23, textarea.span-23 {width:898px!important;} input.span-24, textarea.span-24 {width:938px!important;} .append-1 {padding-right:40px;} .append-2 {padding-right:80px;} .append-3 {padding-right:120px;} .append-4 {padding-right:160px;} .append-5 {padding-right:200px;} .append-6 {padding-right:240px;} .append-7 {padding-right:280px;} .append-8 {padding-right:320px;} .append-9 {padding-right:360px;} .append-10 {padding-right:400px;} .append-11 {padding-right:440px;} .append-12 {padding-right:480px;} .append-13 {padding-right:520px;} .append-14 {padding-right:560px;} .append-15 {padding-right:600px;} .append-16 {padding-right:640px;} .append-17 {padding-right:680px;} .append-18 {padding-right:720px;} .append-19 {padding-right:760px;} .append-20 {padding-right:800px;} .append-21 {padding-right:840px;} .append-22 {padding-right:880px;} .append-23 {padding-right:920px;} .prepend-1 {padding-left:40px;} .prepend-2 {padding-left:80px;} .prepend-3 {padding-left:120px;} .prepend-4 {padding-left:160px;} .prepend-5 {padding-left:200px;} .prepend-6 {padding-left:240px;} .prepend-7 {padding-left:280px;} .prepend-8 {padding-left:320px;} .prepend-9 {padding-left:360px;} .prepend-10 {padding-left:400px;} .prepend-11 {padding-left:440px;} .prepend-12 {padding-left:480px;} .prepend-13 {padding-left:520px;} .prepend-14 {padding-left:560px;} .prepend-15 {padding-left:600px;} .prepend-16 {padding-left:640px;} .prepend-17 {padding-left:680px;} .prepend-18 {padding-left:720px;} .prepend-19 {padding-left:760px;} .prepend-20 {padding-left:800px;} .prepend-21 {padding-left:840px;} .prepend-22 {padding-left:880px;} .prepend-23 {padding-left:920px;} .border {padding-right:4px;margin-right:5px;border-right:1px solid #eee;} .colborder {padding-right:24px;margin-right:25px;border-right:1px solid #eee;} .pull-1 {margin-left:-40px;} .pull-2 {margin-left:-80px;} .pull-3 {margin-left:-120px;} .pull-4 {margin-left:-160px;} .pull-5 {margin-left:-200px;} .pull-6 {margin-left:-240px;} .pull-7 {margin-left:-280px;} .pull-8 {margin-left:-320px;} .pull-9 {margin-left:-360px;} .pull-10 {margin-left:-400px;} .pull-11 {margin-left:-440px;} .pull-12 {margin-left:-480px;} .pull-13 {margin-left:-520px;} .pull-14 {margin-left:-560px;} .pull-15 {margin-left:-600px;} .pull-16 {margin-left:-640px;} .pull-17 {margin-left:-680px;} .pull-18 {margin-left:-720px;} .pull-19 {margin-left:-760px;} .pull-20 {margin-left:-800px;} .pull-21 {margin-left:-840px;} .pull-22 {margin-left:-880px;} .pull-23 {margin-left:-920px;} .pull-24 {margin-left:-960px;} .pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float:left;position:relative;} .push-1 {margin:0 -40px 1.5em 40px;} .push-2 {margin:0 -80px 1.5em 80px;} .push-3 {margin:0 -120px 1.5em 120px;} .push-4 {margin:0 -160px 1.5em 160px;} .push-5 {margin:0 -200px 1.5em 200px;} .push-6 {margin:0 -240px 1.5em 240px;} .push-7 {margin:0 -280px 1.5em 280px;} .push-8 {margin:0 -320px 1.5em 320px;} .push-9 {margin:0 -360px 1.5em 360px;} .push-10 {margin:0 -400px 1.5em 400px;} .push-11 {margin:0 -440px 1.5em 440px;} .push-12 {margin:0 -480px 1.5em 480px;} .push-13 {margin:0 -520px 1.5em 520px;} .push-14 {margin:0 -560px 1.5em 560px;} .push-15 {margin:0 -600px 1.5em 600px;} .push-16 {margin:0 -640px 1.5em 640px;} .push-17 {margin:0 -680px 1.5em 680px;} .push-18 {margin:0 -720px 1.5em 720px;} .push-19 {margin:0 -760px 1.5em 760px;} .push-20 {margin:0 -800px 1.5em 800px;} .push-21 {margin:0 -840px 1.5em 840px;} .push-22 {margin:0 -880px 1.5em 880px;} .push-23 {margin:0 -920px 1.5em 920px;} .push-24 {margin:0 -960px 1.5em 960px;} .push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float:right;position:relative;} .prepend-top {margin-top:1.5em;} .append-bottom {margin-bottom:1.5em;} .box {padding:1.5em;margin-bottom:1.5em;background:#E5ECF9;} hr {background:#ddd;color:#ddd;clear:both;float:none;width:100%;height:.1em;margin:0 0 1.45em;border:none;} hr.space {background:#fff;color:#fff;visibility:hidden;} .clearfix:after, .container:after {content:"\0020";display:block;height:0;clear:both;visibility:hidden;overflow:hidden;} .clearfix, .container {display:block;} .clear {clear:both;} /* -----------------------------------------------------------------------*/ html { font: 11pt "Play", "Lucida Grande","Lucida Sans Unicode","Lucida Sans",Verdana,sans-serif; } .wrapper { width: 824px; margin: auto; margin-top: 60px; } h1 { font-size: 14px; font-weight: bold; margin:0; } h1 a { font-size: 50px; font-weight: bold; } h3 { font-size: 20px; font-weight: bold; } #sub { font-size: 20px; margin: 0; } a { color: #3A6394; font-weight: bold; text-decoration: none; } a:hover { color: #1C75DB; } .center { text-align: center; } .small { font-size: 14pt !important; weight: normal; } img { margin-top: 30px; margin-bottom: 40px; -webkit-box-shadow:0 0 20px #666; box-shadow:0 0 20px #666; -webkit-border-radius:4px; border-radius:4px; width: 80%; } .warn { color: red; } .warn a { color: red; } </style> <link href='http://fonts.googleapis.com/css?family=Play:400,700&v2' rel='stylesheet' type='text/css'> </head> <body> <div class="wrapper"> <div class="center"><h1><a href="https://totalfinder.binaryage.com">TotalFinder</a></h1></div> <br/> - <div class="center"><p>TotalFinder is a plugin for Finder.app which adds dual panel, keyboard shortcuts, colored labels and other useful features.</p></div> + <div class="center"><p>TotalFinder is a plugin/tweak for Finder.app which adds a dual panel view, additional keyboard shortcuts, colored labels, advanced path copying, cut and paste, and many other useful features.</p></div> <div class="center"><img src="intro.png" alt="TotalFinder"></div> <div class="center"> - <p>Compatible with macOS 12.0 (Monterey).</p> - <p class="warn">Not compatible with Apple's new ARM processors (M1, M1 PRO, M1 MAX, etc.).</p> - <p class="warn">Unfortunately it requires <a href="https://totalfinder.binaryage.com/sip">disabled System Integrity Protection</a>.</p> - <br> - <p>For compatibility with older macOS versions please <a href="https://totalfinder.binaryage.com/compatibility">see this table</a>.</p> - <p>The documentation is located at<br><a href="https://totalfinder.binaryage.com/about">https://totalfinder.binaryage.com/about</a></p> - <p>TotalFinder is no longer sold and supported. For discussion visit<br><a href="https://discuss.binaryage.com">https://discuss.binaryage.com</a></p> + <p>Compatible with macOS 13 Ventura, 12 Monterey, 11 Big Sur, and 10.15 Catalina.</p> + <p>Compatible with Apple Silicon (M1, M2, etc.), though <a href="https://totalfinder.binaryage.com/apple-silicon">not officially supported</a>.</p> + <p class="warn">TotalFinder unfortunately requires <a href="https://totalfinder.binaryage.com/sip">System Integrity Protection</a> to remain weakened while in use.</p> + <p>To find the correct TotalFinder version for older macOS versions, please <a href="https://totalfinder.binaryage.com/compatibility">check the compatibility table</a>.</p> + <p>The documentation is located at:<br><a href="https://totalfinder.binaryage.com/about">https://totalfinder.binaryage.com/about</a></p> + <p>TotalFinder is no longer sold or officially supported.</p> + <p>Feel free to talk about TotalFinder in the discussion thread on the BinaryAge forums:<br><a href="https://discuss.binaryage.com/t/8364">https://discuss.binaryage.com/t/8364</a></p> </div> </div> </body> </html> \ No newline at end of file diff --git a/installer/readme.pdf b/installer/readme.pdf index f01b340..ac70acf 100644 Binary files a/installer/readme.pdf and b/installer/readme.pdf differ
binaryage/totalfinder-i18n
249a9815a8015e9ca94d876d3fbfc0bcd9a8ec4c
make rubocop happy again
diff --git a/crashwatcher/ruby/extract-crash-info.rb b/crashwatcher/ruby/extract-crash-info.rb index 5788ace..96ab516 100755 --- a/crashwatcher/ruby/extract-crash-info.rb +++ b/crashwatcher/ruby/extract-crash-info.rb @@ -1,115 +1,115 @@ #!/usr/bin/env ruby # frozen_string_literal: true def parse_module_version(content) m = content.match(/\+\s*com.binaryage.totalfinder\s*\((.*?)\)/m) return nil if m.nil? # m[1] == 1.5.18 - 1.5.18 m[1].split('-')[0].strip end def parse_special_info(content) # "recent swizzled method" can appear in TotalFinder crash logs since v1.4.18 m = content.match(/recent swizzled method:(.*?)\n/m) return nil if m.nil? m[1].strip end def parse_plugin_identifier(content) m = content.match(/PlugIn Identifier:(.*?)\n/m) return nil if m.nil? m[1] end def find_first_ba_module(content) addresses = [] ranges = [] content.lines.each do |line| # extract addresses from callstacks on all threads # 8 com.apple.AppKit 0x00007fff88a0d68f -[NSApplication run] + 395 addresses << Regexp.last_match(1).to_i(16) if line =~ /^\s*\d+\s+.*?0x([0-9a-f]+)\s/ # extract loaded module ranges, filter out only com.binaryage related # 0x1181c2000 - 0x1181c3ff7 +com.binaryage.totalfinder.nodesktopdots ##VERSION## (##VERSION##) <...> /some/path if line =~ /^\s*0x([0-9a-f]+)\s+-\s+0x([0-9a-f]+)\s+.*?(com\.binaryage.*?)\s/ ranges << [Regexp.last_match(1).to_i(16), Regexp.last_match(2).to_i(16), Regexp.last_match(3)] end end # test if any address is present inside our ranges addresses.each do |address| ranges.each do |range| hit = address >= range[0] && address <= range[1] return range[2] if hit end end nil end file = File.absolute_path(ARGV[0]) # this is just a special sanity check to include related-crash-report.rb errors in case related-crash-report.rb throws related_script_path = File.join(File.dirname(File.absolute_path(__FILE__)), 'related-crash-report.rb') system(related_script_path, file, err: :out) result = $?.exitstatus throw "The crash report '#{file}' is not related to TotalFinder" if result != 3 content = File.read(file) res = 'TotalFinder ' begin module_version = parse_module_version(content) res += "#{module_version} " if module_version plugin = parse_special_info(content) plugin ||= parse_plugin_identifier(content) plugin ||= find_first_ba_module(content) plugin.strip! if plugin res += "crashed in #{plugin.gsub('com.binaryage.totalfinder.', '')} " if plugin rescue # ignored end details = [] begin - version = content.match(/Version:(.*?)\n/m)[1].split(' ')[0] + version = content.match(/Version:(.*?)\n/m)[1].split[0] details << "v#{version.strip}" rescue # ignored end begin version = content.match(/OS Version:.*?\((.*?)\)\n/m)[1] details << "OS #{version.strip}" rescue # ignored end begin type = content.match(/Exception Type:(.*?)\n/m)[1] x = type.match(/(.*?)\(.*\)/) type = x[1] if x # remove braced part if present type.downcase! type.sub!('exc_', '') type.sub!('_', ' ') details << type.strip rescue # ignored end begin - thread = content.match(/Crashed Thread:(.*?)\n/m)[1].split(' ')[0] + thread = content.match(/Crashed Thread:(.*?)\n/m)[1].split[0] details << "thread #{thread.strip}" rescue # ignored end res += "| #{details.join(', ')}" puts res diff --git a/crashwatcher/ruby/vendor/gist.rb b/crashwatcher/ruby/vendor/gist.rb index dd68b3a..916fd3e 100755 --- a/crashwatcher/ruby/vendor/gist.rb +++ b/crashwatcher/ruby/vendor/gist.rb @@ -1,652 +1,658 @@ #!/usr/bin/env ruby +# frozen_string_literal: true # https://github.com/defunkt/gist/blob/master/lib/gist.rb require 'net/https' require 'cgi' require 'uri' begin require 'json' rescue LoadError require File.join File.dirname(__FILE__), 'json.rb' end # It just gists. module Gist - extend self + module_function VERSION = '6.0.0' # A list of clipboard commands with copy and paste support. CLIPBOARD_COMMANDS = { - 'pbcopy' => 'pbpaste', - 'xclip' => 'xclip -o', - 'xsel -i' => 'xsel -o', - 'putclip' => 'getclip', - } + 'pbcopy' => 'pbpaste', + 'xclip' => 'xclip -o', + 'xsel -i' => 'xsel -o', + 'putclip' => 'getclip' + }.freeze - GITHUB_API_URL = URI("https://api.github.com/") - GITHUB_URL = URI("https://github.com/") - GIT_IO_URL = URI("https://git.io") + GITHUB_API_URL = URI('https://api.github.com/') + GITHUB_URL = URI('https://github.com/') + GIT_IO_URL = URI('https://git.io') - GITHUB_BASE_PATH = "" - GHE_BASE_PATH = "/api/v3" + GITHUB_BASE_PATH = '' + GHE_BASE_PATH = '/api/v3' GITHUB_CLIENT_ID = '4f7ec0d4eab38e74384e' - URL_ENV_NAME = "GITHUB_URL" - CLIENT_ID_ENV_NAME = "GIST_CLIENT_ID" + URL_ENV_NAME = 'GITHUB_URL' + CLIENT_ID_ENV_NAME = 'GIST_CLIENT_ID' USER_AGENT = "gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})" # Exception tag for errors raised while gisting. module Error - ; - def self.exception(*args) RuntimeError.new(*args).extend(self) end end class ClipboardError < RuntimeError include Error end # helper module for authentication token actions module AuthTokenFile def self.filename if ENV.key?(URL_ENV_NAME) File.expand_path "~/.gist.#{ENV[URL_ENV_NAME].gsub(/:/, '.').gsub(/[^a-z0-9.-]/, '')}" else - File.expand_path "~/.gist" + File.expand_path '~/.gist' end end def self.read File.read(filename).chomp end def self.write(token) - File.open(filename, 'w', 0600) do |f| + File.open(filename, 'w', 0o600) do |f| f.write token end end end # auth token for authentication # # @return [String] string value of access token or `nil`, if not found def auth_token - @token ||= AuthTokenFile.read rescue nil + @token ||= begin + AuthTokenFile.read + rescue + nil + end end # Upload a gist to https://gist.github.com # # @param [String] content the code you'd like to gist # @param [Hash] options more detailed options, see # the documentation for {multi_gist} # # @see http://developer.github.com/v3/gists/ - def gist(content, options = {}) + def gist(content, options={}) filename = options[:filename] || default_filename - multi_gist({filename => content}, options) + multi_gist({ filename => content }, options) end def default_filename - "gistfile1.txt" + 'gistfile1.txt' end # Upload a gist to https://gist.github.com # # @param [Hash] files the code you'd like to gist: filename => content # @param [Hash] options more detailed options # # @option options [String] :description the description # @option options [Boolean] :public (false) is this gist public # @option options [Boolean] :anonymous (false) is this gist anonymous # @option options [String] :access_token (`File.read("~/.gist")`) The OAuth2 access token. # @option options [String] :update the URL or id of a gist to update # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful. # @option options [Boolean] :open (false) Open the resulting URL in a browser. # @option options [Boolean] :skip_empty (false) Skip gisting empty files. # @option options [Symbol] :output (:all) The type of return value you'd like: # :html_url gives a String containing the url to the gist in a browser # :short_url gives a String contianing a git.io url that redirects to html_url # :javascript gives a String containing a script tag suitable for embedding the gist # :all gives a Hash containing the parsed json response from the server # # @return [String, Hash] the return value as configured by options[:output] # @raise [Gist::Error] if something went wrong # # @see http://developer.github.com/v3/gists/ - def multi_gist(files, options = {}) + def multi_gist(files, options={}) if options[:anonymous] raise 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \ - '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' + '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' else - access_token = (options[:access_token] || auth_token()) + access_token = (options[:access_token] || auth_token) end json = {} json[:description] = options[:description] if options[:description] - json[:public] = !!options[:public] + json[:public] = !options[:public].nil? json[:files] = {} files.each_pair do |(name, content)| - if content.to_s.strip == "" - raise "Cannot gist empty files" unless options[:skip_empty] + if content.to_s.strip == '' + raise 'Cannot gist empty files' unless options[:skip_empty] else - name = name == "-" ? default_filename : File.basename(name) - json[:files][name] = {:content => content} + name = name == '-' ? default_filename : File.basename(name) + json[:files][name] = { content: content } end end return if json[:files].empty? && options[:skip_empty] - existing_gist = options[:update].to_s.split("/").last + existing_gist = options[:update].to_s.split('/').last url = "#{base_path}/gists" - url << "/" << CGI.escape(existing_gist) if existing_gist.to_s != '' + url << '/' << CGI.escape(existing_gist) if existing_gist.to_s != '' request = Net::HTTP::Post.new(url) request['Authorization'] = "token #{access_token}" if access_token.to_s != '' request.body = JSON.dump(json) request.content_type = 'application/json' retried = false begin response = http(api_url, request) - if Net::HTTPSuccess === response + if response.is_a?(Net::HTTPSuccess) on_success(response.body, options) else raise "Got #{response.class} from gist: #{response.body}" end rescue => e raise if retried + retried = true retry end - rescue => e raise e.extend Error end # List all gists(private also) for authenticated user # otherwise list public gists for given username (optional argument) # # @param [String] user # @deprecated # # see https://developer.github.com/v3/gists/#list-gists - def list_gists(user = "") - url = "#{base_path}" + def list_gists(user='') + url = base_path.to_s - if user == "" - access_token = auth_token() - if access_token.to_s != '' - url << "/gists" + if user == '' + access_token = auth_token + if access_token.to_s == '' + raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists." + else + url << '/gists' request = Net::HTTP::Get.new(url) request['Authorization'] = "token #{access_token}" response = http(api_url, request) pretty_gist(response) - else - raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists." end else url << "/users/#{user}/gists" request = Net::HTTP::Get.new(url) response = http(api_url, request) pretty_gist(response) end end - def list_all_gists(user = "") - url = "#{base_path}" + def list_all_gists(user='') + url = base_path.to_s - if user == "" - url << "/gists?per_page=100" - else - url << "/users/#{user}/gists?per_page=100" - end + url << if user == '' + '/gists?per_page=100' + else + "/users/#{user}/gists?per_page=100" + end - get_gist_pages(url, auth_token()) + get_gist_pages(url, auth_token) end - def read_gist(id, file_name = nil, options = {}) + def read_gist(id, file_name=nil, options={}) url = "#{base_path}/gists/#{id}" - access_token = (options[:access_token] || auth_token()) - if access_token.to_s != '' - url << "?access_token=" << CGI.escape(access_token) - end + access_token = (options[:access_token] || auth_token) + url << '?access_token=' << CGI.escape(access_token) if access_token.to_s != '' request = Net::HTTP::Get.new(url) request['Authorization'] = "token #{access_token}" if access_token.to_s != '' response = http(api_url, request) if response.code == '200' body = JSON.parse(response.body) - files = body["files"] + files = body['files'] if file_name file = files[file_name] raise Error, "Gist with id of #{id} and file #{file_name} does not exist." unless file else file = files.values.first end - file["content"] + file['content'] else raise Error, "Gist with id of #{id} does not exist." end end def delete_gist(id) - id = id.split("/").last + id = id.split('/').last url = "#{base_path}/gists/#{id}" - access_token = auth_token() - if access_token.to_s != '' + access_token = auth_token + if access_token.to_s == '' + raise Error, "Not authenticated. Use 'gist --login' to login." + else request = Net::HTTP::Delete.new(url) - request["Authorization"] = "token #{access_token}" + request['Authorization'] = "token #{access_token}" response = http(api_url, request) - else - raise Error, "Not authenticated. Use 'gist --login' to login." end if response.code == '204' - puts "Deleted!" + puts 'Deleted!' else raise Error, "Gist with id of #{id} does not exist." end end - def get_gist_pages(url, access_token = "") - + def get_gist_pages(url, access_token='') request = Net::HTTP::Get.new(url) request['Authorization'] = "token #{access_token}" if access_token.to_s != '' response = http(api_url, request) pretty_gist(response) link_header = response.header['link'] if link_header - links = Hash[link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') }].invert + links = link_header.gsub(/(<|>|")/, '').split(',').to_h { |link| link.split('; rel=') }.invert get_gist_pages(links['next'], access_token) if links['next'] end - end # return prettified string result of response body for all gists # # @params [Net::HTTPResponse] response # @return [String] prettified result of listing all gists # # see https://developer.github.com/v3/gists/#response def pretty_gist(response) body = JSON.parse(response.body) if response.code == '200' body.each do |gist| - description = "#{gist['description'] || gist['files'].keys.join(" ")} #{gist['public'] ? '' : '(secret)'}" - puts "#{gist['html_url']} #{description.tr("\n", " ")}\n" + description = "#{gist['description'] || gist['files'].keys.join(' ')} #{gist['public'] ? '' : '(secret)'}" + puts "#{gist['html_url']} #{description.tr("\n", ' ')}\n" $stdout.flush end else raise Error, body['message'] end end # Convert long github urls into short git.io ones # # @param [String] url # @return [String] shortened url, or long url if shortening fails def shorten(url) - request = Net::HTTP::Post.new("/create") - request.set_form_data(:url => url) + request = Net::HTTP::Post.new('/create') + request.set_form_data(url: url) response = http(GIT_IO_URL, request) case response.code - when "200" + when '200' URI.join(GIT_IO_URL, response.body).to_s - when "201" + when '201' response['Location'] else url end end # Convert github url into raw file url # # Unfortunately the url returns from github's api is legacy, # we have to taking a HTTPRedirection before appending it # with '/raw'. Let's looking forward for github's api fix :) # # @param [String] url # @return [String] the raw file url def rawify(url) uri = URI(url) request = Net::HTTP::Get.new(uri.path) response = http(uri, request) - if Net::HTTPSuccess === response - url + '/raw' - elsif Net::HTTPRedirection === response + case response + when Net::HTTPSuccess + "#{url}/raw" + when Net::HTTPRedirection rawify(response.header['location']) end end # Log the user into gist. # - def login!(credentials = {}) + def login!(credentials={}) if (login_url == GITHUB_URL || ENV.key?(CLIENT_ID_ENV_NAME)) && credentials.empty? && !ENV.key?('GIST_USE_USERNAME_AND_PASSWORD') device_flow_login! else access_token_login!(credentials) end end def device_flow_login! - puts "Requesting login parameters..." - request = Net::HTTP::Post.new("/login/device/code") + puts 'Requesting login parameters...' + request = Net::HTTP::Post.new('/login/device/code') request.body = JSON.dump({ - :scope => 'gist', - :client_id => client_id, + scope: 'gist', + client_id: client_id }) request.content_type = 'application/json' - request['accept'] = "application/json" + request['accept'] = 'application/json' response = http(login_url, request) - if response.code != '200' - raise Error, "HTTP #{response.code}: #{response.body}" - end + raise Error, "HTTP #{response.code}: #{response.body}" if response.code != '200' body = JSON.parse(response.body) puts "Please sign in at #{body['verification_uri']}" puts " and enter code: #{body['user_code']}" device_code = body['device_code'] interval = body['interval'] loop do sleep(interval.to_i) - request = Net::HTTP::Post.new("/login/oauth/access_token") + request = Net::HTTP::Post.new('/login/oauth/access_token') request.body = JSON.dump({ - :client_id => client_id, - :grant_type => 'urn:ietf:params:oauth:grant-type:device_code', - :device_code => device_code + client_id: client_id, + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + device_code: device_code }) request.content_type = 'application/json' request['Accept'] = 'application/json' response = http(login_url, request) - if response.code != '200' - raise Error, "HTTP #{response.code}: #{response.body}" - end + raise Error, "HTTP #{response.code}: #{response.body}" if response.code != '200' + body = JSON.parse(response.body) break unless body['error'] == 'authorization_pending' end - if body['error'] - raise Error, body['error_description'] - end + raise Error, body['error_description'] if body['error'] AuthTokenFile.write JSON.parse(response.body)['access_token'] - puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/connections/applications/#{client_id}" + puts "Success! #{ENV[URL_ENV_NAME] || 'https://github.com/'}settings/connections/applications/#{client_id}" end # Logs the user into gist. # # This method asks the user for a username and password, and tries to obtain # and OAuth2 access token, which is then stored in ~/.gist # # @raise [Gist::Error] if something went wrong # @see http://developer.github.com/v3/oauth/ - def access_token_login!(credentials = {}) - puts "Obtaining OAuth2 access_token from GitHub." + def access_token_login!(credentials={}) + puts 'Obtaining OAuth2 access_token from GitHub.' loop do - print "GitHub username: " + print 'GitHub username: ' username = credentials[:username] || $stdin.gets.strip - print "GitHub password: " + print 'GitHub password: ' password = credentials[:password] || begin - `stty -echo` rescue nil - $stdin.gets.strip - ensure - `stty echo` rescue nil - end - puts "" + begin + `stty -echo` + rescue + nil + end + $stdin.gets.strip + ensure + begin + `stty echo` + rescue + nil + end + end + puts '' request = Net::HTTP::Post.new("#{base_path}/authorizations") request.body = JSON.dump({ - :scopes => [:gist], - :note => "The gist gem (#{Time.now})", - :note_url => "https://github.com/ConradIrwin/gist" + scopes: [:gist], + note: "The gist gem (#{Time.now})", + note_url: 'https://github.com/ConradIrwin/gist' }) request.content_type = 'application/json' request.basic_auth(username, password) response = http(api_url, request) - if Net::HTTPUnauthorized === response && response['X-GitHub-OTP'] - print "2-factor auth code: " + if response.is_a?(Net::HTTPUnauthorized) && response['X-GitHub-OTP'] + print '2-factor auth code: ' twofa_code = $stdin.gets.strip - puts "" + puts '' request['X-GitHub-OTP'] = twofa_code response = http(api_url, request) end - if Net::HTTPCreated === response + case response + when Net::HTTPCreated AuthTokenFile.write JSON.parse(response.body)['token'] - puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens" + puts "Success! #{ENV[URL_ENV_NAME] || 'https://github.com/'}settings/tokens" return - elsif Net::HTTPUnauthorized === response + when Net::HTTPUnauthorized puts "Error: #{JSON.parse(response.body)['message']}" next else raise "Got #{response.class} from gist: #{response.body}" end end rescue => e raise e.extend Error end # Return HTTP connection # # @param [URI::HTTP] The URI to which to connect # @return [Net::HTTP] def http_connection(uri) env = ENV['http_proxy'] || ENV['HTTP_PROXY'] connection = if env proxy = URI(env) if proxy.user Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(uri.host, uri.port) else Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port) end else Net::HTTP.new(uri.host, uri.port) end - if uri.scheme == "https" + if uri.scheme == 'https' connection.use_ssl = true connection.verify_mode = OpenSSL::SSL::VERIFY_NONE end connection.open_timeout = 10 connection.read_timeout = 10 connection end # Run an HTTP operation # # @param [URI::HTTP] The URI to which to connect # @param [Net::HTTPRequest] The request to make # @return [Net::HTTPResponse] def http(url, request) request['User-Agent'] = USER_AGENT http_connection(url).start do |http| http.request request end rescue Timeout::Error raise "Could not connect to #{api_url}" end # Called after an HTTP response to gist to perform post-processing. # # @param [String] body the text body from the github api # @param [Hash] options more detailed options, see # the documentation for {multi_gist} - def on_success(body, options = {}) + def on_success(body, options={}) json = JSON.parse(body) output = case options[:output] when :javascript - %Q{<script src="#{json['html_url']}.js"></script>} + %(<script src="#{json['html_url']}.js"></script>) when :html_url json['html_url'] when :raw_url rawify(json['html_url']) when :short_url shorten(json['html_url']) when :short_raw_url shorten(rawify(json['html_url'])) else json end Gist.copy(output.to_s) if options[:copy] Gist.open(json['html_url']) if options[:open] output end # Copy a string to the clipboard. # # @param [String] content # @raise [Gist::Error] if no clipboard integration could be found # def copy(content) IO.popen(clipboard_command(:copy), 'r+') { |clip| clip.print content } unless paste == content message = 'Copying to clipboard failed.' - if ENV["TMUX"] && clipboard_command(:copy) == 'pbcopy' + if ENV['TMUX'] && clipboard_command(:copy) == 'pbcopy' message << "\nIf you're running tmux on a mac, try http://robots.thoughtbot.com/post/19398560514/how-to-copy-and-paste-with-tmux-on-mac-os-x" end raise Error, message end rescue Error => e raise ClipboardError, e.message + "\nAttempted to copy: #{content}" end # Get a string from the clipboard. # # @param [String] content # @raise [Gist::Error] if no clipboard integration could be found def paste `#{clipboard_command(:paste)}` end # Find command from PATH environment. # # @param [String] cmd command name to find # @param [String] options PATH environment variable # @return [String] the command found - def which(cmd, path = ENV['PATH']) + def which(cmd, path=ENV['PATH']) if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/ - path.split(File::PATH_SEPARATOR).each { |dir| - f = File.join(dir, cmd + ".exe") + path.split(File::PATH_SEPARATOR).each do |dir| + f = File.join(dir, "#{cmd}.exe") return f if File.executable?(f) && !File.directory?(f) - } + end nil else - return system("which #{cmd} > /dev/null 2>&1") + system("which #{cmd} > /dev/null 2>&1") end end # Get the command to use for the clipboard action. # # @param [Symbol] action either :copy or :paste # @return [String] the command to run # @raise [Gist::ClipboardError] if no clipboard integration could be found def clipboard_command(action) command = CLIPBOARD_COMMANDS.keys.detect do |cmd| which cmd end - raise ClipboardError, <<-EOT unless command -Could not find copy command, tried: - #{CLIPBOARD_COMMANDS.values.join(' || ')} + raise ClipboardError, <<~EOT unless command + Could not find copy command, tried: + #{CLIPBOARD_COMMANDS.values.join(' || ')} EOT + action == :copy ? command : CLIPBOARD_COMMANDS[command] end # Open a URL in a browser. # # @param [String] url # @raise [RuntimeError] if no browser integration could be found # # This method was heavily inspired by defunkt's Gist#open, # @see https://github.com/defunkt/gist/blob/bca9b29/lib/gist.rb#L157 def open(url) command = if ENV['BROWSER'] ENV['BROWSER'] elsif RUBY_PLATFORM =~ /darwin/ 'open' elsif RUBY_PLATFORM =~ /linux/ - %w( + %w[ sensible-browser xdg-open firefox firefox-bin - ).detect do |cmd| + ].detect do |cmd| which cmd end elsif ENV['OS'] == 'Windows_NT' || RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw|wince/i 'start ""' else - raise "Could not work out how to use a browser." + raise 'Could not work out how to use a browser.' end `#{command} #{url}` end # Get the API base path def base_path ENV.key?(URL_ENV_NAME) ? GHE_BASE_PATH : GITHUB_BASE_PATH end def login_url ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_URL end # Get the API URL def api_url ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_API_URL end def client_id ENV.key?(CLIENT_ID_ENV_NAME) ? URI(ENV[CLIENT_ID_ENV_NAME]) : GITHUB_CLIENT_ID end def legacy_private_gister? return unless which('git') + `git config --global gist.private` =~ /\Ayes|1|true|on\z/i end - def should_be_public?(options = {}) + def should_be_public?(options={}) if options.key? :private !options[:private] else !Gist.legacy_private_gister? end end -end \ No newline at end of file +end diff --git a/crashwatcher/ruby/vendor/json.rb b/crashwatcher/ruby/vendor/json.rb index 578791f..f3b65e6 100644 --- a/crashwatcher/ruby/vendor/json.rb +++ b/crashwatcher/ruby/vendor/json.rb @@ -1,1304 +1,1305 @@ +# frozen_string_literal: true + require 'strscan' module JSON module Pure # This class implements the JSON parser that is used to parse a JSON string # into a Ruby data structure. class Parser < StringScanner STRING = /" ((?:[^\x0-\x1f"\\] | # escaped special characters: \\["\\\/bfnrt] | \\u[0-9a-fA-F]{4} | # match all but escaped special characters: \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*) - "/nx - INTEGER = /(-?0|-?[1-9]\d*)/ + "/nx.freeze + INTEGER = /(-?0|-?[1-9]\d*)/.freeze FLOAT = /(-? (?:0|[1-9]\d*) (?: \.\d+(?i:e[+-]?\d+) | \.\d+ | (?i:e[+-]?\d+) ) - )/x - NAN = /NaN/ - INFINITY = /Infinity/ - MINUS_INFINITY = /-Infinity/ - OBJECT_OPEN = /\{/ - OBJECT_CLOSE = /\}/ - ARRAY_OPEN = /\[/ - ARRAY_CLOSE = /\]/ - PAIR_DELIMITER = /:/ - COLLECTION_DELIMITER = /,/ - TRUE = /true/ - FALSE = /false/ - NULL = /null/ - IGNORE = %r( + )/x.freeze + NAN = /NaN/.freeze + INFINITY = /Infinity/.freeze + MINUS_INFINITY = /-Infinity/.freeze + OBJECT_OPEN = /\{/.freeze + OBJECT_CLOSE = /\}/.freeze + ARRAY_OPEN = /\[/.freeze + ARRAY_CLOSE = /\]/.freeze + PAIR_DELIMITER = /:/.freeze + COLLECTION_DELIMITER = /,/.freeze + TRUE = /true/.freeze + FALSE = /false/.freeze + NULL = /null/.freeze + IGNORE = %r{ (?: //[^\n\r]*[\n\r]| # line comments /\* # c-style comments (?: [^*/]| # normal chars /[^*]| # slashes that do not start a nested comment \*[^/]| # asterisks that do not end this comment /(?=\*/) # single slash before this comment's end )* \*/ # the End of this comment |[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr )+ - )mx + }mx.freeze UNPARSED = Object.new # Creates a new JSON::Pure::Parser instance for the string _source_. # # It will be configured by the _opts_ hash. _opts_ can have the following # keys: # * *max_nesting*: The maximum depth of nesting allowed in the parsed data # structures. Disable depth checking with :max_nesting => false|nil|0, # it defaults to 19. # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in # defiance of RFC 4627 to be parsed by the Parser. This option defaults # to false. # * *symbolize_names*: If set to true, returns symbols for the names # (keys) in a JSON object. Otherwise strings are returned, which is also # the default. # * *create_additions*: If set to false, the Parser doesn't create # additions even if a matchin class and create_id was found. This option # defaults to true. # * *object_class*: Defaults to Hash # * *array_class*: Defaults to Array # * *quirks_mode*: Enables quirks_mode for parser, that is for example # parsing single JSON values instead of documents is possible. - def initialize(source, opts = {}) + def initialize(source, opts={}) opts ||= {} - unless @quirks_mode = opts[:quirks_mode] - source = convert_encoding source - end + source = convert_encoding source unless @quirks_mode = opts[:quirks_mode] super source - if !opts.key?(:max_nesting) # defaults to 19 - @max_nesting = 19 - elsif opts[:max_nesting] - @max_nesting = opts[:max_nesting] - else - @max_nesting = 0 - end - @allow_nan = !!opts[:allow_nan] - @symbolize_names = !!opts[:symbolize_names] - if opts.key?(:create_additions) - @create_additions = !!opts[:create_additions] - else - @create_additions = true - end + @max_nesting = if !opts.key?(:max_nesting) # defaults to 19 + 19 + elsif opts[:max_nesting] + opts[:max_nesting] + else + 0 + end + @allow_nan = !opts[:allow_nan].nil? + @symbolize_names = !opts[:symbolize_names].nil? + @create_additions = if opts.key?(:create_additions) + !opts[:create_additions].nil? + else + true + end @create_id = @create_additions ? JSON.create_id : nil @object_class = opts[:object_class] || Hash @array_class = opts[:array_class] || Array @match_string = opts[:match_string] end alias source string def quirks_mode? !!@quirks_mode end def reset super @current_nesting = 0 end # Parses the current JSON string _source_ and returns the complete data # structure as a result. def parse reset obj = nil if @quirks_mode while !eos? && skip(IGNORE) end if eos? - raise ParserError, "source did not contain any JSON!" + raise ParserError, 'source did not contain any JSON!' else obj = parse_value - obj == UNPARSED and raise ParserError, "source did not contain any JSON!" + obj == UNPARSED and raise ParserError, 'source did not contain any JSON!' end else until eos? - case - when scan(OBJECT_OPEN) + if scan(OBJECT_OPEN) obj and raise ParserError, "source '#{peek(20)}' not in JSON!" @current_nesting = 1 obj = parse_object - when scan(ARRAY_OPEN) + elsif scan(ARRAY_OPEN) obj and raise ParserError, "source '#{peek(20)}' not in JSON!" @current_nesting = 1 obj = parse_array - when skip(IGNORE) - ; + elsif skip(IGNORE) + else raise ParserError, "source '#{peek(20)}' not in JSON!" end end - obj or raise ParserError, "source did not contain any JSON!" + obj or raise ParserError, 'source did not contain any JSON!' end obj end private def convert_encoding(source) if source.respond_to?(:to_str) source = source.to_str else raise TypeError, "#{source.inspect} is not like a string" end if defined?(::Encoding) if source.encoding == ::Encoding::ASCII_8BIT b = source[0, 4].bytes.to_a source = - case - when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 + if b.size >= 4 && (b[0]).zero? && (b[1]).zero? && (b[2]).zero? source.dup.force_encoding(::Encoding::UTF_32BE).encode!(::Encoding::UTF_8) - when b.size >= 4 && b[0] == 0 && b[2] == 0 + elsif b.size >= 4 && (b[0]).zero? && (b[2]).zero? source.dup.force_encoding(::Encoding::UTF_16BE).encode!(::Encoding::UTF_8) - when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0 + elsif b.size >= 4 && (b[1]).zero? && (b[2]).zero? && (b[3]).zero? source.dup.force_encoding(::Encoding::UTF_32LE).encode!(::Encoding::UTF_8) - when b.size >= 4 && b[1] == 0 && b[3] == 0 + elsif b.size >= 4 && (b[1]).zero? && (b[3]).zero? source.dup.force_encoding(::Encoding::UTF_16LE).encode!(::Encoding::UTF_8) else source.dup end else source = source.encode(::Encoding::UTF_8) end source.force_encoding(::Encoding::ASCII_8BIT) else b = source source = - case - when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 + if b.size >= 4 && (b[0]).zero? && (b[1]).zero? && (b[2]).zero? JSON.iconv('utf-8', 'utf-32be', b) - when b.size >= 4 && b[0] == 0 && b[2] == 0 + elsif b.size >= 4 && (b[0]).zero? && (b[2]).zero? JSON.iconv('utf-8', 'utf-16be', b) - when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0 + elsif b.size >= 4 && (b[1]).zero? && (b[2]).zero? && (b[3]).zero? JSON.iconv('utf-8', 'utf-32le', b) - when b.size >= 4 && b[1] == 0 && b[3] == 0 + elsif b.size >= 4 && (b[1]).zero? && (b[3]).zero? JSON.iconv('utf-8', 'utf-16le', b) else b end end source end # Unescape characters in strings. UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr } UNESCAPE_MAP.update({ - ?" => '"', - ?\\ => '\\', - ?/ => '/', - ?b => "\b", - ?f => "\f", - ?n => "\n", - ?r => "\r", - ?t => "\t", - ?u => nil, - }) + '"' => '"', + '\\' => '\\', + '/' => '/', + 'b' => "\b", + 'f' => "\f", + 'n' => "\n", + 'r' => "\r", + 't' => "\t", + 'u' => nil + }) EMPTY_8BIT_STRING = '' - if ::String.method_defined?(:encode) - EMPTY_8BIT_STRING.force_encoding Encoding::ASCII_8BIT - end + EMPTY_8BIT_STRING.force_encoding Encoding::ASCII_8BIT if ::String.method_defined?(:encode) def parse_string if scan(STRING) return '' if self[1].empty? + string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c| - if u = UNESCAPE_MAP[$&[1]] + if u = UNESCAPE_MAP[Regexp.last_match(0)[1]] u else # \uXXXX bytes = EMPTY_8BIT_STRING.dup i = 0 - while c[6 * i] == ?\\ && c[6 * i + 1] == ?u - bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16) + while c[6 * i] == '\\' && c[(6 * i) + 1] == 'u' + bytes << c[(6 * i) + 2, 2].to_i(16) << c[(6 * i) + 4, 2].to_i(16) i += 1 end JSON.iconv('utf-8', 'utf-16be', bytes) end end - if string.respond_to?(:force_encoding) - string.force_encoding(::Encoding::UTF_8) - end - if @create_additions and @match_string - for (regexp, klass) in @match_string + string.force_encoding(::Encoding::UTF_8) if string.respond_to?(:force_encoding) + if @create_additions && @match_string + @match_string.each do |(regexp, klass)| klass.json_creatable? or next string =~ regexp and return klass.json_create(string) end end string else UNPARSED end rescue => e raise ParserError, "Caught #{e.class} at '#{peek(20)}': #{e}" end def parse_value - case - when scan(FLOAT) + if scan(FLOAT) Float(self[1]) - when scan(INTEGER) + elsif scan(INTEGER) Integer(self[1]) - when scan(TRUE) + elsif scan(true) true - when scan(FALSE) + elsif scan(false) false - when scan(NULL) + elsif scan(NULL) nil - when (string = parse_string) != UNPARSED + elsif (string = parse_string) != UNPARSED string - when scan(ARRAY_OPEN) + elsif scan(ARRAY_OPEN) @current_nesting += 1 ary = parse_array @current_nesting -= 1 ary - when scan(OBJECT_OPEN) + elsif scan(OBJECT_OPEN) @current_nesting += 1 obj = parse_object @current_nesting -= 1 obj - when @allow_nan && scan(NAN) + elsif @allow_nan && scan(NAN) NaN - when @allow_nan && scan(INFINITY) + elsif @allow_nan && scan(INFINITY) Infinity - when @allow_nan && scan(MINUS_INFINITY) + elsif @allow_nan && scan(MINUS_INFINITY) MinusInfinity else UNPARSED end end def parse_array - raise NestingError, "nesting of #@current_nesting is too deep" if + raise NestingError, "nesting of #{@current_nesting} is too deep" if @max_nesting.nonzero? && @current_nesting > @max_nesting + result = @array_class.new delim = false until eos? - case - when (value = parse_value) != UNPARSED + if (value = parse_value) != UNPARSED delim = false result << value skip(IGNORE) if scan(COLLECTION_DELIMITER) delim = true elsif match?(ARRAY_CLOSE) - ; + else raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!" end - when scan(ARRAY_CLOSE) - if delim - raise ParserError, "expected next element in array at '#{peek(20)}'!" - end + elsif scan(ARRAY_CLOSE) + raise ParserError, "expected next element in array at '#{peek(20)}'!" if delim + break - when skip(IGNORE) - ; + elsif skip(IGNORE) + else raise ParserError, "unexpected token in array at '#{peek(20)}'!" end end result end def parse_object - raise NestingError, "nesting of #@current_nesting is too deep" if + raise NestingError, "nesting of #{@current_nesting} is too deep" if @max_nesting.nonzero? && @current_nesting > @max_nesting + result = @object_class.new delim = false until eos? - case - when (string = parse_string) != UNPARSED + if (string = parse_string) != UNPARSED skip(IGNORE) - unless scan(PAIR_DELIMITER) - raise ParserError, "expected ':' in object at '#{peek(20)}'!" - end + raise ParserError, "expected ':' in object at '#{peek(20)}'!" unless scan(PAIR_DELIMITER) + skip(IGNORE) - unless (value = parse_value).equal? UNPARSED + if (value = parse_value).equal? UNPARSED + raise ParserError, "expected value in object at '#{peek(20)}'!" + else result[@symbolize_names ? string.to_sym : string] = value delim = false skip(IGNORE) if scan(COLLECTION_DELIMITER) delim = true elsif match?(OBJECT_CLOSE) - ; + else raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!" end - else - raise ParserError, "expected value in object at '#{peek(20)}'!" - end - when scan(OBJECT_CLOSE) - if delim - raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!" end - if @create_additions and klassname = result[@create_id] + elsif scan(OBJECT_CLOSE) + raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!" if delim + + if @create_additions && (klassname = result[@create_id]) klass = JSON.deep_const_get klassname - break unless klass and klass.json_creatable? + break unless klass && klass.json_creatable? + result = klass.json_create(result) end break - when skip(IGNORE) - ; + elsif skip(IGNORE) + else raise ParserError, "unexpected token in object at '#{peek(20)}'!" end end result end end end end module JSON MAP = { "\x0" => '\u0000', "\x1" => '\u0001', "\x2" => '\u0002', "\x3" => '\u0003', "\x4" => '\u0004', "\x5" => '\u0005', "\x6" => '\u0006', "\x7" => '\u0007', - "\b" => '\b', - "\t" => '\t', - "\n" => '\n', + "\b" => '\b', + "\t" => '\t', + "\n" => '\n', "\xb" => '\u000b', - "\f" => '\f', - "\r" => '\r', + "\f" => '\f', + "\r" => '\r', "\xe" => '\u000e', "\xf" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016', "\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', "\x1a" => '\u001a', "\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', "\x1e" => '\u001e', "\x1f" => '\u001f', - '"' => '\"', - '\\' => '\\\\', - } # :nodoc: + '"' => '\"', + '\\' => '\\\\' + }.freeze # :nodoc: # Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with # UTF16 big endian characters as \u????, and return it. if defined?(::Encoding) def utf8_to_json(string) # :nodoc: string = string.dup string << '' # XXX workaround: avoid buffer sharing string.force_encoding(::Encoding::ASCII_8BIT) - string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] } + string.gsub!(/["\\\x0-\x1f]/) { MAP[Regexp.last_match(0)] } string.force_encoding(::Encoding::UTF_8) string end def utf8_to_json_ascii(string) # :nodoc: string = string.dup string << '' # XXX workaround: avoid buffer sharing string.force_encoding(::Encoding::ASCII_8BIT) - string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] } + string.gsub!(/["\\\x0-\x1f]/) { MAP[Regexp.last_match(0)] } string.gsub!(/( (?: [\xc2-\xdf][\x80-\xbf] | [\xe0-\xef][\x80-\xbf]{2} | [\xf0-\xf4][\x80-\xbf]{3} )+ | [\x80-\xc1\xf5-\xff] # invalid - )/nx) { |c| + )/nx) do |c| c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'" - s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0] + s = JSON.iconv('utf-16be', 'utf-8', c).unpack1('H*') s.gsub!(/.{4}/n, '\\\\u\&') - } + end string.force_encoding(::Encoding::UTF_8) string rescue => e raise GeneratorError, "Caught #{e.class}: #{e}" end else def utf8_to_json(string) # :nodoc: - string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } + string.gsub(/["\\\x0-\x1f]/) { MAP[Regexp.last_match(0)] } end def utf8_to_json_ascii(string) # :nodoc: - string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } + string = string.gsub(/["\\\x0-\x1f]/) { MAP[Regexp.last_match(0)] } string.gsub!(/( (?: [\xc2-\xdf][\x80-\xbf] | [\xe0-\xef][\x80-\xbf]{2} | [\xf0-\xf4][\x80-\xbf]{3} )+ | [\x80-\xc1\xf5-\xff] # invalid - )/nx) { |c| + )/nx) do |c| c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'" - s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0] + s = JSON.iconv('utf-16be', 'utf-8', c).unpack1('H*') s.gsub!(/.{4}/n, '\\\\u\&') - } + end string rescue => e raise GeneratorError, "Caught #{e.class}: #{e}" end end module_function :utf8_to_json, :utf8_to_json_ascii module Pure module Generator # This class is used to create State instances, that are use to hold data # while generating a JSON text from a Ruby data structure. class State # Creates a State object from _opts_, which ought to be Hash to create # a new State instance configured by _opts_, something else to create # an unconfigured instance. If _opts_ is a State object, it is just # returned. def self.from_state(opts) - case - when self === opts + if self === opts opts - when opts.respond_to?(:to_hash) + elsif opts.respond_to?(:to_hash) new(opts.to_hash) - when opts.respond_to?(:to_h) + elsif opts.respond_to?(:to_h) new(opts.to_h) else SAFE_STATE_PROTOTYPE.dup end end # Instantiates a new State object, configured by _opts_. # # _opts_ can have the following keys: # # * *indent*: a string used to indent levels (default: ''), # * *space*: a string that is put after, a : or , delimiter (default: ''), # * *space_before*: a string that is put before a : pair delimiter (default: ''), # * *object_nl*: a string that is put at the end of a JSON object (default: ''), # * *array_nl*: a string that is put at the end of a JSON array (default: ''), # * *check_circular*: is deprecated now, use the :max_nesting option instead, # * *max_nesting*: sets the maximum level of data structure nesting in # the generated JSON, max_nesting = 0 if no maximum should be checked. # * *allow_nan*: true if NaN, Infinity, and -Infinity should be # generated, otherwise an exception is thrown, if these values are # encountered. This options defaults to false. # * *quirks_mode*: Enables quirks_mode for parser, that is for example # generating single JSON values instead of documents is possible. - def initialize(opts = {}) + def initialize(opts={}) @indent = '' @space = '' @space_before = '' @object_nl = '' @array_nl = '' @allow_nan = false @ascii_only = false @quirks_mode = false @buffer_initial_length = 1024 configure opts end # This string is used to indent levels in the JSON text. attr_accessor :indent # This string is used to insert a space between the tokens in a JSON # string. attr_accessor :space # This string is used to insert a space before the ':' in JSON objects. attr_accessor :space_before # This string is put at the end of a line that holds a JSON object (or # Hash). attr_accessor :object_nl # This string is put at the end of a line that holds a JSON array. attr_accessor :array_nl # This integer returns the maximum level of data structure nesting in # the generated JSON, max_nesting = 0 if no maximum is checked. attr_accessor :max_nesting # If this attribute is set to true, quirks mode is enabled, otherwise # it's disabled. attr_accessor :quirks_mode # :stopdoc: attr_reader :buffer_initial_length def buffer_initial_length=(length) - if length > 0 - @buffer_initial_length = length - end + @buffer_initial_length = length if length.positive? end # :startdoc: # This integer returns the current depth data structure nesting in the # generated JSON. attr_accessor :depth def check_max_nesting # :nodoc: return if @max_nesting.zero? + current_nesting = depth + 1 current_nesting > @max_nesting and raise NestingError, "nesting of #{current_nesting} is too deep" end # Returns true, if circular data structures are checked, # otherwise returns false. def check_circular? !@max_nesting.zero? end # Returns true if NaN, Infinity, and -Infinity should be considered as # valid JSON and output. def allow_nan? @allow_nan end # Returns true, if only ASCII characters should be generated. Otherwise # returns false. def ascii_only? @ascii_only end # Returns true, if quirks mode is enabled. Otherwise returns false. def quirks_mode? @quirks_mode end # Configure this State instance with the Hash _opts_, and return # itself. def configure(opts) @indent = opts[:indent] if opts.key?(:indent) @space = opts[:space] if opts.key?(:space) @space_before = opts[:space_before] if opts.key?(:space_before) @object_nl = opts[:object_nl] if opts.key?(:object_nl) @array_nl = opts[:array_nl] if opts.key?(:array_nl) - @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan) + @allow_nan = !opts[:allow_nan].nil? if opts.key?(:allow_nan) @ascii_only = opts[:ascii_only] if opts.key?(:ascii_only) @depth = opts[:depth] || 0 @quirks_mode = opts[:quirks_mode] if opts.key?(:quirks_mode) - if !opts.key?(:max_nesting) # defaults to 19 - @max_nesting = 19 - elsif opts[:max_nesting] - @max_nesting = opts[:max_nesting] - else - @max_nesting = 0 - end + @max_nesting = if !opts.key?(:max_nesting) # defaults to 19 + 19 + elsif opts[:max_nesting] + opts[:max_nesting] + else + 0 + end self end alias merge configure # Returns the configuration instance variables as a hash, that can be # passed to the configure method. def to_h result = {} - for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only quirks_mode buffer_initial_length depth] + %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only quirks_mode + buffer_initial_length depth].each do |iv| result[iv.intern] = instance_variable_get("@#{iv}") end result end # Generates a valid JSON document from object +obj+ and returns the # result. If no valid JSON document can be created this method raises a # GeneratorError exception. def generate(obj) result = obj.to_json(self) - unless @quirks_mode - unless result =~ /\A\s*\[/ && result =~ /\]\s*\Z/ || - result =~ /\A\s*\{/ && result =~ /\}\s*\Z/ - then - raise GeneratorError, "only generation of JSON objects or arrays allowed" - end + if !@quirks_mode && !((result =~ /\A\s*\[/ && result =~ /\]\s*\Z/) || + (result =~ /\A\s*\{/ && result =~ /\}\s*\Z/)) + raise GeneratorError, 'only generation of JSON objects or arrays allowed' end + result end # Return the value returned by method +name+. def [](name) __send__ name end end module GeneratorMethods module Object # Converts this object to a string (calling #to_s), converts # it to a JSON string, and returns the result. This is a fallback, if no # special method #to_json was defined for some object. - def to_json(*) to_s.to_json end + def to_json(*) + to_s.to_json + end end module Hash # Returns a JSON string containing a JSON object, that is unparsed from # this Hash instance. # _state_ is a JSON::State object, that can also be used to configure the # produced JSON string output further. # _depth_ is used to find out nesting depth, to indent accordingly. - def to_json(state = nil, *) + def to_json(state=nil, *) state = State.from_state(state) state.check_max_nesting json_transform(state) end private def json_shift(state) state.object_nl.empty? or return '' state.indent * state.depth end def json_transform(state) delim = ',' delim << state.object_nl result = '{' result << state.object_nl depth = state.depth += 1 first = true indent = !state.object_nl.empty? - each { |key,value| + each do |key, value| result << delim unless first - result << state.indent * depth if indent + result << (state.indent * depth) if indent result << key.to_s.to_json(state) result << state.space_before result << ':' result << state.space result << value.to_json(state) first = false - } + end depth = state.depth -= 1 result << state.object_nl - result << state.indent * depth if indent if indent + result << (state.indent * depth) if indent && indent result << '}' result end end module Array # Returns a JSON string containing a JSON array, that is unparsed from # this Array instance. # _state_ is a JSON::State object, that can also be used to configure the # produced JSON string output further. - def to_json(state = nil, *) + def to_json(state=nil, *) state = State.from_state(state) state.check_max_nesting json_transform(state) end private def json_transform(state) delim = ',' delim << state.array_nl result = '[' result << state.array_nl depth = state.depth += 1 first = true indent = !state.array_nl.empty? - each { |value| + each do |value| result << delim unless first - result << state.indent * depth if indent + result << (state.indent * depth) if indent result << value.to_json(state) first = false - } + end depth = state.depth -= 1 result << state.array_nl - result << state.indent * depth if indent + result << (state.indent * depth) if indent result << ']' end end module Integer # Returns a JSON string representation for this Integer number. - def to_json(*) to_s end + def to_json(*) + to_s + end end module Float # Returns a JSON string representation for this Float number. - def to_json(state = nil, *) + def to_json(state=nil, *) state = State.from_state(state) - case - when infinite? + if infinite? if state.allow_nan? to_s else raise GeneratorError, "#{self} not allowed in JSON" end - when nan? + elsif nan? if state.allow_nan? to_s else raise GeneratorError, "#{self} not allowed in JSON" end else to_s end end end module String if defined?(::Encoding) # This string should be encoded with UTF-8 A call to this method # returns a JSON string encoded with UTF16 big endian characters as # \u????. - def to_json(state = nil, *args) + def to_json(state=nil, *_args) state = State.from_state(state) - if encoding == ::Encoding::UTF_8 - string = self - else - string = encode(::Encoding::UTF_8) - end + string = if encoding == ::Encoding::UTF_8 + self + else + encode(::Encoding::UTF_8) + end if state.ascii_only? '"' << JSON.utf8_to_json_ascii(string) << '"' else '"' << JSON.utf8_to_json(string) << '"' end end else # This string should be encoded with UTF-8 A call to this method # returns a JSON string encoded with UTF16 big endian characters as # \u????. - def to_json(state = nil, *args) + def to_json(state=nil, *_args) state = State.from_state(state) if state.ascii_only? '"' << JSON.utf8_to_json_ascii(self) << '"' else '"' << JSON.utf8_to_json(self) << '"' end end end # Module that holds the extinding methods if, the String module is # included. module Extend # Raw Strings are JSON Objects (the raw bytes are stored in an # array for the key "raw"). The Ruby String can be created by this # module method. def json_create(o) o['raw'].pack('C*') end end # Extends _modul_ with the String::Extend module. def self.included(modul) modul.extend Extend end # This method creates a raw object hash, that can be nested into # other data structures and will be unparsed as a raw string. This # method should be used, if you want to convert raw strings to JSON # instead of UTF-8 strings, e. g. binary data. def to_json_raw_object { - JSON.create_id => self.class.name, - 'raw' => self.unpack('C*'), + JSON.create_id => self.class.name, + 'raw' => unpack('C*') } end # This method creates a JSON text from the result of # a call to to_json_raw_object of this String. def to_json_raw(*args) to_json_raw_object.to_json(*args) end end module TrueClass # Returns a JSON string for true: 'true'. - def to_json(*) 'true' end + def to_json(*) + 'true' + end end module FalseClass # Returns a JSON string for false: 'false'. - def to_json(*) 'false' end + def to_json(*) + 'false' + end end module NilClass # Returns a JSON string for nil: 'null'. - def to_json(*) 'null' end + def to_json(*) + 'null' + end end end end end end module JSON class << self # If _object_ is string-like, parse the string and return the parsed result # as a Ruby data structure. Otherwise generate a JSON text from the Ruby # data structure object and return it. # # The _opts_ argument is passed through to generate/parse respectively. See # generate and parse for their documentation. - def [](object, opts = {}) + def [](object, opts={}) if object.respond_to? :to_str JSON.parse(object.to_str, opts) else JSON.generate(object, opts) end end # Returns the JSON parser class that is used by JSON. This is either # JSON::Ext::Parser or JSON::Pure::Parser. attr_reader :parser # Set the JSON parser class _parser_ to be used by JSON. def parser=(parser) # :nodoc: @parser = parser remove_const :Parser if JSON.const_defined_in?(self, :Parser) const_set :Parser, parser end # Return the constant located at _path_. The format of _path_ has to be # either ::A::B::C or A::B::C. In any case, A has to be located at the top # level (absolute namespace path?). If there doesn't exist a constant at # the given path, an ArgumentError is raised. def deep_const_get(path) # :nodoc: path.to_s.split(/::/).inject(Object) do |p, c| - case - when c.empty? then p - when JSON.const_defined_in?(p, c) then p.const_get(c) + if c.empty? + p + elsif JSON.const_defined_in?(p, c) + p.const_get(c) else begin p.const_missing(c) rescue NameError => e raise ArgumentError, "can't get const #{path}: #{e}" end end end end # Set the module _generator_ to be used by JSON. def generator=(generator) # :nodoc: - old, $VERBOSE = $VERBOSE, nil + old = $VERBOSE + $VERBOSE = nil @generator = generator generator_methods = generator::GeneratorMethods - for const in generator_methods.constants + generator_methods.constants.each do |const| klass = deep_const_get(const) modul = generator_methods.const_get(const) klass.class_eval do instance_methods(false).each do |m| m.to_s == 'to_json' and remove_method m end include modul end end self.state = generator::State - const_set :State, self.state + const_set :State, state const_set :SAFE_STATE_PROTOTYPE, State.new const_set :FAST_STATE_PROTOTYPE, State.new( - :indent => '', - :space => '', - :object_nl => "", - :array_nl => "", - :max_nesting => false + indent: '', + space: '', + object_nl: '', + array_nl: '', + max_nesting: false ) const_set :PRETTY_STATE_PROTOTYPE, State.new( - :indent => ' ', - :space => ' ', - :object_nl => "\n", - :array_nl => "\n" + indent: ' ', + space: ' ', + object_nl: "\n", + array_nl: "\n" ) ensure $VERBOSE = old end # Returns the JSON generator module that is used by JSON. This is # either JSON::Ext::Generator or JSON::Pure::Generator. attr_reader :generator # Returns the JSON generator state class that is used by JSON. This is # either JSON::Ext::Generator::State or JSON::Pure::Generator::State. attr_accessor :state # This is create identifier, which is used to decide if the _json_create_ # hook of a class should be called. It defaults to 'json_class'. attr_accessor :create_id end self.create_id = 'json_class' - NaN = 0.0/0 + NaN = 0.0 / 0 - Infinity = 1.0/0 + Infinity = 1.0 / 0 MinusInfinity = -Infinity # The base exception for JSON errors. class JSONError < StandardError; end # This exception is raised if a parser error occurs. class ParserError < JSONError; end # This exception is raised if the nesting of parsed data structures is too # deep. class NestingError < ParserError; end # :stopdoc: class CircularDatastructure < NestingError; end # :startdoc: # This exception is raised if a generator or unparser error occurs. class GeneratorError < JSONError; end # For backwards compatibility UnparserError = GeneratorError # This exception is raised if the required unicode support is missing on the # system. Usually this means that the iconv library is not installed. class MissingUnicodeSupport < JSONError; end module_function # Parse the JSON document _source_ into a Ruby data structure and return it. # # _opts_ can have the following # keys: # * *max_nesting*: The maximum depth of nesting allowed in the parsed data # structures. Disable depth checking with :max_nesting => false. It defaults # to 19. # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in # defiance of RFC 4627 to be parsed by the Parser. This option defaults # to false. # * *symbolize_names*: If set to true, returns symbols for the names # (keys) in a JSON object. Otherwise strings are returned. Strings are # the default. # * *create_additions*: If set to false, the Parser doesn't create # additions even if a matching class and create_id was found. This option # defaults to true. # * *object_class*: Defaults to Hash # * *array_class*: Defaults to Array - def parse(source, opts = {}) + def parse(source, opts={}) Parser.new(source, opts).parse end # Parse the JSON document _source_ into a Ruby data structure and return it. # The bang version of the parse method defaults to the more dangerous values # for the _opts_ hash, so be sure only to parse trusted _source_ documents. # # _opts_ can have the following keys: # * *max_nesting*: The maximum depth of nesting allowed in the parsed data # structures. Enable depth checking with :max_nesting => anInteger. The parse! # methods defaults to not doing max depth checking: This can be dangerous # if someone wants to fill up your stack. # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in # defiance of RFC 4627 to be parsed by the Parser. This option defaults # to true. # * *create_additions*: If set to false, the Parser doesn't create # additions even if a matching class and create_id was found. This option # defaults to true. - def parse!(source, opts = {}) + def parse!(source, opts={}) opts = { - :max_nesting => false, - :allow_nan => true + max_nesting: false, + allow_nan: true }.update(opts) Parser.new(source, opts).parse end # Generate a JSON document from the Ruby data structure _obj_ and return # it. _state_ is * a JSON::State object, # * or a Hash like object (responding to to_hash), # * an object convertible into a hash by a to_h method, # that is used as or to configure a State object. # # It defaults to a state object, that creates the shortest possible JSON text # in one line, checks for circular data structures and doesn't allow NaN, # Infinity, and -Infinity. # # A _state_ hash can have the following keys: # * *indent*: a string used to indent levels (default: ''), # * *space*: a string that is put after, a : or , delimiter (default: ''), # * *space_before*: a string that is put before a : pair delimiter (default: ''), # * *object_nl*: a string that is put at the end of a JSON object (default: ''), # * *array_nl*: a string that is put at the end of a JSON array (default: ''), # * *allow_nan*: true if NaN, Infinity, and -Infinity should be # generated, otherwise an exception is thrown if these values are # encountered. This options defaults to false. # * *max_nesting*: The maximum depth of nesting allowed in the data # structures from which JSON is to be generated. Disable depth checking # with :max_nesting => false, it defaults to 19. # # See also the fast_generate for the fastest creation method with the least # amount of sanity checks, and the pretty_generate method for some # defaults for pretty output. - def generate(obj, opts = nil) - if State === opts - state, opts = opts, nil + def generate(obj, opts=nil) + if opts.is_a?(State) + state = opts + opts = nil else state = SAFE_STATE_PROTOTYPE.dup end if opts if opts.respond_to? :to_hash opts = opts.to_hash elsif opts.respond_to? :to_h opts = opts.to_h else raise TypeError, "can't convert #{opts.class} into Hash" end state = state.configure(opts) end state.generate(obj) end # :stopdoc: # I want to deprecate these later, so I'll first be silent about them, and # later delete them. alias unparse generate module_function :unparse # :startdoc: # Generate a JSON document from the Ruby data structure _obj_ and return it. # This method disables the checks for circles in Ruby objects. # # *WARNING*: Be careful not to pass any Ruby data structures with circles as # _obj_ argument because this will cause JSON to go into an infinite loop. - def fast_generate(obj, opts = nil) - if State === opts - state, opts = opts, nil + def fast_generate(obj, opts=nil) + if opts.is_a?(State) + state = opts + opts = nil else state = FAST_STATE_PROTOTYPE.dup end if opts if opts.respond_to? :to_hash opts = opts.to_hash elsif opts.respond_to? :to_h opts = opts.to_h else raise TypeError, "can't convert #{opts.class} into Hash" end state.configure(opts) end state.generate(obj) end # :stopdoc: # I want to deprecate these later, so I'll first be silent about them, and later delete them. alias fast_unparse fast_generate module_function :fast_unparse # :startdoc: # Generate a JSON document from the Ruby data structure _obj_ and return it. # The returned document is a prettier form of the document returned by # #unparse. # # The _opts_ argument can be used to configure the generator. See the # generate method for a more detailed explanation. - def pretty_generate(obj, opts = nil) - if State === opts - state, opts = opts, nil + def pretty_generate(obj, opts=nil) + if opts.is_a?(State) + state = opts + opts = nil else state = PRETTY_STATE_PROTOTYPE.dup end if opts if opts.respond_to? :to_hash opts = opts.to_hash elsif opts.respond_to? :to_h opts = opts.to_h else raise TypeError, "can't convert #{opts.class} into Hash" end state.configure(opts) end state.generate(obj) end # :stopdoc: # I want to deprecate these later, so I'll first be silent about them, and later delete them. alias pretty_unparse pretty_generate module_function :pretty_unparse # :startdoc: class << self # The global default options for the JSON.load method: # :max_nesting: false # :allow_nan: true # :quirks_mode: true attr_accessor :load_default_options end self.load_default_options = { - :max_nesting => false, - :allow_nan => true, - :quirks_mode => true, + max_nesting: false, + allow_nan: true, + quirks_mode: true } # Load a ruby data structure from a JSON _source_ and return it. A source can # either be a string-like object, an IO-like object, or an object responding # to the read method. If _proc_ was given, it will be called with any nested # Ruby object as an argument recursively in depth first order. The default # options for the parser can be changed via the load_default_options method. # # This method is part of the implementation of the load/dump interface of # Marshal and YAML. - def load(source, proc = nil) + def load(source, proc=nil) opts = load_default_options if source.respond_to? :to_str source = source.to_str elsif source.respond_to? :to_io source = source.to_io.read elsif source.respond_to?(:read) source = source.read end - if opts[:quirks_mode] && (source.nil? || source.empty?) - source = 'null' - end + source = 'null' if opts[:quirks_mode] && (source.nil? || source.empty?) result = parse(source, opts) recurse_proc(result, &proc) if proc result end # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_ def recurse_proc(result, &proc) case result when Array result.each { |x| recurse_proc x, &proc } - proc.call result when Hash - result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc } - proc.call result - else - proc.call result + result.each do |x, y| + recurse_proc x, &proc + recurse_proc y, &proc + end end + proc.call result end alias restore load module_function :restore class << self # The global default options for the JSON.dump method: # :max_nesting: false # :allow_nan: true # :quirks_mode: true attr_accessor :dump_default_options end self.dump_default_options = { - :max_nesting => false, - :allow_nan => true, - :quirks_mode => true, + max_nesting: false, + allow_nan: true, + quirks_mode: true } # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns # the result. # # If anIO (an IO-like object or an object that responds to the write method) # was given, the resulting JSON is written to it. # # If the number of nested arrays or objects exceeds _limit_, an ArgumentError # exception is raised. This argument is similar (but not exactly the # same!) to the _limit_ argument in Marshal.dump. # # The default options for the generator can be changed via the # dump_default_options method. # # This method is part of the implementation of the load/dump interface of # Marshal and YAML. - def dump(obj, anIO = nil, limit = nil) - if anIO and limit.nil? + def dump(obj, anIO=nil, limit=nil) + if anIO && limit.nil? anIO = anIO.to_io if anIO.respond_to?(:to_io) unless anIO.respond_to?(:write) limit = anIO anIO = nil end end opts = JSON.dump_default_options - limit and opts.update(:max_nesting => limit) + limit and opts.update(max_nesting: limit) result = generate(obj, opts) if anIO anIO.write result anIO else result end rescue JSON::NestingError - raise ArgumentError, "exceed depth limit" + raise ArgumentError, 'exceed depth limit' end # Swap consecutive bytes of _string_ in place. def self.swap!(string) # :nodoc: 0.upto(string.size / 2) do |i| - break unless string[2 * i + 1] - string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i] + break unless string[(2 * i) + 1] + + string[2 * i], string[(2 * i) + 1] = string[(2 * i) + 1], string[2 * i] end string end # Shortuct for iconv. if ::String.method_defined?(:encode) # Encodes string using Ruby's _String.encode_ def self.iconv(to, from, string) string.encode(to, from) end else require 'iconv' # Encodes string using _iconv_ library def self.iconv(to, from, string) Iconv.conv(to, from, string) end end if ::Object.method(:const_defined?).arity == 1 def self.const_defined_in?(modul, constant) modul.const_defined?(constant) end else def self.const_defined_in?(modul, constant) modul.const_defined?(constant, false) end end end module ::Kernel private # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in # one line. def j(*objs) objs.each do |obj| - puts JSON::generate(obj, :allow_nan => true, :max_nesting => false) + puts JSON.generate(obj, allow_nan: true, max_nesting: false) end nil end # Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with # indentation and over many lines. def jj(*objs) objs.each do |obj| - puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false) + puts JSON.pretty_generate(obj, allow_nan: true, max_nesting: false) end nil end # If _object_ is string-like, parse the string and return the parsed result as # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data # structure object and return it. # # The _opts_ argument is passed through to generate/parse respectively. See # generate and parse for their documentation. def JSON(object, *args) if object.respond_to? :to_str JSON.parse(object.to_str, args.first) else JSON.generate(object, args.first) end end end # Extends any Class to include _json_creatable?_ method. class ::Class # Returns true if this class can be used to create an instance # from a serialised JSON string. The class has to implement a class # method _json_create_ that expects a hash as first parameter. The hash # should include the required data. def json_creatable? respond_to?(:json_create) end end JSON.generator = JSON::Pure::Generator JSON.parser = JSON::Pure::Parser diff --git a/rakefile b/rakefile index a20ac6a..67f013d 100644 --- a/rakefile +++ b/rakefile @@ -1,3 +1,3 @@ # frozen_string_literal: true -import 'ruby/tasks.rake' \ No newline at end of file +import 'ruby/tasks.rake' diff --git a/ruby/tasks.rake b/ruby/tasks.rake index f601661..ac859c4 100644 --- a/ruby/tasks.rake +++ b/ruby/tasks.rake @@ -1,709 +1,707 @@ # frozen_string_literal: true require 'date' require 'pp' require 'colored2' ################################################################################################ # constants ROOT_DIR = File.expand_path('.') FINDER_DIR = '/System/Library/CoreServices/Finder.app' FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')].freeze TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') ################################################################################################ # helpers # this is here just IntelliJ to understand colors class String def self.blue Colored2.blue(self) end def self.red Colored2.red(self) end def self.yellow Colored2.yellow(self) end def self.green Colored2.green(self) end def self.cyan Colored2.cyan(self) end def self.magenta Colored2.magenta(self) end def self.bold Colored2.bold(self) end def self.underline Colored2.underline(self) end end def die(msg, status=1) puts red("Error[#{status || $CHILD_STATUS}]: #{msg}").red exit status || $CHILD_STATUS end def sys(cmd) puts "> #{cmd}".yellow system(cmd) end ################################################################################################ # routines def write_file(filename, content) if ENV['dry'] puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" return end - File.open(filename, 'w') do |f| - f.write content - end + File.write(filename, content) end def append_file(filename, content) if ENV['dry'] puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" return end File.open(filename, 'a') do |f| f.write content end end def get_list_of_plugins(filter=nil) filter ||= '*' plugins = [] Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| if File.directory?(file) && File.exist?(File.join(file, "#{File.basename(file)}.xcodeproj")) plugins << File.basename(file) end end plugins.uniq end def ack(dir, glob, regexps) glob = File.join(dir, '**{,/*/**}', glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) set = [] Dir.glob(glob) do |file| puts file if ENV['verbose'] content = File.read(file) regexps.each do |r| match = content.scan(r) set.concat match.flatten end end set.sort.uniq end def stitch_broken_strings(strings) strings.map do |s| r = /([^\\])(".*?")/m s.gsub(r) do |_x| Regexp.last_match(1) end end end def extract_menu_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,h}', [ /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_code_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,m,h}', [ /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,)]/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_ui_strings(folder, xibs) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| xibs.each do |xib| result.concat ack(dir, "#{xib}.xib", [ /"\^(.*?[^\\])"/m ]) end end result.sort.uniq end def parse_strings_file(filename) return [] unless File.exist? filename File.read(filename).lines end def update_strings(old_strings, new_keys, target) removed_count = 0 count = 0 # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings known_keys = [] strings = old_strings.map do |line| match = line =~ /^"(.*?)"/ # it is a valid key-definition line? next line unless match count += 1 if new_keys.include? Regexp.last_match(1) if known_keys.include? Regexp.last_match(1) line = "/* DUPLICIT #{line.strip} */\n" # *** removed_count += 1 else known_keys << Regexp.last_match(1) end else line = "/* REMOVED #{line.strip} */\n" # *** removed_count += 1 end line end to_be_added = new_keys - known_keys - write_file(target, strings.join('')) + write_file(target, strings.join) { 'removed_count' => removed_count, 'count' => count, 'new_strings' => new_keys, 'old_strings' => old_strings, 'output' => strings, 'to_be_added' => to_be_added.sort.uniq } end def update_english_strings(project, src_folder, xibs, additional_strings=[]) target = File.join(ENGLISH_LPROJ, "#{project}.strings") code_strings = extract_code_strings(src_folder) ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) new_strings = code_strings.concat(ui_strings).concat(additional_strings) new_strings.sort.uniq! old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) xibs = {} # xib naming exceptions that don't follow conventions unconventional = { 'SomeXibName' => 'SomePluginName' } Dir.glob(File.join(dir, '*.xib')) do |file| name = File.basename(file, '.xib') # does the name begin with some plugin name? plugin = plugins.find { |item| item == name || name.start_with?(item) } plugin = unconventional['name'] if plugin.nil? && unconventional['name'] unless plugin.nil? xibs[plugin] ||= [] xibs[plugin] << name next end xibs['SHELL'] ||= [] xibs['SHELL'] << name end xibs end def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) additions = {} plugins.each do |plugin| plugin_dir = File.join(dir, plugin) next unless File.exist? plugin_dir next if xibs[plugin].nil? || xibs[plugin].empty? # an edge case for empty array additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])['to_be_added'] # process just plugin xibs end additions end def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) update_english_strings('TotalFinder', shell_dir, xibs, duplicates) # process just shell xibs end def get_additions_duplicates(additions) all = [] additions.each do |_k, v| all.concat v end # count occurrences and return only duplicities all.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys.sort.uniq end def insert_additions(list, target) return if list.empty? strings = [] strings << "\n" strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" list.each do |key| value = key.gsub('MenuItem:', '') # MenuItems special case strings << "\"#{key}\" = \"#{value}\";" end append_file(target, strings.join("\n")) puts " #{"+#{list.size}".yellow} in #{target}" end def inprint_strings(source, dest, shared_originals=[]) strings = parse_strings_file(source) originals = [] originals.concat shared_originals originals.concat parse_strings_file(dest) # transform lang back to english index = 0 strings.map! do |line| index += 1 next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) line = "#{Regexp.last_match(1)} = #{Regexp.last_match(1)};\n" line end # replace translations we already know from previous version index = 0 originals.each do |original| index += 1 next unless original.strip[0...1] == '"' original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) rest = Regexp.last_match(3) die "syntax error in #{dest.blue}:#{index} [#{original}]" unless Regexp.last_match(1) && Regexp.last_match(2) strings.map! do |line| line = "#{needle} = #{haystack};#{rest}\n" if line.start_with?(needle) line end end - write_file(dest, strings.join('')) + write_file(dest, strings.join) strings end def find_key(key, lines) lines.each do |line| next unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) die "syntax error in [#{line}]" unless Regexp.last_match(1) && Regexp.last_match(2) return haystack if needle == key end nil end def post_process_menu(dest, shared_originals=[]) strings = parse_strings_file(dest) strings.map! do |line| next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) key = Regexp.last_match(1) val = Regexp.last_match(2) rest = Regexp.last_match(3) if key == val # try to lookup existing val translated_val = find_key(key.gsub('MenuItem:', ''), shared_originals) line = "#{key} = #{translated_val};#{rest}\n" unless translated_val.nil? end line end File.open(dest, 'w') do |f| f << strings.join end strings end def propagate_english_to_cwd total = 0 # TotalFinder.strings are master files, some strings may move between files all = parse_strings_file File.join(Dir.pwd, 'TotalFinder.strings') Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| puts " #{File.basename(file)}".yellow total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size end puts " -> #{total.to_s.green} strings processed" end def remove_missing_files_in_cwd files1 = Dir.glob(File.join(ENGLISH_LPROJ, '*')).map { |f| File.basename f } files2 = Dir.glob(File.join(Dir.pwd, '*')).map { |f| File.basename f } to_be_deleted = files2 - files1 to_be_deleted.each do |file| puts "deleting '#{file}'".red FileUtils.rm(file) end end def propagate_from_english_to_other_lprojs glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do puts dir.blue propagate_english_to_cwd remove_missing_files_in_cwd end end end def create_localizations_for_project glob = ENV['to'] || '*.lproj' project = ENV['project'] || die('Project name not defined') Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do write_file(File.join(dir, "#{project}.strings"), '/* no strings */') end end end def exec_cmd_in_lprojs(cmd) glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| puts dir.blue Dir.chdir dir do sys(cmd) end end end def merge_string_tables Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| puts dir.blue string_files = Dir.glob(File.join(dir, '*.strings')).sort! totalfinder_strings = string_files.filter { |file| /TotalFinder\.strings/.match?(file) } other_strings = string_files.filter { |file| !/TotalFinder\.strings/.match?(file) } other_strings.each do |strings_file| unless /Template\.strings/.match?(strings_file) file_content = File.read(strings_file) strings_file =~ /\/([^\/]*)\.strings/ name = Regexp.last_match(1) contents = [] contents << '' contents << '' contents << "/* --- #{name} --- */" contents << '' contents << file_content content = contents.join("\n") append_file(totalfinder_strings.first, content) end File.delete(strings_file) end end end def validate_strings_file(path) lines = parse_strings_file(path) in_multi_line_comment = false counter = 0 lines.each do |line| counter += 1 if in_multi_line_comment && line =~ /.*\*\/\w*$/ in_multi_line_comment = false next end next if in_multi_line_comment line = "#{line.gsub(/\r\n?/, '')}\n" next if line =~ /^".*?"\s*=\s*".*?";\s*$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ next if line =~ /^\/\*.*?\*\/$/ next if line =~ /^\s*$/ if line =~ /^\/\*[^*]*/ in_multi_line_comment = true next end puts "#{"line ##{counter}: unrecognized pattern".red} (fix rakefile if this is a valid pattern)" puts line puts "mate -l #{counter} \"#{path}\"".yellow return false end true end def validate_strings_files begin require 'cmess/guess_encoding' rescue LoadError die 'You must "gem install cmess" to use character encoding detection' end glob = ENV['to'] || '*.lproj' counter = 0 failed = 0 warnings = 0 known_files = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*')) do |path| known_files << File.basename(path) end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| unrecognized_files = [] missing_files = known_files.dup Dir.glob(File.join(dir, '*')) do |path| file = File.basename(path) if missing_files.include?(file) missing_files.delete(file) else unrecognized_files << file end end if !missing_files.empty? || !unrecognized_files.empty? warnings += 1 puts "in #{dir.blue}:" puts " missing files: #{missing_files.join(', ')}" unless missing_files.empty? puts " unrecognized files: #{unrecognized_files.join(', ')}" unless unrecognized_files.empty? end end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, '*.strings')) do |path| counter += 1 ok = 1 input = File.read path charset = 'ASCII' unless input.strip.empty? charset = CMess::GuessEncoding::Automatic.guess(input) ok = ((validate_strings_file path) && ((charset == 'ASCII') || (charset == 'UTF-8'))) end puts "#{charset.magenta} #{path.blue} #{'ok'.yellow}" if ok puts "#{charset.magenta} #{path.blue} #{'failed'.red}" unless ok failed += 1 unless ok end all = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*.strings')) do |file| all.concat parse_strings_file(file) end list = [] all.each do |original| next unless original.strip[0...1] == '"' original =~ /^\s*?"(.*)"\s*?=/ list << Regexp.last_match(1) end dups = list.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys unless dups.empty? puts puts 'found duplicate keys:'.red dups.each { |x| puts " #{x}" } puts puts 'solution:'.yellow + ' shared keys should be placed in TotalFinder.strings'.blue puts end puts '-----------------------------------' failed_msg = (failed.positive? ? "#{failed} failed".red : 'all is ok'.yellow) warnings_msg = (warnings.positive? ? " [#{warnings} warnings]".green : '') puts "checked #{"#{counter} files".magenta} and #{failed_msg}#{warnings_msg}" end def stub_installer_lprojs glob = '*.lproj' english_source = File.join(INSTALLER_RESOURCES_DIR, 'en.lproj') die("need #{english_source}!") unless File.exist?(english_source) Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| name = File.basename(dir) next if name == 'en.lproj' full_path = File.join(INSTALLER_RESOURCES_DIR, name) next if File.exist?(full_path) # already have it puts "Creating stub #{full_path.blue}" sys("cp -r \"#{english_source}\" \"#{full_path}\"") end end ################################################################################################ # tasks desc 'switch /Applications/TotalFinder.app into dev mode' task :dev do sys('./bin/dev.sh') end desc 'switch /Applications/TotalFinder.app into non-dev mode' task :undev do sys('./bin/undev.sh') end desc 'restart Finder.app' task :restart do sys('./bin/restart.sh') end desc 'normalize Finder.app so it contains all our language folders (run with sudo)' task :normalize do lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') Dir.glob(lprojs) do |folder| dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) if File.exist? dir puts dir.blue + ' exists'.yellow else die('Unable to create a folder. Hint: you should run this as sudo rake normalize') unless sys("mkdir -p \"#{dir}\"") puts dir.blue + ' created'.green end end end desc 'cherrypicks strings from sources and applies missing strings to en.lproj' task :cherrypick do die 'install ack 2.0+ | for example via homebrew:> brew install ack' if `which ack` == '' die 'upgrade your ack to 2.0+ | for example via homebrew:> brew install ack' unless `ack --version` =~ /ack 2/ plugins = get_list_of_plugins xibs = categorize_xibs(plugins) puts 'XIBs:'.blue pp xibs puts puts 'Processing string files:'.yellow # additions is a hash containing an array of added translation keys for each plugin additions = process_english_strings_in_plugins(plugins, xibs) duplicates = get_additions_duplicates(additions) res = process_english_strings_in_shell(xibs['SHELL'], duplicates) # duplicates will be moved into shell shell_additions = res['to_be_added'] shell_new_strings = res['new_strings'] # insert additions to shell target = File.join(ENGLISH_LPROJ, 'TotalFinder.strings') insert_additions(shell_additions, target) unhandled_duplicates = duplicates - shell_new_strings unless unhandled_duplicates.empty? puts puts 'Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:'.yellow puts unhandled_duplicates.join(', ').magenta end end desc 'propagates structure of en.lproj to all other language folders while keeping already translated strings' task :propagate do propagate_from_english_to_other_lprojs end desc 'make stub lproj folders for installer, creates all which exist in plugin' task :stub do stub_installer_lprojs end desc 'exec command in all lproj folders' task :exec do exec_cmd_in_lprojs(ENV['cmd'] || 'ls') end desc 'validates all strings files and checks them for syntax errors' task :validate do validate_strings_files end desc 'validates all strings files and checks them for syntax errors' task :create_localization do create_localizations_for_project end desc 'merge all string tables into single TotalFinder.strings' task :merge_string_tables do merge_string_tables end task default: :restart
binaryage/totalfinder-i18n
3d288c0fb3e923a828a5801b5bc91252da371528
ja.lproj, nl.lproj: Add Japanese and Dutch localised strings for "Always use Finder icon rendering".
diff --git a/plugin/ja.lproj/TotalFinder.strings b/plugin/ja.lproj/TotalFinder.strings index c729631..8e2826e 100644 --- a/plugin/ja.lproj/TotalFinder.strings +++ b/plugin/ja.lproj/TotalFinder.strings @@ -1,227 +1,227 @@ /* preferences */ "BASIC" = "基本"; "SYSTEM" = "システム"; "Menus" = "メニュー"; "Updates" = "アップデート"; "File Browser" = "ファイルブラウザ"; "Dock" = "Dock"; "Sidebar" = "サイドバー"; /* TotalFinder Status Menu Item */ "Check for Updates" = "アップデートを確認"; "Uninstall TotalFinder" = "TotalFinder をアンインストールする"; "About TotalFinder" = "TotalFinder 情報"; "Restart Finder" = "Finder を再起動"; "Status Menu" = "Status Menu"; /* Reset to Defaults Alert Box */ "Reset" = "リセット"; "Cancel" = "キャンセル"; "Do you really want reset to defaults?" = "TotalFinder を初期設定に戻します。よろしいですか?"; "This will restore initial TotalFinder settings." = "この操作で TotalFinder は初期設定に戻ります。"; /* MainMenu items */ "TotalFinder" = "TotalFinder"; "TotalFinder Preferences…" = "環境設定…"; "Visit Homepage…" = "ホームページ(英語)を開く…"; /* registration */ "Licensed to %@" = "%@ にライセンスされています"; "Change License" = "ライセンスを変更する"; "Unregistered version in trial mode" = "未登録の試用版"; "Register" = "登録する"; /* navigation bar */ "About" = "情報"; /* tweaks page */ "Reset TotalFinder to defaults" = "初期設定に戻す"; "Hide icon in Menu Bar" = "メニューバーから TotalFinder を取り除く"; "Keep original Dock icon" = "Finder アイコンはオリジナルを使う"; /* about page */ "Check Now" = "今すぐ確認"; "Automatically check the website for updates" = "アップデートがあるかウェブサイトを自動で確認します"; "Include pre-releases" = "プレリリース版を含める"; "Participate in TotalFinder testing" = "TotalFinder のテスト版の検証に参加します"; /* registration */ "TotalFinder Registration" = "TotalFinder の登録"; "Registration" = "登録"; "Please enter your license details from the email we have sent you:" = "メールで送られてきたライセンスコードを入力してください:"; "Buy TotalFinder Now" = "TotalFinder を購入する"; "Thanks for registering!" = "登録ありがとうございます!"; "This TotalFinder copy is licensed to:" = "TotalFinder はこの方にライセンスされています:"; "Close" = "閉じる"; "Back" = "戻る"; "Invalid license code" = "無効なライセンスコード"; "Please go back and try again." = "前に戻ってやり直してください。"; "To purchase a license for TotalFinder, please visit BinaryAge web store." = "TotalFinder ライセンスの購入は、BinaryAge のウェブストアで。"; "Thank you for using TotalFinder!" = "TotalFinder をご使用いただきありがとうございます!"; "License Name" = "ライセンス名"; "License Key" = "ライセンスキー"; /* shortcuts subsystem */ "Click to record new shortcut" = "クリックして新規ショートカット"; "Delete shortcut" = "ショートカットを削除"; "OK" = "OK"; "Record Shortcut" = "ショートカットを記録"; "Space" = "スペース"; "The key combination %@ cannot be used" = "%@ というキーの組み合わせは使用できません"; "This combination cannot be used because it is already used..." = "This combination cannot be used because it is already used by a system-wide keyboard shortcut.\nIf you really want to use this key combination, most shortcuts can be changed in the Keyboard & Mouse panel in System Preferences."; "This shortcut cannot be used because it is already used by the menu item ‘%@’." = "このショートカットは、メニュー項目 ‘%@’ で使用されているため、使用できません。"; "Type New Shortcut" = "新規ショートカットをタイプ"; "Type Shortcut" = "ショートカットをタイプ"; "Use Old Shortcut" = "以前のショートカットを使用"; "Set it anyway" = "Set it anyway"; /* tabs section */ "Disable tabs completely" = "タブ機能を完全に停止する"; "Do you really want to disable tabs?" = "本当にタブ機能を無効にしてよろしいですか?"; "Do you really want to enable tabs?" = "本当にタブ機能を有効にしてよろしいですか?"; "Tabs" = "タブ"; "This option will effectively disable the tabs module in TotalFinder..." = "このオプションは、TotalFinder のタブモジュールの働き実際に停止します。デュアルモードとバイザー機能も同様に事実上停止します。このオプションは、Marvericks で - TotalFinder の他の機能を利用しながら、Finder ネイティブのタブ機能を使用する際に必要とされます。\n\nこのオプションの変更を反映するために Finder を再起動しなくてはなりません!\n注意: 再起動に先立ち、(ファイルのコピーや移動といった) Finder で実行中のタスクを終えるようにして下さい。"; "This option will effectively enable the tabs module in TotalFinder..." = "このオプションは、TotalFinder のタブモジュールの働きを実際に開始します。\n\nこのオプションの変更を反映するために、Finder を再起動しなくてはなりません。\n注意: 再起動に先立ち、(ファイルのコピーや移動といった) Finder で実行中のタスクを終えるようにして下さい。"; "This will effectively disable tabs, dual mode and visor. Finder restart is needed." = "これは、タブ、デュアルモード、バイザー機能を実際に停止します。Finder の再起動が必要となります。"; /* --- ColorfulSidebar --- */ "Show sidebar icons in color" = "サイドバーのアイコンを色つきで表示"; -"Always use Finder icon rendering" = "Always use Finder icon rendering"; +"Always use Finder icon rendering" = "Finderのアイコンレンダリングを常に使用する"; /* --- ColumnViewAutoWidth --- */ "Automatically adjust widths in Column View" = "カラム表示で列幅を自動的に調整します"; "Limit maximum column width to" = "列幅の最大上限値"; "Limit minimum column width to" = "列幅の最小下限値"; /* --- CopyPathMenu --- */ "Copy Path" = "パスをコピー"; "POSIX Path" = "POSIX パス"; "URL" = "URL"; "Windows Path" = "Windows パス"; "HFS Path" = "HFS パス"; "Terminal Path" = "ターミナルパス"; "UNC Path" = "UNC Path"; "Allow path copying from Context Menus" = "コンテキストメニューからパスのコピーを許可"; /* --- CutAndPaste --- */ /* please note these items should be translated by exactly the same conventions */ /* as Main Menu > Edit > Copy item works in your localized Finder */ /* do not translate it directly from English but look how your menu looks in your language */ /* sample screenshot of English version: http://dl.dropbox.com/u/559047/Screenshots/qigu.png */ "Edit" = "編集"; "Cut" = "カット"; "Cut “%@”" = "“%@” をカット"; "Cut %u Items" = "%u 項目をカット"; "Paste" = "ペースト"; "Paste %u Items" = "%u 項目をペースト"; "Copy" = "コピー"; "Show CutPaste buttons in Context Menus" = "コンテキストメニューにカットボタン等を表示"; /* --- DockProgressBar --- */ "Show progress bar in the Dock" = "Dock アイコンにプログレスバーを表示します"; /* --- Labels --- */ "Colored Labels" = "ラベルの背景に色をつける"; "The last applied tag determines item's background color." = "最後に適用したタグによって、項目の背景色を決定します。"; /* --- MenuItems --- */ /* menu items are special - their keys are always prefixed with 'MenuItem:' (prefix) The goal is to distinguish them from normal string keys and allow menu item localization to be independent from other strings. Without this (in English) some keys would be shared for menu items and preferences, and this would make it uneasy to localize them in other languages properly => this will prevent it. */ "MenuItem:Pin Visor" = "バイザー固定"; "MenuItem:Close Tab" = "タブを閉じる"; "MenuItem:New Native Tab" = "ネイティブなタブを新規で開く"; "MenuItem:Close Native Tab" = "ネイティブなタブを閉じる"; "MenuItem:Show Previous Native Tab" = "前のネイティブタブを表示"; "MenuItem:Show Next Native Tab" = "次のネイティブタブを表示"; "MenuItem:New Tab" = "新規タブ"; "MenuItem:Reopen Closed Tab" = "閉じたタブを再度開く"; "MenuItem:Close Window" = "ウィンドウを閉じる"; "MenuItem:Toggle Dual Mode" = "デュアルモードの切替"; "MenuItem:Narrow Tabs Bar" = "細いタブバーを使う"; "MenuItem:Select Previous Tab" = "前のタブを選択"; "MenuItem:Select Next Tab" = "次のタブを選択"; "MenuItem:Switch Active Panel" = "アクティブなパネルを切り替え"; "MenuItem:Show System Files" = "システムファイルを表示"; "MenuItem:Column View Auto Width" = "カラム表示で列幅を自動調整"; "MenuItem:Dock Progress Bar" = "Dock プログレスバー"; /* note: These menu item localizations are taken from Finder's localization table: Enter Full Screen Exit Full Screen */ /* --- SystemFiles --- */ "Show System Files" = "システムファイルを表示"; /* --- Tabs --- */ "TotalFinder - unregistered version" = "TotalFinder - 未登録"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 試用期限の残りはあと 1 日です - 購入してください!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 2 日です - 購入してください!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 3 日です - 購入してください!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 4 日です - 購入してください!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 5 日です - 購入してください!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - 試用期限の残りはあと %d 日です - 購入してください!"; "Close Tab" = "タブを閉じる"; "Toggle Dual Mode" = "デュアルモードの切替"; "New Tab" = "新規タブ"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "タブバーを狭くする"; "Open new tabs with previous location" = "以前の場所を新規のタブで開く"; "Freelance Windows" = "タブの代わりに新しいウィンドウで開く"; /* --- Visor --- */ "Pin Visor" = "バイザー固定"; "Show Visor" = "バイザーを表示"; "Hide Visor" = "バイザーを隠す"; "Visor" = "バイザー"; "a system-wide window sliding from the bottom on a hot-key" = "ホットキーでいつでも画面下部にウィンドウを表示できます"; "Visor Feature" = "バイザー機能を有効にする"; "Activation:" = "起動:"; "Show on all Spaces" = "すべてのSpacesの画面で表示"; "Animation:" = "表示効果:"; "Control:" = "制御:"; "Slide Window" = "ウィンドウをスライド"; "Fade Window" = "ウィンドウをフェードイン/アウト"; "Show on top of the Dock" = "Dock よりも前面に表示"; "Free Form Window" = "ウィンドウのサイズ変更を許可"; "Hide on ESC" = "ESCキーで隠す"; "Screen:" = "画面:"; "Screen" = "スクリーン"; "Screen with Mouse Cursor" = "マウスカーソルのあるスクリーン"; diff --git a/plugin/nl.lproj/TotalFinder.strings b/plugin/nl.lproj/TotalFinder.strings index 54e220b..9686777 100644 --- a/plugin/nl.lproj/TotalFinder.strings +++ b/plugin/nl.lproj/TotalFinder.strings @@ -1,227 +1,227 @@ /* preferences */ "BASIC" = "BASIS"; "SYSTEM" = "SYSTEEM"; "Menus" = "Menu's"; "Updates" = "Updates"; "File Browser" = "Bestandsweergave"; "Dock" = "Dock"; "Sidebar" = "Navigatiebalk"; /* TotalFinder Status Menu Item */ "Check for Updates" = "Controleer op updates"; "Uninstall TotalFinder" = "Verwijder TotalFinder"; "About TotalFinder" = "Over TotalFinder"; "Restart Finder" = "Herstart Finder"; "Status Menu" = "Status Menu"; /* Reset to Defaults Alert Box */ "Reset" = "Herstel"; "Cancel" = "Annuleren"; "Do you really want reset to defaults?" = "Wilt u echt terug naar de standaardinstellingen?"; "This will restore initial TotalFinder settings." = "Dit zal de standaardinstellingen van TotalFinder herstellen."; /* MainMenu items */ "TotalFinder" = "TotalFinder"; "TotalFinder Preferences…" = "TotalFinder voorkeuren…"; "Visit Homepage…" = "Ga naar de homepage…"; /* registration */ "Licensed to %@" = "Gelicenseerd aan %@"; "Change License" = "Wijzig licentie"; "Unregistered version in trial mode" = "Ongeregistreerde versie in probeermodus"; "Register" = "Registreer"; /* navigation bar */ "About" = "Over"; /* tweaks page */ "Reset TotalFinder to defaults" = "Herstel de standaardinstellingen van TotalFinder"; "Hide icon in Menu Bar" = "Verberg icoon in menubalk"; "Keep original Dock icon" = "Behoud het originele Dockicoon"; /* about page */ "Check Now" = "Controleer nu"; "Automatically check the website for updates" = "Controleer automatisch of er updates zijn"; "Include pre-releases" = "Inclusief pre-releases"; "Participate in TotalFinder testing" = "Help mee met het testen van TotalFinder"; /* registration */ "TotalFinder Registration" = "Registratie van TotalFinder"; "Registration" = "Registreren"; "Please enter your license details from the email we have sent you:" = "Voer de licentiegegevens in die u per e-mail van ons ontvangen heeft:"; "Buy TotalFinder Now" = "Koop TotalFinder nu"; "Thanks for registering!" = "Bedankt voor uw registratie!"; "This TotalFinder copy is licensed to:" = "Dit exemplaar van TotalFinder is gelicenseerd aan:"; "Close" = "Sluiten"; "Back" = "Terug"; "Invalid license code" = "Ongeldige licentiecode"; "Please go back and try again." = "Ga terug en probeer het opnieuw."; "To purchase a license for TotalFinder, please visit BinaryAge web store." = "Bezoek de webwinkel van BinaryAge om een licentie voor het gebruik van Totalfinder te kopen."; "Thank you for using TotalFinder!" = "Bedankt voor het gebruiken van TotalFinder!"; "License Name" = "Licentienaam"; "License Key" = "Licentiecode"; /* shortcuts subsystem */ "Click to record new shortcut" = "Klik om een nieuwe sneltoets op te nemen"; "Delete shortcut" = "Verwijder sneltoets"; "OK" = "OK"; "Record Shortcut" = "Neem sneltoets op"; "Space" = "Spatie"; "The key combination %@ cannot be used" = "De toetscombinatie %@ kan niet worden gebruikt"; "This combination cannot be used because it is already used..." = "Deze combinatie kan niet worden gebruikt omdat het al is toegewezen aan een systeemwijde toetscombinatie.\nAls u echt deze toetscombinatie wilt gebruiken, kunt u de meeste toetscombinaties wijzigen in de systeemvoorkeuren-paneel Toetsenbord en muis. "; "This shortcut cannot be used because it is already used by the menu item ‘%@’." = "Deze sneltoets kan niet worden gebruikt, omdat die al in gebruik is door menu-item ‘%@’."; "Type New Shortcut" = "Typ een nieuwe sneltoets"; "Type Shortcut" = "Typ sneltoets"; "Use Old Shortcut" = "Gebruik oude sneltoets"; "Set it anyway" = "Set it anyway"; /* tabs section */ "Disable tabs completely" = "Tabs volledig uitzetten?"; "Do you really want to disable tabs?" = "Wilt u echt de tabs uitzetten?"; "Do you really want to enable tabs?" = "wilt u echt de tabs aanzetten?"; "Tabs" = "Tabbladen"; "This option will effectively disable the tabs module in TotalFinder..." = "Deze optie zal de tabs-module volledig uitzetten in TotalFinder. Hierdoor zullen de dubbele kolom en visor ook worden uitgezet. Dit kan gewenst zijn in Mavericks – gebruik enkel de ingebouwde Finder tabs maar behoud andere voordelen van TotalFinder functies.\n\nFinder zal worden herstart om de wijzigingen toe te passen.\nLet op: voltooi eerst alle Finder-bezigheden (zoals het verplaatsen of kopiëren van bestanden)."; "This option will effectively enable the tabs module in TotalFinder..." = "Deze optie zal de tabs-module aanzetten in TotalFinder.\n\nFinder zal worden herstart om de wijzigingen toe te passen.\nLet op: voltooi eerst alle Finder-bezigheden (zoals het verplaatsen of kopiëren van bestanden)."; "This will effectively disable tabs, dual mode and visor. Finder restart is needed." = "Dit zal tabs tabs, dubbele kolom en visor uitzetten. Finder herstarten is vereist."; /* --- ColorfulSidebar --- */ "Show sidebar icons in color" = "Toon gekleurde iconen in navigatiebalk"; -"Always use Finder icon rendering" = "Always use Finder icon rendering"; +"Always use Finder icon rendering" = "Gebruik altijd Finder icon rendering"; /* --- ColumnViewAutoWidth --- */ "Automatically adjust widths in Column View" = "Pas formaat automatisch aan bij kolomweergave"; "Limit maximum column width to" = "Limiteer maximale kolombreedte tot"; "Limit minimum column width to" = "Limiteer minimale kolombreedte tot"; /* --- CopyPathMenu --- */ "Copy Path" = "Kopieer het pad"; "POSIX Path" = "POSIX-pad"; "URL" = "URL"; "Windows Path" = "Windows-pad"; "HFS Path" = "HFS-pad"; "Terminal Path" = "Terminal-pad"; "UNC Path" = "UNC-pad"; "Allow path copying from Context Menus" = "Sta kopiëren van paden uit contextmenu's toe"; /* --- CutAndPaste --- */ /* please note these items should be translated by exactly the same conventions */ /* as Main Menu > Edit > Copy item works in your localized Finder */ /* do not translate it directly from English but look how your menu looks in your language */ /* sample screenshot of English version: http://dl.dropbox.com/u/559047/Screenshots/qigu.png */ "Edit" = "Wijzig"; "Cut" = "Knip"; "Cut “%@”" = "Knip “%@”"; "Cut %u Items" = "Knip %u onderdelen"; "Paste" = "Plak"; "Paste %u Items" = "Plak %u onderdelen"; "Copy" = "Kopieer"; "Show CutPaste buttons in Context Menus" = "Toon knip- en plakknoppen in contextmenu's"; /* --- DockProgressBar --- */ "Show progress bar in the Dock" = "Laat voortgang zien in het Dock"; /* --- Labels --- */ "Colored Labels" = "Gekleurde labels"; "The last applied tag determines item's background color." = "De laatst toegewezen tag bepaalt het item's achtergrondkleur."; /* --- MenuItems --- */ /* menu items are special - their keys are always prefixed with 'MenuItem:' (prefix) The goal is to distinguish them from normal string keys and allow menu item localization to be independent from other strings. Without this (in English) some keys would be shared for menu items and preferences, and this would make it uneasy to localize them in other languages properly => this will prevent it. */ "MenuItem:Pin Visor" = "Zet Visor vast"; "MenuItem:Close Tab" = "Sluit tabblad"; "MenuItem:New Native Tab" = "Nieuw native tabblad"; "MenuItem:Close Native Tab" = "Sluit native tabblad"; "MenuItem:Show Previous Native Tab" = "Toon vorige native tabblad"; "MenuItem:Show Next Native Tab" = "Toon volgende native tabblad"; "MenuItem:New Tab" = "Nieuw tabblad"; "MenuItem:Reopen Closed Tab" = "Heropen gesloten tabblad"; "MenuItem:Close Window" = "Sluit venster"; "MenuItem:Toggle Dual Mode" = "Dubbele/enkele kolom"; "MenuItem:Narrow Tabs Bar" = "Verklein tabbalk"; "MenuItem:Select Previous Tab" = "Kies vorig tabblad"; "MenuItem:Select Next Tab" = "Kies volgend tabblad"; "MenuItem:Switch Active Panel" = "Verander actief paneel"; "MenuItem:Show System Files" = "Toon systeembestanden"; "MenuItem:Column View Auto Width" = "Kolomweergave automatisch formaat"; "MenuItem:Dock Progress Bar" = "Dock-voortgangsindicator"; /* note: These menu item localizations are taken from Finder's localization table: Enter Full Screen Exit Full Screen */ /* --- SystemFiles --- */ "Show System Files" = "Toon systeembestanden"; /* --- Tabs --- */ "TotalFinder - unregistered version" = "TotalFinder - ongeregistreerde versie"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - nog 1 dag - koop nu!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - nog 2 dagen - koop nu!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - nog 3 dagen - koop nu!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - nog 4 dagen - koop nu!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - nog 5 dagen - koop nu!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - nog %d dagen - koop nu!"; "Close Tab" = "Sluit tabblad"; "Toggle Dual Mode" = "Dubbele/enkele kolom"; "New Tab" = "Nieuw tabblad"; "Use narrow Tabs Bar" = "Gebruik smalle tabbalk"; "Open new tabs with previous location" = "Open nieuwe tabs met de vorige locatie"; "Freelance Windows" = "Freelance-schermen"; /* --- Visor --- */ "Pin Visor" = "Zet Visor vast"; "Show Visor" = "Activeer Visor"; "Hide Visor" = "Deactiveer Visor"; "Visor" = "Visor"; "a system-wide window sliding from the bottom on a hot-key" = "een systeembreed venster dat van beneden binnenschuift met één sneltoets"; "Visor Feature" = "De Visor-functie"; "Activation:" = "Activatie:"; "Show on all Spaces" = "Laat zien op alle Spaces"; "Animation:" = "Animatie:"; "Control:" = "Besturen:"; "Slide Window" = "Venster inschuiven"; "Fade Window" = "Venster fade-in"; /* This word exists, according to the Van Dale dictionary */ "Show on top of the Dock" = "Blijf boven het Dock"; "Free Form Window" = "Vrij venster"; "Hide on ESC" = "Verberg met ESC"; "Screen:" = "Scherm:"; "Screen" = "Scherm"; "Screen with Mouse Cursor" = "Scherm met muisaanwijzer";
binaryage/totalfinder-i18n
dd5cb6d8f285d79684b777a07c715bfab7e6d60e
ColorfulSidebarPreferences: Add "Always use Finder icon rendering" preference, slated for TotalFinder 1.14.2 release. This preference changes the behaviour of the Colorful Sidebar feature by skipping TotalFinder's icon mapping lookup entirely, which is normally used for legacy skeuomorphic icons such as NSMediaBrowserMediaTypeAudio (for Music), and instead falling back to rendering icons the way Finder normally would. ※ Please note that this also disables user-defined custom icon mappings via `~/.totalfinder-sidebar.icons.plist`.
diff --git a/plugin/XIBs/ColorfulSidebarPreferences.xib b/plugin/XIBs/ColorfulSidebarPreferences.xib index e899c4d..e33585c 100644 --- a/plugin/XIBs/ColorfulSidebarPreferences.xib +++ b/plugin/XIBs/ColorfulSidebarPreferences.xib @@ -1,45 +1,57 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="19528" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="20037" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="19528"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="20037"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="ColorfulSidebarPluginPreferencesController"> <connections> <outlet property="$sidebarPreferences" destination="4" id="14"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="4" userLabel="Sidebar Preferences"> - <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> + <rect key="frame" x="0.0" y="0.0" width="480" height="91"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="7"> - <rect key="frame" x="18" y="9" width="201" height="18"/> + <rect key="frame" x="18" y="64" width="201" height="18"/> <buttonCell key="cell" type="check" title="^Show sidebar icons in color" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="8"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderColorfulSidebarEnabled" id="13"/> </connections> </button> + <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Erf-Zg-Thm"> + <rect key="frame" x="18" y="8" width="233" height="18"/> + <buttonCell key="cell" type="check" title="^Always use Finder icon rendering" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="7bY-jV-KzA"> + <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> + <font key="font" metaFont="system"/> + </buttonCell> + <connections> + <binding destination="3" name="value" keyPath="values.TotalFinderColorfulSidebarAlwaysUseFinderIconRenderer" id="KHt-M4-gcH"/> + </connections> + </button> </subviews> <constraints> <constraint firstItem="7" firstAttribute="leading" secondItem="4" secondAttribute="leading" constant="20" symbolic="YES" id="5"/> <constraint firstItem="7" firstAttribute="centerY" secondItem="4" secondAttribute="centerY" id="17"/> + <constraint firstItem="Erf-Zg-Thm" firstAttribute="leading" secondItem="7" secondAttribute="leading" id="xyG-Xx-wUn"/> + <constraint firstItem="Erf-Zg-Thm" firstAttribute="top" secondItem="7" secondAttribute="bottom" constant="20" id="yDq-eY-icx"/> </constraints> - <point key="canvasLocation" x="139" y="154"/> + <point key="canvasLocation" x="139" y="190"/> </customView> <customObject id="2" userLabel="Sidebar Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="4" id="9"/> <outlet property="owner_" destination="-2" id="11"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document>
binaryage/totalfinder-i18n
bac30410f5a2910c17c24306a65d4904f528eafd
TabsPreferences: Remove an erroneous width constraint that was causing localised versions of the "Freelance Windows" preference string to be cut off in languages that had a much longer string, such as Japanese. ※ TODO: Also consider rewording the "Freelance Windows" preference entirely, since it is currently very unclear to end-users what that feature even does. The Japanese localisation currently does a pretty good job of this. (The internal preference "DontMakeTabs" can at least clue in any technically-minded users who look at the XIB code…)
diff --git a/plugin/XIBs/TabsPreferences.xib b/plugin/XIBs/TabsPreferences.xib index 6199151..d9adb67 100644 --- a/plugin/XIBs/TabsPreferences.xib +++ b/plugin/XIBs/TabsPreferences.xib @@ -1,106 +1,103 @@ <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="19528" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="19528"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="TabsPluginPreferencesController"> <connections> <outlet property="$tabsPreferences" destination="1" id="70"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Tabs Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="159"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="11"> <rect key="frame" x="18" y="86" width="160" height="18"/> <buttonCell key="cell" type="check" title="^Use narrow Tabs Bar" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="12"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderNarrowTabsBar" id="13"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="19"> <rect key="frame" x="18" y="123" width="122" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Toggle Dual Mode" id="20"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <customView translatesAutoresizingMaskIntoConstraints="NO" id="32" customClass="MASShortcutView"> <rect key="frame" x="186" y="86" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="73"/> <constraint firstAttribute="width" constant="130" id="126"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="NarrowTabsBar"/> </userDefinedRuntimeAttributes> </customView> <customView translatesAutoresizingMaskIntoConstraints="NO" id="49" customClass="MASShortcutView"> <rect key="frame" x="146" y="122" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="74"/> <constraint firstAttribute="width" constant="130" id="124"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="DualMode"/> </userDefinedRuntimeAttributes> </customView> <button translatesAutoresizingMaskIntoConstraints="NO" id="75"> - <rect key="frame" x="18" y="13" width="149" height="18"/> - <constraints> - <constraint firstAttribute="width" constant="147" id="g5t-WI-Jyt"/> - </constraints> + <rect key="frame" x="18" y="13" width="152" height="18"/> <buttonCell key="cell" type="check" title="^Freelance Windows" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="76"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderDontMakeTabs" id="88"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="102"> <rect key="frame" x="18" y="50" width="261" height="18"/> <buttonCell key="cell" type="check" title="^Open new tabs with previous location" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="103"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderNewTabsWithCurrentTarget" id="110"/> </connections> </button> </subviews> <constraints> <constraint firstItem="49" firstAttribute="leading" secondItem="19" secondAttribute="trailing" constant="8" symbolic="YES" id="136"/> <constraint firstItem="19" firstAttribute="top" secondItem="1" secondAttribute="top" constant="20" symbolic="YES" id="149"/> <constraint firstItem="49" firstAttribute="centerY" secondItem="19" secondAttribute="centerY" id="150"/> <constraint firstItem="11" firstAttribute="top" secondItem="19" secondAttribute="bottom" constant="20" id="153"/> <constraint firstItem="32" firstAttribute="centerY" secondItem="11" secondAttribute="centerY" id="156"/> <constraint firstItem="32" firstAttribute="leading" secondItem="11" secondAttribute="trailing" constant="8" symbolic="YES" id="157"/> <constraint firstItem="11" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="158"/> <constraint firstItem="19" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="159"/> <constraint firstItem="102" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="169"/> <constraint firstItem="102" firstAttribute="top" secondItem="11" secondAttribute="bottom" constant="20" id="EyF-gb-0fw"/> <constraint firstItem="75" firstAttribute="leading" secondItem="102" secondAttribute="leading" id="XHr-q0-Wye"/> <constraint firstItem="75" firstAttribute="top" secondItem="102" secondAttribute="bottom" constant="21" id="eEw-DD-XdV"/> </constraints> <point key="canvasLocation" x="139" y="163.5"/> </customView> <customObject id="2" userLabel="Tabs Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="72"/> <outlet property="owner_" destination="-2" id="71"/> </connections> </customObject> <userDefaultsController id="4" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document>
binaryage/totalfinder-i18n
d6460ea98f49bc2a568f17b86c621c908faa7cb8
fix an uninstallation dialog typo
diff --git a/uninstaller/en.lproj/Localizable.strings b/uninstaller/en.lproj/Localizable.strings index a3746fc..7a16e29 100644 --- a/uninstaller/en.lproj/Localizable.strings +++ b/uninstaller/en.lproj/Localizable.strings @@ -1,23 +1,23 @@ /* buttons */ "Quit" = "Quit"; "Cancel" = "Cancel"; "Uninstall" = "Uninstall"; "Details" = "Details"; /* tooltips */ "Show detailed transcript" = "Show detailed transcript"; /* main texts */ -"You are about uninstall *APP*" = "You are about uninstall TotalFinder"; +"You are about uninstall *APP*" = "You are about to uninstall TotalFinder"; "This program will uninstall all *APP* components from this computer." = "This program will uninstall all TotalFinder components from this computer."; "*APP* has been uninstalled" = "TotalFinder has been uninstalled"; "Thank you for trying *APP*." = "Thank you for trying TotalFinder."; "*APP* uninstallation failed" = "TotalFinder uninstallation failed"; "The uninstall script encountered problems. Please see the details. Please report bugs to support@binaryage.com." = "The uninstall script encountered problems. Please see the details. Please report bugs to support@binaryage.com."; /* possible script messages in details section */ "Uninstaller needs admin privileges to remove *APP* from your system." = "Uninstaller needs admin privileges to remove TotalFinder from your system."; "Running uninstall script:\n" = "Running uninstall script:\n"; "Uninstall script finished successfully.\n" = "Uninstall script finished successfully.\n"; "Uninstall script needs admin rights.\n" = "Uninstall script needs admin rights.\n"; "Uninstall script failed with error [%d].\n" = "Uninstall script failed with error [%d].\n";
binaryage/totalfinder-i18n
377570d1ee6400f3e334230c2475841a8e293926
indicate post-install launch of TotalFinder agent
diff --git a/plugin/com.binaryage.totalfinder.agent.plist b/plugin/com.binaryage.totalfinder.agent.plist index 900b4a9..3abf1ca 100644 --- a/plugin/com.binaryage.totalfinder.agent.plist +++ b/plugin/com.binaryage.totalfinder.agent.plist @@ -1,18 +1,19 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.binaryage.totalfinder.agent</string> <key>ProgramArguments</key> <array> <string>/Applications/TotalFinder.app/Contents/MacOS/TotalFinder</string> + <string>--post-install</string> </array> <key>RunAtLoad</key> <true/> <key>StandardErrorPath</key> <string>/dev/null</string> <key>StandardOutPath</key> <string>/dev/null</string> </dict> </plist>
binaryage/totalfinder-i18n
dc6994bd0a687feafb0c5e6366165f70f886b8a6
fix broken markup in th.lproj/PurchaseScreen.html
diff --git a/plugin/th.lproj/PurchaseScreen.html b/plugin/th.lproj/PurchaseScreen.html index e5e3c13..eb041a5 100644 --- a/plugin/th.lproj/PurchaseScreen.html +++ b/plugin/th.lproj/PurchaseScreen.html @@ -1,26 +1,26 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <title></title> <meta name="Generator" content="Cocoa HTML Writer"> <meta name="CocoaVersion" content="1038.36"> <style type="text/css"> p.p1 {margin: 0.0px 0.0px 20.0px 0.0px; font: 12.0px 'Lucida Grande'; color: #6666ff} p.p2 {margin: 0.0px 0.0px 20.0px 0.0px; font: 12.0px Thonburi; color: #666666} span.s1 {font: 12.0px Thonburi; color: #666666} span.s2 {color: #666666} span.s3 {text-decoration: underline ; color: #6666ff} span.s4 {font: 12.0px 'Lucida Grande'} span.s5 {font: 12.0px Thonburi; text-decoration: underline ; color: #6666ff} </style> </head> <body> <p class="p1"><span class="s1">ข้อมูลเพิ่มเติม</span><span class="s2">:<br> </span><span class="s1">หน้าแรก</span><span class="s2">: <a href="https://totalfinder.binaryage.com/"><span class="s3">https://totalfinder.binaryage.com</span></a><br> -</span><span class="s1">เอกสารประกอบ</span><span class="s2">: <a href="https://totalfinder.binaryage.com/about"><span class="s3"https://totalfinder.binaryage.com/about</span></a><br> +</span><span class="s1">เอกสารประกอบ</span><span class="s2">: <a href="https://totalfinder.binaryage.com/about"><span class="s3">https://totalfinder.binaryage.com/about</span></a><br> </span><span class="s1">ติดต่อและช่วยเหลือ</span><span class="s2">: <a href="https://discuss.binaryage.com/"><span class="s3">https://discuss.binaryage.com</span></a></span></p> <p class="p2"><span class="s4">TotalFinder </span>ถูกสร้างขึ้นจากเครื่องมือหลายอย่างและโปรแกรม open-source มากมาย ขอขอบคุณ<span class="s4"> <a href="https://totalfinder.binaryage.com/credits"><span class="s5">ผู้พัฒนาโปรแกรมเหล่านั้น</span></a>!</span></p> </body> </html>
binaryage/totalfinder-i18n
0413e9ce277eda7db4089978b91c248568034ef3
remove hardcoded version in cy.lproj/InfoLine.html
diff --git a/plugin/cy.lproj/InfoLine.html b/plugin/cy.lproj/InfoLine.html index 8506393..0afda27 100644 --- a/plugin/cy.lproj/InfoLine.html +++ b/plugin/cy.lproj/InfoLine.html @@ -1,7 +1,7 @@ <style> html {font-family: 'Lucida Grande', arial; font-size: 10px; cursor: default; color: #999;} html,body {overflow: hidden;} a, a:visited { color: #66f; } a:hover {color: #22f} </style> -<center><b>TotalFinder 1.0.1</b> gan <a href="https://www.binaryage.com">binaryage.com</a></center> +<center><b>TotalFinder ##VERSION##</b> gan <a href="https://www.binaryage.com">binaryage.com</a></center>
binaryage/totalfinder-i18n
1f5c186566c9a864f4d058e458f1e5d1603fb5f5
normalize he.lproj/InfoLine.html
diff --git a/plugin/he.lproj/InfoLine.html b/plugin/he.lproj/InfoLine.html index 04ef9d7..6940e30 100644 --- a/plugin/he.lproj/InfoLine.html +++ b/plugin/he.lproj/InfoLine.html @@ -1,18 +1,7 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta http-equiv="Content-Style-Type" content="text/css"> - <title></title> - <meta name="Generator" content="Cocoa HTML Writer"> - <meta name="CocoaVersion" content="1265.21"> - <style type="text/css"> - p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; text-align: center; font: 10.0px 'Lucida Grande'; color: #999999} - span.s1 {direction: ltr; unicode-bidi: embed} - span.s2 {text-decoration: underline ; color: #6666ff} - </style> -</head> -<body> -<p dir="rtl" class="p1"><b>TotalFinder גרסא ##VERSION##<b> ע״י <a href="https://www.binaryage.com">binaryage.com</a></p> -</body> -</html> +<style> + html {font-family: 'Lucida Grande', arial; font-size: 10px; cursor: default; color: #999;} + html,body {overflow: hidden;} + a, a:visited { color: #66f; } + a:hover {color: #22f} +</style> +<center><b>TotalFinder גרסא ##VERSION##</b> ע״י <a href="https://www.binaryage.com">binaryage.com</a></center> \ No newline at end of file
binaryage/totalfinder-i18n
98a69a457b0f8c012c09dd99b407ba15fd3b9ed2
fix UTF-8 encoding in hu.lproj/LicensingInfo.html
diff --git a/plugin/hu.lproj/LicensingInfo.html b/plugin/hu.lproj/LicensingInfo.html index 48a7384..d68ddcf 100644 --- a/plugin/hu.lproj/LicensingInfo.html +++ b/plugin/hu.lproj/LicensingInfo.html @@ -1,19 +1,19 @@ <style> html{font-family:'Lucida Grande',arial;font-size:10px;cursor:default;color:#666;} html,body {overflow: hidden;} a,a:visited{color:#66f;} a:hover{color:#22f} h1{white-space:nowrap;} ul{margin:0;padding:0;padding-left:16px;} p{margin-bottom: 10px} .choice{margin-top: 6px;} .example{margin-left: 14px;margin-top: 2px; font-size: 9px;} .note {font-size: 9px;} </style> -<p>A licensz két módon használható:</p> -<div class="choice">1. <strong>egy felhasználó több számítógépen</strong> <span class="note">(ameddig csak egyetlen felhasználó használja a TotalFinder-t)</span></div> -<div class="example">Például: egy asztali számítógép és egy laptop, aminek Ön a kizárólagos használója</div> -<div class="choice">2. <strong>több felhasználó egyetlen számítógépen</strong></div> -<div class="example">Például: otthoni számítógép, amelyet a család összes tagja használ</div> -<p class="note">A licenszeléssel kapcsolatos további kérdések miatt keresse fel az alábbi haivatkozást: <a href="https://totalfinder.binaryage.com/licensing">https://totalfinder.binaryage.com/licensing</a></p> +<p>A licensz két módon használható:</p> +<div class="choice">1. <strong>egy felhasználó több számítógépen</strong> <span class="note">(ameddig csak egyetlen felhasználó használja a TotalFinder-t)</span></div> +<div class="example">Például: egy asztali számítógép és egy laptop, aminek Ön a kizárólagos használója</div> +<div class="choice">2. <strong>több felhasználó egyetlen számítógépen</strong></div> +<div class="example">Például: otthoni számítógép, amelyet a család összes tagja használ</div> +<p class="note">A licenszeléssel kapcsolatos további kérdések miatt keresse fel az alábbi haivatkozást: <a href="https://totalfinder.binaryage.com/licensing">https://totalfinder.binaryage.com/licensing</a></p>
binaryage/totalfinder-i18n
136a77ef02086bcfe2000f44ed4c7550dd6f5a70
fix broken markup in el.lproj/PurchaseScreen.html
diff --git a/plugin/el.lproj/PurchaseScreen.html b/plugin/el.lproj/PurchaseScreen.html index 3a324d8..3649e71 100644 --- a/plugin/el.lproj/PurchaseScreen.html +++ b/plugin/el.lproj/PurchaseScreen.html @@ -1,23 +1,23 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <title></title> <meta name="Generator" content="Cocoa HTML Writer"> <meta name="CocoaVersion" content="1038.35"> <style type="text/css"> p.p1 {margin: 0.0px 0.0px 20.0px 0.0px; font: 12.0px 'Lucida Grande'; color: #6666ff} p.p2 {margin: 0.0px 0.0px 20.0px 0.0px; font: 12.0px 'Lucida Grande'; color: #666666} span.s1 {color: #666666} span.s2 {text-decoration: underline ; color: #6666ff} </style> </head> <body> <p class="p1"><span class="s1">Πληροφορίες:<br> Σελίδα: <a href="https://totalfinder.binaryage.com/"><span class="s2">https://totalfinder.binaryage.com</span></a><br> -Βιβλιογραφία: <a href="https://totalfinder.binaryage.com/about"><span class="s2"https://totalfinder.binaryage.com/about</span></a><br> +Βιβλιογραφία: <a href="https://totalfinder.binaryage.com/about"><span class="s2">https://totalfinder.binaryage.com/about</span></a><br> Υποστήριξη: <a href="https://discuss.binaryage.com/"><span class="s2">https://discuss.binaryage.com</span></a></span></p> <p class="p2">Το TotalFinder δημιουργήθηκε με την βοήθεια πολλών εργαλείων και ανοιχτού κώδικα βιβλιοθηκών. Ευχαριστώ πολύ <a href="https://totalfinder.binaryage.com/credits"><span class="s2">τους δημιουργούς</span></a>!</p> </body> </html>
binaryage/totalfinder-i18n
e729bebae453f3a0114d64dadf5a013587a60e5b
make rubocop happy again
diff --git a/ruby/.rubocop.yml b/ruby/.rubocop.yml index d85ac0c..bebf064 100644 --- a/ruby/.rubocop.yml +++ b/ruby/.rubocop.yml @@ -1,62 +1,63 @@ AllCops: TargetRubyVersion: 2.7 + NewCops: enable Include: - '*.rb' - '*.rake' Layout/LineLength: Max: 126 Layout/SpaceAroundEqualsInParameterDefault: EnforcedStyle: no_space Metrics/MethodLength: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false Metrics/BlockNesting: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/ClassLength: Enabled: false Style/Documentation: Enabled: false Layout/FirstArrayElementIndentation: Enabled: false Style/GuardClause: Enabled: false Metrics/PerceivedComplexity: Enabled: false Style/TernaryParentheses: Enabled: false Style/RegexpLiteral: Enabled: false Style/RescueStandardError: Enabled: false Style/SafeNavigation: Enabled: false Style/HashEachMethods: Enabled: false Style/HashTransformKeys: Enabled: false Style/HashTransformValues: Enabled: false \ No newline at end of file diff --git a/ruby/tasks.rake b/ruby/tasks.rake index 1ad829d..2d6ea19 100644 --- a/ruby/tasks.rake +++ b/ruby/tasks.rake @@ -1,758 +1,754 @@ # frozen_string_literal: true -require 'rake' require 'date' require 'pp' require 'colored2' ################################################################################################ # constants ROOT_DIR = File.expand_path('.') FINDER_DIR = '/System/Library/CoreServices/Finder.app' FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')].freeze TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') ################################################################################################ # helpers # this is here just IntelliJ to understand colors class String def self.blue Colored2.blue(self) end def self.red Colored2.red(self) end def self.yellow Colored2.yellow(self) end def self.green Colored2.green(self) end def self.cyan Colored2.cyan(self) end def self.magenta Colored2.magenta(self) end def self.bold Colored2.bold(self) end def self.underline Colored2.underline(self) end end def die(msg, status=1) puts red("Error[#{status || $CHILD_STATUS}]: #{msg}").red exit status || $CHILD_STATUS end def sys(cmd) puts "> #{cmd}".yellow system(cmd) end ################################################################################################ # routines def write_file(filename, content) if ENV['dry'] puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" return end File.open(filename, 'w') do |f| f.write content end end def append_file(filename, content) if ENV['dry'] puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" return end File.open(filename, 'a') do |f| f.write content end end def get_list_of_plugins(filter=nil) filter ||= '*' plugins = [] Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| - if File.directory?(file) && File.exist?(File.join(file, File.basename(file) + '.xcodeproj')) + if File.directory?(file) && File.exist?(File.join(file, "#{File.basename(file)}.xcodeproj")) plugins << File.basename(file) end end plugins.uniq end def ack(dir, glob, regexps) glob = File.join(dir, '**{,/*/**}', glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) set = [] Dir.glob(glob) do |file| puts file if ENV['verbose'] content = File.read(file) regexps.each do |r| match = content.scan(r) set.concat match.flatten end end set.sort.uniq end def stitch_broken_strings(strings) strings.map do |s| r = /([^\\])(".*?")/m s.gsub(r) do |_x| Regexp.last_match(1) end end end def extract_menu_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,h}', [ - /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m + /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_code_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,m,h}', [ - /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, - /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,)]/m + /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, + /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,)]/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_ui_strings(folder, xibs) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| xibs.each do |xib| result.concat ack(dir, "#{xib}.xib", [ - /"\^(.*?[^\\])"/m + /"\^(.*?[^\\])"/m ]) end end result.sort.uniq end def parse_strings_file(filename) return [] unless File.exist? filename File.read(filename).lines end def update_strings(old_strings, new_keys, target) removed_count = 0 count = 0 # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings known_keys = [] strings = old_strings.map do |line| match = line =~ /^"(.*?)"/ # it is a valid key-definition line? next line unless match count += 1 if new_keys.include? Regexp.last_match(1) if known_keys.include? Regexp.last_match(1) line = "/* DUPLICIT #{line.strip} */\n" # *** removed_count += 1 else known_keys << Regexp.last_match(1) end else line = "/* REMOVED #{line.strip} */\n" # *** removed_count += 1 end line end to_be_added = new_keys - known_keys write_file(target, strings.join('')) { 'removed_count' => removed_count, 'count' => count, 'new_strings' => new_keys, 'old_strings' => old_strings, 'output' => strings, 'to_be_added' => to_be_added.sort.uniq } end def update_english_strings(project, src_folder, xibs, additional_strings=[]) target = File.join(ENGLISH_LPROJ, "#{project}.strings") code_strings = extract_code_strings(src_folder) ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) new_strings = code_strings.concat(ui_strings).concat(additional_strings) new_strings.sort.uniq! old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end def update_english_menu_strings(src_folder) target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') new_strings = extract_menu_strings(src_folder).map { |s| "MenuItem:#{s}" } old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) xibs = {} # xib naming exceptions that don't follow conventions unconventional = { 'SomeXibName' => 'SomePluginName' } Dir.glob(File.join(dir, '*.xib')) do |file| name = File.basename(file, '.xib') # does the name begin with some plugin name? plugin = plugins.find { |item| item == name || name.start_with?(item) } plugin = unconventional['name'] if plugin.nil? && unconventional['name'] unless plugin.nil? xibs[plugin] ||= [] xibs[plugin] << name next end xibs['SHELL'] ||= [] xibs['SHELL'] << name end xibs end def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) additions = {} plugins.each do |plugin| plugin_dir = File.join(dir, plugin) next unless File.exist? plugin_dir next if xibs[plugin].nil? || xibs[plugin].empty? # an edge case for empty array additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])['to_be_added'] # process just plugin xibs end additions end def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) update_english_strings('TotalFinder', shell_dir, xibs, duplicates) # process just shell xibs end def process_english_menu update_english_menu_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)['to_be_added'] end def get_additions_duplicates(additions) all = [] additions.each do |_k, v| all.concat v end # count occurrences and return only duplicities all.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys.sort.uniq end def insert_additions(list, target) return if list.empty? strings = [] strings << "\n" strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" list.each do |key| value = key.gsub('MenuItem:', '') # MenuItems special case strings << "\"#{key}\" = \"#{value}\";" end append_file(target, strings.join("\n")) puts " #{"+#{list.size}".yellow} in #{target}" end def inprint_strings(source, dest, shared_originals=[]) strings = parse_strings_file(source) originals = [] originals.concat shared_originals originals.concat parse_strings_file(dest) # transform lang back to english index = 0 strings.map! do |line| index += 1 next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) - line = Regexp.last_match(1) + ' = ' + Regexp.last_match(1) + ";\n" + line = "#{Regexp.last_match(1)} = #{Regexp.last_match(1)};\n" line end # replace translations we already know from previous version index = 0 originals.each do |original| index += 1 next unless original.strip[0...1] == '"' original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) rest = Regexp.last_match(3) die "syntax error in #{dest.blue}:#{index} [#{original}]" unless Regexp.last_match(1) && Regexp.last_match(2) strings.map! do |line| - line = needle + ' = ' + haystack + ';' + rest + "\n" if line.starts_with?(needle) + line = "#{needle} = #{haystack};#{rest}\n" if line.start_with?(needle) line end end write_file(dest, strings.join('')) strings end def find_key(key, lines) lines.each do |line| next unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) die "syntax error in [#{line}]" unless Regexp.last_match(1) && Regexp.last_match(2) return haystack if needle == key end nil end def post_process_menu(dest, shared_originals=[]) strings = parse_strings_file(dest) strings.map! do |line| next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) key = Regexp.last_match(1) val = Regexp.last_match(2) rest = Regexp.last_match(3) if key == val # try to lookup existing val translated_val = find_key(key.gsub('MenuItem:', ''), shared_originals) - line = key + ' = ' + translated_val + ';' + rest + "\n" unless translated_val.nil? + line = "#{key} = #{translated_val};#{rest}\n" unless translated_val.nil? end line end File.open(dest, 'w') do |f| f << strings.join end strings end def propagate_english_to_cwd total = 0 # TotalFinder.strings are master files, some strings may move between files all = parse_strings_file File.join(Dir.pwd, 'TotalFinder.strings') Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| next if File.basename(file) == 'TotalFinder.strings' all.concat parse_strings_file(File.join(Dir.pwd, File.basename(file))) end Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| puts " #{File.basename(file)}".yellow total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size end # post-process MenuItems.strings file = 'MenuItems.strings' puts " post processing #{file.yellow}" total += post_process_menu(File.join(Dir.pwd, file), all).size - puts ' -> ' + total.to_s.green + ' strings processed' + puts " -> #{total.to_s.green} strings processed" end def remove_missing_files_in_cwd files1 = Dir.glob(File.join(ENGLISH_LPROJ, '*')).map { |f| File.basename f } files2 = Dir.glob(File.join(Dir.pwd, '*')).map { |f| File.basename f } to_be_deleted = files2 - files1 to_be_deleted.each do |file| puts "deleting '#{file}'".red FileUtils.rm(file) end end def propagate_from_english_to_other_lprojs glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do puts dir.blue propagate_english_to_cwd remove_missing_files_in_cwd end end end def create_localizations_for_project glob = ENV['to'] || '*.lproj' project = ENV['project'] || die('Project name not defined') Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do - write_file(File.join(dir, project + '.strings'), '/* no strings */') + write_file(File.join(dir, "#{project}.strings"), '/* no strings */') end end end def exec_cmd_in_lprojs(cmd) glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| puts dir.blue Dir.chdir dir do sys(cmd) end end end def merge_string_tables Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| puts dir.blue string_files = Dir.glob(File.join(dir, '*.strings')).sort! totalfinder_strings = string_files.filter { |file| /TotalFinder\.strings/.match?(file) } other_strings = string_files.filter { |file| !/TotalFinder\.strings/.match?(file) } - other_strings.each { |strings_file| + other_strings.each do |strings_file| unless /Template\.strings/.match?(strings_file) file_content = File.read(strings_file) strings_file =~ /\/([^\/]*)\.strings/ name = Regexp.last_match(1) contents = [] contents << '' contents << '' contents << "/* --- #{name} --- */" contents << '' contents << file_content content = contents.join("\n") append_file(totalfinder_strings.first, content) end File.delete(strings_file) - } - + end end end def validate_strings_file(path) lines = parse_strings_file(path) in_multi_line_comment = false counter = 0 lines.each do |line| counter += 1 if in_multi_line_comment && line =~ /.*\*\/\w*$/ in_multi_line_comment = false next end next if in_multi_line_comment - line = line.gsub(/\r\n?/, '') + "\n" + line = "#{line.gsub(/\r\n?/, '')}\n" next if line =~ /^".*?"\s*=\s*".*?";\s*$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ next if line =~ /^\/\*.*?\*\/$/ next if line =~ /^\s*$/ if line =~ /^\/\*[^*]*/ in_multi_line_comment = true next end - puts "line ##{counter}: unrecognized pattern".red + ' (fix rakefile if this is a valid pattern)' + puts "#{"line ##{counter}: unrecognized pattern".red} (fix rakefile if this is a valid pattern)" puts line puts "mate -l #{counter} \"#{path}\"".yellow return false end true end def validate_strings_files begin require 'cmess/guess_encoding' rescue LoadError die 'You must "gem install cmess" to use character encoding detection' end glob = ENV['to'] || '*.lproj' counter = 0 failed = 0 warnings = 0 known_files = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*')) do |path| known_files << File.basename(path) end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| unrecognized_files = [] missing_files = known_files.dup Dir.glob(File.join(dir, '*')) do |path| file = File.basename(path) if missing_files.include?(file) missing_files.delete(file) else unrecognized_files << file end end if !missing_files.empty? || !unrecognized_files.empty? warnings += 1 - puts 'in ' + dir.blue + ':' - puts ' missing files: ' + missing_files.join(', ') unless missing_files.empty? - puts ' unrecognized files: ' + unrecognized_files.join(', ') unless unrecognized_files.empty? + puts "in #{dir.blue}:" + puts " missing files: #{missing_files.join(', ')}" unless missing_files.empty? + puts " unrecognized files: #{unrecognized_files.join(', ')}" unless unrecognized_files.empty? end end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, '*.strings')) do |path| counter += 1 ok = 1 input = File.read path charset = 'ASCII' unless input.strip.empty? charset = CMess::GuessEncoding::Automatic.guess(input) ok = ((validate_strings_file path) && ((charset == 'ASCII') || (charset == 'UTF-8'))) end - puts charset.magenta + ' ' + path.blue + ' ' + 'ok'.yellow if ok - puts charset.magenta + ' ' + path.blue + ' ' + 'failed'.red unless ok + puts "#{charset.magenta} #{path.blue} #{'ok'.yellow}" if ok + puts "#{charset.magenta} #{path.blue} #{'failed'.red}" unless ok failed += 1 unless ok end all = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*.strings')) do |file| all.concat parse_strings_file(file) end list = [] all.each do |original| next unless original.strip[0...1] == '"' original =~ /^\s*?"(.*)"\s*?=/ list << Regexp.last_match(1) end dups = list.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys unless dups.empty? puts puts 'found duplicate keys:'.red dups.each { |x| puts " #{x}" } puts puts 'solution:'.yellow + ' shared keys should be placed in TotalFinder.strings'.blue puts end puts '-----------------------------------' - puts 'checked ' + - "#{counter} files".magenta + - ' and ' + - (failed.positive? ? "#{failed} failed".red : 'all is ok'.yellow) + - (warnings.positive? ? " [#{warnings} warnings]".green : '') + failed_msg = (failed.positive? ? "#{failed} failed".red : 'all is ok'.yellow) + warnings_msg = (warnings.positive? ? " [#{warnings} warnings]".green : '') + puts "checked #{"#{counter} files".magenta} and #{failed_msg}#{warnings_msg}" end def stub_installer_lprojs glob = '*.lproj' english_source = File.join(INSTALLER_RESOURCES_DIR, 'en.lproj') die("need #{english_source}!") unless File.exist?(english_source) Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| name = File.basename(dir) next if name == 'en.lproj' full_path = File.join(INSTALLER_RESOURCES_DIR, name) next if File.exist?(full_path) # already have it - puts 'Creating stub ' + full_path.blue + puts "Creating stub #{full_path.blue}" sys("cp -r \"#{english_source}\" \"#{full_path}\"") end end ################################################################################################ # tasks desc 'switch /Applications/TotalFinder.app into dev mode' task :dev do sys('./bin/dev.sh') end desc 'switch /Applications/TotalFinder.app into non-dev mode' task :undev do sys('./bin/undev.sh') end desc 'restart Finder.app' task :restart do sys('./bin/restart.sh') end desc 'normalize Finder.app so it contains all our language folders (run with sudo)' task :normalize do lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') Dir.glob(lprojs) do |folder| dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) if File.exist? dir puts dir.blue + ' exists'.yellow else die('Unable to create a folder. Hint: you should run this as sudo rake normalize') unless sys("mkdir -p \"#{dir}\"") puts dir.blue + ' created'.green end end end desc 'cherrypicks strings from sources and applies missing strings to en.lproj' task :cherrypick do die 'install ack 2.0+ | for example via homebrew:> brew install ack' if `which ack` == '' die 'upgrade your ack to 2.0+ | for example via homebrew:> brew install ack' unless `ack --version` =~ /ack 2/ plugins = get_list_of_plugins xibs = categorize_xibs(plugins) puts 'XIBs:'.blue pp xibs puts puts 'Processing string files:'.yellow # additions is a hash containing an array of added translation keys for each plugin additions = process_english_strings_in_plugins(plugins, xibs) duplicates = get_additions_duplicates(additions) res = process_english_strings_in_shell(xibs['SHELL'], duplicates) # duplicates will be moved into shell shell_additions = res['to_be_added'] shell_new_strings = res['new_strings'] menu_additions = process_english_menu # insert additions to plugins plugins.each do |plugin| next unless additions[plugin] target = File.join(ENGLISH_LPROJ, "#{plugin}.strings") list = additions[plugin] - duplicates - shell_new_strings insert_additions(list, target) end # insert additions to shell target = File.join(ENGLISH_LPROJ, 'TotalFinder.strings') insert_additions(shell_additions, target) # insert additions to menu items target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') insert_additions(menu_additions, target) unhandled_duplicates = duplicates - shell_new_strings unless unhandled_duplicates.empty? puts puts 'Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:'.yellow puts unhandled_duplicates.join(', ').magenta end end desc 'propagates structure of en.lproj to all other language folders while keeping already translated strings' task :propagate do propagate_from_english_to_other_lprojs end desc 'make stub lproj folders for installer, creates all which exist in plugin' task :stub do stub_installer_lprojs end desc 'exec command in all lproj folders' task :exec do exec_cmd_in_lprojs(ENV['cmd'] || 'ls') end desc 'validates all strings files and checks them for syntax errors' task :validate do validate_strings_files end desc 'validates all strings files and checks them for syntax errors' task :create_localization do create_localizations_for_project end desc 'merge all string tables into single TotalFinder.strings' task :merge_string_tables do merge_string_tables end task default: :restart
binaryage/totalfinder-i18n
d579abc8a8d092dff3e65ad0b24095c450269fc6
uninstaller: fix broken uninstaller/he.lproj/Localizable.strings
diff --git a/uninstaller/he.lproj/Localizable.strings b/uninstaller/he.lproj/Localizable.strings index 685f7d1..70bff96 100644 --- a/uninstaller/he.lproj/Localizable.strings +++ b/uninstaller/he.lproj/Localizable.strings @@ -1,23 +1,23 @@ /* buttons */ "Quit" = "יציאה"; "Cancel" = "ביטול"; "Uninstall" = "הסרה"; "Details" = "פרטים"; /* tooltips */ "Show detailed transcript" = "הצג תעתיק מפורט"; /* main texts */ "You are about uninstall *APP*" = "הנך עומד להסיר את TotalFinder"; -"This program will uninstall all *APP* components from this computer." = "תוכנית זו תסיר את כל רכיבי TotalFinder ממחשב זה.; +"This program will uninstall all *APP* components from this computer." = "תוכנית זו תסיר את כל רכיבי TotalFinder ממחשב זה."; "*APP* has been uninstalled" = "הסרת TotalFinder הסתיימה בהצלחה"; "Thank you for trying *APP*." = "Thank you for trying TotalFinder."; "*APP* uninstallation failed" = "הסרת TotalFinder נכשלה"; "The uninstall script encountered problems. Please see the details. Please report bugs to support@binaryage.com." = "סקריפט ההסרה נתקל בתקלות. אנא ראו הפרטים. נשמח אם תדווחו על באגים לכתובת support@binaryage.com."; /* possible script messages in details section */ "Uninstaller needs admin privileges to remove *APP* from your system." = "לאשף ההסרה דרושה פריבילגית מנהל המערכת על מנת להסיר את TotalFinder מהמערכת שלכם."; "Running uninstall script:\n" = "מריץ סקריפט הסרה:\n"; "Uninstall script finished successfully.\n" = "סקריפט הסרה סיים בהצלחה.\n"; "Uninstall script needs admin rights.\n" = "סקריפט ההסרה דורש זכויות של מנהל מערכת.\n"; -"Uninstall script failed with error [%d].\n" = "סקריפט ההסרה נכשל עם שגיאה [%d].\n"; \ No newline at end of file +"Uninstall script failed with error [%d].\n" = "סקריפט ההסרה נכשל עם שגיאה [%d].\n";
binaryage/totalfinder-i18n
094f9b6d97a52ae3dce110bee38978250c64b335
ruby: implement merge_string_tables task
diff --git a/ruby/tasks.rake b/ruby/tasks.rake index 91d5028..1ad829d 100644 --- a/ruby/tasks.rake +++ b/ruby/tasks.rake @@ -1,721 +1,758 @@ # frozen_string_literal: true require 'rake' require 'date' require 'pp' require 'colored2' ################################################################################################ # constants ROOT_DIR = File.expand_path('.') FINDER_DIR = '/System/Library/CoreServices/Finder.app' FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')].freeze TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') ################################################################################################ # helpers # this is here just IntelliJ to understand colors class String def self.blue Colored2.blue(self) end def self.red Colored2.red(self) end def self.yellow Colored2.yellow(self) end def self.green Colored2.green(self) end def self.cyan Colored2.cyan(self) end def self.magenta Colored2.magenta(self) end def self.bold Colored2.bold(self) end def self.underline Colored2.underline(self) end end def die(msg, status=1) puts red("Error[#{status || $CHILD_STATUS}]: #{msg}").red exit status || $CHILD_STATUS end def sys(cmd) puts "> #{cmd}".yellow system(cmd) end ################################################################################################ # routines def write_file(filename, content) if ENV['dry'] puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" return end File.open(filename, 'w') do |f| f.write content end end def append_file(filename, content) if ENV['dry'] puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" return end File.open(filename, 'a') do |f| f.write content end end def get_list_of_plugins(filter=nil) filter ||= '*' plugins = [] Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| if File.directory?(file) && File.exist?(File.join(file, File.basename(file) + '.xcodeproj')) plugins << File.basename(file) end end plugins.uniq end def ack(dir, glob, regexps) glob = File.join(dir, '**{,/*/**}', glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) set = [] Dir.glob(glob) do |file| puts file if ENV['verbose'] content = File.read(file) regexps.each do |r| match = content.scan(r) set.concat match.flatten end end set.sort.uniq end def stitch_broken_strings(strings) strings.map do |s| r = /([^\\])(".*?")/m s.gsub(r) do |_x| Regexp.last_match(1) end end end def extract_menu_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,h}', [ /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_code_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,m,h}', [ /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,)]/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_ui_strings(folder, xibs) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| xibs.each do |xib| result.concat ack(dir, "#{xib}.xib", [ /"\^(.*?[^\\])"/m ]) end end result.sort.uniq end def parse_strings_file(filename) return [] unless File.exist? filename File.read(filename).lines end def update_strings(old_strings, new_keys, target) removed_count = 0 count = 0 # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings known_keys = [] strings = old_strings.map do |line| match = line =~ /^"(.*?)"/ # it is a valid key-definition line? next line unless match count += 1 if new_keys.include? Regexp.last_match(1) if known_keys.include? Regexp.last_match(1) line = "/* DUPLICIT #{line.strip} */\n" # *** removed_count += 1 else known_keys << Regexp.last_match(1) end else line = "/* REMOVED #{line.strip} */\n" # *** removed_count += 1 end line end to_be_added = new_keys - known_keys write_file(target, strings.join('')) { 'removed_count' => removed_count, 'count' => count, 'new_strings' => new_keys, 'old_strings' => old_strings, 'output' => strings, 'to_be_added' => to_be_added.sort.uniq } end def update_english_strings(project, src_folder, xibs, additional_strings=[]) target = File.join(ENGLISH_LPROJ, "#{project}.strings") code_strings = extract_code_strings(src_folder) ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) new_strings = code_strings.concat(ui_strings).concat(additional_strings) new_strings.sort.uniq! old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end def update_english_menu_strings(src_folder) target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') new_strings = extract_menu_strings(src_folder).map { |s| "MenuItem:#{s}" } old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) xibs = {} # xib naming exceptions that don't follow conventions unconventional = { 'SomeXibName' => 'SomePluginName' } Dir.glob(File.join(dir, '*.xib')) do |file| name = File.basename(file, '.xib') # does the name begin with some plugin name? plugin = plugins.find { |item| item == name || name.start_with?(item) } plugin = unconventional['name'] if plugin.nil? && unconventional['name'] unless plugin.nil? xibs[plugin] ||= [] xibs[plugin] << name next end xibs['SHELL'] ||= [] xibs['SHELL'] << name end xibs end def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) additions = {} plugins.each do |plugin| plugin_dir = File.join(dir, plugin) next unless File.exist? plugin_dir next if xibs[plugin].nil? || xibs[plugin].empty? # an edge case for empty array additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])['to_be_added'] # process just plugin xibs end additions end def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) update_english_strings('TotalFinder', shell_dir, xibs, duplicates) # process just shell xibs end def process_english_menu update_english_menu_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)['to_be_added'] end def get_additions_duplicates(additions) all = [] additions.each do |_k, v| all.concat v end # count occurrences and return only duplicities all.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys.sort.uniq end def insert_additions(list, target) return if list.empty? strings = [] strings << "\n" strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" list.each do |key| value = key.gsub('MenuItem:', '') # MenuItems special case strings << "\"#{key}\" = \"#{value}\";" end append_file(target, strings.join("\n")) puts " #{"+#{list.size}".yellow} in #{target}" end def inprint_strings(source, dest, shared_originals=[]) strings = parse_strings_file(source) originals = [] originals.concat shared_originals originals.concat parse_strings_file(dest) # transform lang back to english index = 0 strings.map! do |line| index += 1 next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) line = Regexp.last_match(1) + ' = ' + Regexp.last_match(1) + ";\n" line end # replace translations we already know from previous version index = 0 originals.each do |original| index += 1 next unless original.strip[0...1] == '"' original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) rest = Regexp.last_match(3) die "syntax error in #{dest.blue}:#{index} [#{original}]" unless Regexp.last_match(1) && Regexp.last_match(2) strings.map! do |line| line = needle + ' = ' + haystack + ';' + rest + "\n" if line.starts_with?(needle) line end end write_file(dest, strings.join('')) strings end def find_key(key, lines) lines.each do |line| next unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) die "syntax error in [#{line}]" unless Regexp.last_match(1) && Regexp.last_match(2) return haystack if needle == key end nil end def post_process_menu(dest, shared_originals=[]) strings = parse_strings_file(dest) strings.map! do |line| next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) key = Regexp.last_match(1) val = Regexp.last_match(2) rest = Regexp.last_match(3) if key == val # try to lookup existing val translated_val = find_key(key.gsub('MenuItem:', ''), shared_originals) line = key + ' = ' + translated_val + ';' + rest + "\n" unless translated_val.nil? end line end File.open(dest, 'w') do |f| f << strings.join end strings end def propagate_english_to_cwd total = 0 # TotalFinder.strings are master files, some strings may move between files all = parse_strings_file File.join(Dir.pwd, 'TotalFinder.strings') Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| next if File.basename(file) == 'TotalFinder.strings' all.concat parse_strings_file(File.join(Dir.pwd, File.basename(file))) end Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| puts " #{File.basename(file)}".yellow total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size end # post-process MenuItems.strings file = 'MenuItems.strings' puts " post processing #{file.yellow}" total += post_process_menu(File.join(Dir.pwd, file), all).size puts ' -> ' + total.to_s.green + ' strings processed' end def remove_missing_files_in_cwd files1 = Dir.glob(File.join(ENGLISH_LPROJ, '*')).map { |f| File.basename f } files2 = Dir.glob(File.join(Dir.pwd, '*')).map { |f| File.basename f } to_be_deleted = files2 - files1 to_be_deleted.each do |file| puts "deleting '#{file}'".red FileUtils.rm(file) end end def propagate_from_english_to_other_lprojs glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do puts dir.blue propagate_english_to_cwd remove_missing_files_in_cwd end end end def create_localizations_for_project glob = ENV['to'] || '*.lproj' project = ENV['project'] || die('Project name not defined') Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do write_file(File.join(dir, project + '.strings'), '/* no strings */') end end end def exec_cmd_in_lprojs(cmd) glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| puts dir.blue Dir.chdir dir do sys(cmd) end end end +def merge_string_tables + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| + puts dir.blue + + string_files = Dir.glob(File.join(dir, '*.strings')).sort! + totalfinder_strings = string_files.filter { |file| /TotalFinder\.strings/.match?(file) } + other_strings = string_files.filter { |file| !/TotalFinder\.strings/.match?(file) } + + other_strings.each { |strings_file| + unless /Template\.strings/.match?(strings_file) + file_content = File.read(strings_file) + + strings_file =~ /\/([^\/]*)\.strings/ + name = Regexp.last_match(1) + + contents = [] + contents << '' + contents << '' + contents << "/* --- #{name} --- */" + contents << '' + contents << file_content + content = contents.join("\n") + + append_file(totalfinder_strings.first, content) + end + + File.delete(strings_file) + } + + end +end + def validate_strings_file(path) lines = parse_strings_file(path) in_multi_line_comment = false counter = 0 lines.each do |line| counter += 1 if in_multi_line_comment && line =~ /.*\*\/\w*$/ in_multi_line_comment = false next end next if in_multi_line_comment line = line.gsub(/\r\n?/, '') + "\n" next if line =~ /^".*?"\s*=\s*".*?";\s*$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ next if line =~ /^\/\*.*?\*\/$/ next if line =~ /^\s*$/ if line =~ /^\/\*[^*]*/ in_multi_line_comment = true next end puts "line ##{counter}: unrecognized pattern".red + ' (fix rakefile if this is a valid pattern)' puts line puts "mate -l #{counter} \"#{path}\"".yellow return false end true end def validate_strings_files begin require 'cmess/guess_encoding' rescue LoadError die 'You must "gem install cmess" to use character encoding detection' end glob = ENV['to'] || '*.lproj' counter = 0 failed = 0 warnings = 0 known_files = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*')) do |path| known_files << File.basename(path) end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| unrecognized_files = [] missing_files = known_files.dup Dir.glob(File.join(dir, '*')) do |path| file = File.basename(path) if missing_files.include?(file) missing_files.delete(file) else unrecognized_files << file end end if !missing_files.empty? || !unrecognized_files.empty? warnings += 1 puts 'in ' + dir.blue + ':' puts ' missing files: ' + missing_files.join(', ') unless missing_files.empty? puts ' unrecognized files: ' + unrecognized_files.join(', ') unless unrecognized_files.empty? end end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, '*.strings')) do |path| counter += 1 ok = 1 input = File.read path charset = 'ASCII' unless input.strip.empty? charset = CMess::GuessEncoding::Automatic.guess(input) ok = ((validate_strings_file path) && ((charset == 'ASCII') || (charset == 'UTF-8'))) end puts charset.magenta + ' ' + path.blue + ' ' + 'ok'.yellow if ok puts charset.magenta + ' ' + path.blue + ' ' + 'failed'.red unless ok failed += 1 unless ok end all = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*.strings')) do |file| all.concat parse_strings_file(file) end list = [] all.each do |original| next unless original.strip[0...1] == '"' original =~ /^\s*?"(.*)"\s*?=/ list << Regexp.last_match(1) end dups = list.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys unless dups.empty? puts puts 'found duplicate keys:'.red dups.each { |x| puts " #{x}" } puts puts 'solution:'.yellow + ' shared keys should be placed in TotalFinder.strings'.blue puts end puts '-----------------------------------' puts 'checked ' + "#{counter} files".magenta + ' and ' + (failed.positive? ? "#{failed} failed".red : 'all is ok'.yellow) + (warnings.positive? ? " [#{warnings} warnings]".green : '') end def stub_installer_lprojs glob = '*.lproj' english_source = File.join(INSTALLER_RESOURCES_DIR, 'en.lproj') die("need #{english_source}!") unless File.exist?(english_source) Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| name = File.basename(dir) next if name == 'en.lproj' full_path = File.join(INSTALLER_RESOURCES_DIR, name) next if File.exist?(full_path) # already have it puts 'Creating stub ' + full_path.blue sys("cp -r \"#{english_source}\" \"#{full_path}\"") end end ################################################################################################ # tasks desc 'switch /Applications/TotalFinder.app into dev mode' task :dev do sys('./bin/dev.sh') end desc 'switch /Applications/TotalFinder.app into non-dev mode' task :undev do sys('./bin/undev.sh') end desc 'restart Finder.app' task :restart do sys('./bin/restart.sh') end desc 'normalize Finder.app so it contains all our language folders (run with sudo)' task :normalize do lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') Dir.glob(lprojs) do |folder| dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) if File.exist? dir puts dir.blue + ' exists'.yellow else die('Unable to create a folder. Hint: you should run this as sudo rake normalize') unless sys("mkdir -p \"#{dir}\"") puts dir.blue + ' created'.green end end end desc 'cherrypicks strings from sources and applies missing strings to en.lproj' task :cherrypick do die 'install ack 2.0+ | for example via homebrew:> brew install ack' if `which ack` == '' die 'upgrade your ack to 2.0+ | for example via homebrew:> brew install ack' unless `ack --version` =~ /ack 2/ plugins = get_list_of_plugins xibs = categorize_xibs(plugins) puts 'XIBs:'.blue pp xibs puts puts 'Processing string files:'.yellow # additions is a hash containing an array of added translation keys for each plugin additions = process_english_strings_in_plugins(plugins, xibs) duplicates = get_additions_duplicates(additions) res = process_english_strings_in_shell(xibs['SHELL'], duplicates) # duplicates will be moved into shell shell_additions = res['to_be_added'] shell_new_strings = res['new_strings'] menu_additions = process_english_menu # insert additions to plugins plugins.each do |plugin| next unless additions[plugin] target = File.join(ENGLISH_LPROJ, "#{plugin}.strings") list = additions[plugin] - duplicates - shell_new_strings insert_additions(list, target) end # insert additions to shell target = File.join(ENGLISH_LPROJ, 'TotalFinder.strings') insert_additions(shell_additions, target) # insert additions to menu items target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') insert_additions(menu_additions, target) unhandled_duplicates = duplicates - shell_new_strings unless unhandled_duplicates.empty? puts puts 'Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:'.yellow puts unhandled_duplicates.join(', ').magenta end end desc 'propagates structure of en.lproj to all other language folders while keeping already translated strings' task :propagate do propagate_from_english_to_other_lprojs end desc 'make stub lproj folders for installer, creates all which exist in plugin' task :stub do stub_installer_lprojs end desc 'exec command in all lproj folders' task :exec do exec_cmd_in_lprojs(ENV['cmd'] || 'ls') end desc 'validates all strings files and checks them for syntax errors' task :validate do validate_strings_files end desc 'validates all strings files and checks them for syntax errors' task :create_localization do create_localizations_for_project end +desc 'merge all string tables into single TotalFinder.strings' +task :merge_string_tables do + merge_string_tables +end + task default: :restart
binaryage/totalfinder-i18n
ecbf6931e6039755b5f1fc6e459e973ac2534b58
ruby: make rubocop happy
diff --git a/ruby/tasks.rake b/ruby/tasks.rake index fec4cfe..91d5028 100644 --- a/ruby/tasks.rake +++ b/ruby/tasks.rake @@ -1,704 +1,721 @@ # frozen_string_literal: true -require 'date' require 'rake' +require 'date' require 'pp' +require 'colored2' ################################################################################################ # constants ROOT_DIR = File.expand_path('.') FINDER_DIR = '/System/Library/CoreServices/Finder.app' FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')].freeze TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') ################################################################################################ -# dependencies +# helpers -begin - require 'colored' -rescue LoadError - raise 'You must "gem install colored" to use terminal colors' -end +# this is here just IntelliJ to understand colors +class String + def self.blue + Colored2.blue(self) + end -################################################################################################ -# helpers + def self.red + Colored2.red(self) + end + + def self.yellow + Colored2.yellow(self) + end + + def self.green + Colored2.green(self) + end + + def self.cyan + Colored2.cyan(self) + end + + def self.magenta + Colored2.magenta(self) + end + + def self.bold + Colored2.bold(self) + end + + def self.underline + Colored2.underline(self) + end +end def die(msg, status=1) - puts "Error[#{status || $CHILD_STATUS}]: #{msg}".red + puts red("Error[#{status || $CHILD_STATUS}]: #{msg}").red exit status || $CHILD_STATUS end def sys(cmd) puts "> #{cmd}".yellow system(cmd) end ################################################################################################ # routines def write_file(filename, content) if ENV['dry'] puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" return end File.open(filename, 'w') do |f| f.write content end end def append_file(filename, content) if ENV['dry'] puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" return end File.open(filename, 'a') do |f| f.write content end end def get_list_of_plugins(filter=nil) filter ||= '*' plugins = [] Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| if File.directory?(file) && File.exist?(File.join(file, File.basename(file) + '.xcodeproj')) plugins << File.basename(file) end end plugins.uniq end def ack(dir, glob, regexps) glob = File.join(dir, '**{,/*/**}', glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) set = [] Dir.glob(glob) do |file| puts file if ENV['verbose'] content = File.read(file) regexps.each do |r| match = content.scan(r) set.concat match.flatten end end set.sort.uniq end def stitch_broken_strings(strings) - # example of broken string - # "This option will effectively disable the tabs module in TotalFinder. In effect the dual mode and visor functionality will be " - # "disabled as well. This may be desired under Mavericks - use native Finder tabs " - # "exclusively while keeping benefits of other TotalFinder features.\n\nFor this operation Finder has to be restarted!\nNote: " - # "Prior restarting please finish all Finder tasks in progress (like copying or " - # "moving files)." - strings.map do |s| r = /([^\\])(".*?")/m s.gsub(r) do |_x| Regexp.last_match(1) end end end -def extract_menuitems_strings(folder) +def extract_menu_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,h}', [ /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_code_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| result.concat ack(dir, '*.{cpp,mm,m,h}', [ /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, - /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,\)]/m + /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,)]/m ]) end stitch_broken_strings(result.sort.uniq) end def extract_ui_strings(folder, xibs) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| xibs.each do |xib| result.concat ack(dir, "#{xib}.xib", [ /"\^(.*?[^\\])"/m ]) end end result.sort.uniq end def parse_strings_file(filename) return [] unless File.exist? filename File.read(filename).lines end def update_strings(old_strings, new_keys, target) removed_count = 0 count = 0 # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings known_keys = [] strings = old_strings.map do |line| match = line =~ /^"(.*?)"/ # it is a valid key-definition line? next line unless match count += 1 if new_keys.include? Regexp.last_match(1) if known_keys.include? Regexp.last_match(1) line = "/* DUPLICIT #{line.strip} */\n" # *** removed_count += 1 else known_keys << Regexp.last_match(1) end else line = "/* REMOVED #{line.strip} */\n" # *** removed_count += 1 end line end to_be_added = new_keys - known_keys write_file(target, strings.join('')) { 'removed_count' => removed_count, 'count' => count, 'new_strings' => new_keys, 'old_strings' => old_strings, 'output' => strings, 'to_be_added' => to_be_added.sort.uniq } end def update_english_strings(project, src_folder, xibs, additional_strings=[]) target = File.join(ENGLISH_LPROJ, "#{project}.strings") code_strings = extract_code_strings(src_folder) ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) new_strings = code_strings.concat(ui_strings).concat(additional_strings) new_strings.sort.uniq! old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] - strings = res['output'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end -def update_english_menuitems_strings(src_folder) +def update_english_menu_strings(src_folder) target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') - new_strings = extract_menuitems_strings(src_folder).map { |s| "MenuItem:#{s}" } + new_strings = extract_menu_strings(src_folder).map { |s| "MenuItem:#{s}" } old_strings = parse_strings_file(target) res = update_strings(old_strings, new_strings, target) removed_count = res['removed_count'] - strings = res['output'] count = res['count'] puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" res end def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) xibs = {} # xib naming exceptions that don't follow conventions unconventional = { 'SomeXibName' => 'SomePluginName' } Dir.glob(File.join(dir, '*.xib')) do |file| name = File.basename(file, '.xib') # does the name begin with some plugin name? - plugin = plugins.find { |plugin| (plugin == name) || (name.index(plugin) == 0) } + plugin = plugins.find { |item| item == name || name.start_with?(item) } plugin = unconventional['name'] if plugin.nil? && unconventional['name'] unless plugin.nil? xibs[plugin] ||= [] xibs[plugin] << name next end xibs['SHELL'] ||= [] xibs['SHELL'] << name end xibs end def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) additions = {} plugins.each do |plugin| plugin_dir = File.join(dir, plugin) next unless File.exist? plugin_dir next if xibs[plugin].nil? || xibs[plugin].empty? # an edge case for empty array additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])['to_be_added'] # process just plugin xibs end additions end def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) update_english_strings('TotalFinder', shell_dir, xibs, duplicates) # process just shell xibs end -def process_english_menuitems - update_english_menuitems_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)['to_be_added'] +def process_english_menu + update_english_menu_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)['to_be_added'] end def get_additions_duplicates(additions) all = [] additions.each do |_k, v| all.concat v end - # count occurences and return only duplicities + # count occurrences and return only duplicities all.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys.sort.uniq end def insert_additions(list, target) return if list.empty? strings = [] strings << "\n" strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" list.each do |key| value = key.gsub('MenuItem:', '') # MenuItems special case strings << "\"#{key}\" = \"#{value}\";" end append_file(target, strings.join("\n")) puts " #{"+#{list.size}".yellow} in #{target}" end def inprint_strings(source, dest, shared_originals=[]) strings = parse_strings_file(source) originals = [] originals.concat shared_originals originals.concat parse_strings_file(dest) # transform lang back to english index = 0 strings.map! do |line| index += 1 next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) line = Regexp.last_match(1) + ' = ' + Regexp.last_match(1) + ";\n" line end - # replace translations we already know from previsous version + # replace translations we already know from previous version index = 0 originals.each do |original| index += 1 next unless original.strip[0...1] == '"' original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) rest = Regexp.last_match(3) die "syntax error in #{dest.blue}:#{index} [#{original}]" unless Regexp.last_match(1) && Regexp.last_match(2) - found = false strings.map! do |line| - if (line.index needle) == 0 - line = needle + ' = ' + haystack + ';' + rest + "\n" - found = true - end + line = needle + ' = ' + haystack + ';' + rest + "\n" if line.starts_with?(needle) line end end write_file(dest, strings.join('')) strings end def find_key(key, lines) lines.each do |line| next unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ needle = Regexp.last_match(1) haystack = Regexp.last_match(2) - die "syntax error in #{dest.blue}:#{index} [#{line}]" unless Regexp.last_match(1) && Regexp.last_match(2) + die "syntax error in [#{line}]" unless Regexp.last_match(1) && Regexp.last_match(2) return haystack if needle == key end nil end -def post_process_menuitems(dest, shared_originals=[]) +def post_process_menu(dest, shared_originals=[]) strings = parse_strings_file(dest) strings.map! do |line| next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) key = Regexp.last_match(1) val = Regexp.last_match(2) rest = Regexp.last_match(3) if key == val - # try to lookup exitsting val + # try to lookup existing val translated_val = find_key(key.gsub('MenuItem:', ''), shared_originals) line = key + ' = ' + translated_val + ';' + rest + "\n" unless translated_val.nil? end line end File.open(dest, 'w') do |f| f << strings.join end strings end def propagate_english_to_cwd total = 0 # TotalFinder.strings are master files, some strings may move between files all = parse_strings_file File.join(Dir.pwd, 'TotalFinder.strings') Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| next if File.basename(file) == 'TotalFinder.strings' all.concat parse_strings_file(File.join(Dir.pwd, File.basename(file))) end Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| puts " #{File.basename(file)}".yellow total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size end # post-process MenuItems.strings file = 'MenuItems.strings' puts " post processing #{file.yellow}" - total += post_process_menuitems(File.join(Dir.pwd, file), all).size + total += post_process_menu(File.join(Dir.pwd, file), all).size puts ' -> ' + total.to_s.green + ' strings processed' end def remove_missing_files_in_cwd files1 = Dir.glob(File.join(ENGLISH_LPROJ, '*')).map { |f| File.basename f } files2 = Dir.glob(File.join(Dir.pwd, '*')).map { |f| File.basename f } to_be_deleted = files2 - files1 to_be_deleted.each do |file| puts "deleting '#{file}'".red FileUtils.rm(file) end end def propagate_from_english_to_other_lprojs glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do puts dir.blue propagate_english_to_cwd remove_missing_files_in_cwd end end end def create_localizations_for_project glob = ENV['to'] || '*.lproj' project = ENV['project'] || die('Project name not defined') Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do write_file(File.join(dir, project + '.strings'), '/* no strings */') end end end def exec_cmd_in_lprojs(cmd) glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| puts dir.blue Dir.chdir dir do sys(cmd) end end end def validate_strings_file(path) lines = parse_strings_file(path) in_multi_line_comment = false counter = 0 - count = lines.size lines.each do |line| counter += 1 if in_multi_line_comment && line =~ /.*\*\/\w*$/ in_multi_line_comment = false next end next if in_multi_line_comment line = line.gsub(/\r\n?/, '') + "\n" next if line =~ /^".*?"\s*=\s*".*?";\s*$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ next if line =~ /^\/\*.*?\*\/$/ next if line =~ /^\s*$/ - if line =~ /^\/\*[^\*]*/ + if line =~ /^\/\*[^*]*/ in_multi_line_comment = true next end puts "line ##{counter}: unrecognized pattern".red + ' (fix rakefile if this is a valid pattern)' puts line puts "mate -l #{counter} \"#{path}\"".yellow return false end true end def validate_strings_files begin require 'cmess/guess_encoding' rescue LoadError die 'You must "gem install cmess" to use character encoding detection' end glob = ENV['to'] || '*.lproj' counter = 0 failed = 0 warnings = 0 known_files = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*')) do |path| known_files << File.basename(path) end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| unrecognized_files = [] missing_files = known_files.dup Dir.glob(File.join(dir, '*')) do |path| file = File.basename(path) if missing_files.include?(file) missing_files.delete(file) else unrecognized_files << file end end if !missing_files.empty? || !unrecognized_files.empty? warnings += 1 puts 'in ' + dir.blue + ':' puts ' missing files: ' + missing_files.join(', ') unless missing_files.empty? puts ' unrecognized files: ' + unrecognized_files.join(', ') unless unrecognized_files.empty? end end Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, '*.strings')) do |path| counter += 1 ok = 1 input = File.read path charset = 'ASCII' unless input.strip.empty? charset = CMess::GuessEncoding::Automatic.guess(input) ok = ((validate_strings_file path) && ((charset == 'ASCII') || (charset == 'UTF-8'))) end puts charset.magenta + ' ' + path.blue + ' ' + 'ok'.yellow if ok puts charset.magenta + ' ' + path.blue + ' ' + 'failed'.red unless ok failed += 1 unless ok end all = [] Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*.strings')) do |file| all.concat parse_strings_file(file) end list = [] all.each do |original| next unless original.strip[0...1] == '"' original =~ /^\s*?"(.*)"\s*?=/ list << Regexp.last_match(1) end dups = list.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys unless dups.empty? puts puts 'found duplicate keys:'.red dups.each { |x| puts " #{x}" } puts puts 'solution:'.yellow + ' shared keys should be placed in TotalFinder.strings'.blue puts end puts '-----------------------------------' - puts 'checked ' + "#{counter} files".magenta + ' and ' + (failed > 0 ? "#{failed} failed".red : 'all is ok'.yellow) + (warnings > 0 ? " [#{warnings} warnings]".green : '') + puts 'checked ' + + "#{counter} files".magenta + + ' and ' + + (failed.positive? ? "#{failed} failed".red : 'all is ok'.yellow) + + (warnings.positive? ? " [#{warnings} warnings]".green : '') end def stub_installer_lprojs glob = '*.lproj' english_source = File.join(INSTALLER_RESOURCES_DIR, 'en.lproj') die("need #{english_source}!") unless File.exist?(english_source) Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| name = File.basename(dir) next if name == 'en.lproj' full_path = File.join(INSTALLER_RESOURCES_DIR, name) next if File.exist?(full_path) # already have it puts 'Creating stub ' + full_path.blue sys("cp -r \"#{english_source}\" \"#{full_path}\"") end end ################################################################################################ # tasks desc 'switch /Applications/TotalFinder.app into dev mode' task :dev do sys('./bin/dev.sh') end desc 'switch /Applications/TotalFinder.app into non-dev mode' task :undev do sys('./bin/undev.sh') end desc 'restart Finder.app' task :restart do sys('./bin/restart.sh') end desc 'normalize Finder.app so it contains all our language folders (run with sudo)' task :normalize do lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') Dir.glob(lprojs) do |folder| dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) if File.exist? dir puts dir.blue + ' exists'.yellow else die('Unable to create a folder. Hint: you should run this as sudo rake normalize') unless sys("mkdir -p \"#{dir}\"") puts dir.blue + ' created'.green end end end desc 'cherrypicks strings from sources and applies missing strings to en.lproj' task :cherrypick do die 'install ack 2.0+ | for example via homebrew:> brew install ack' if `which ack` == '' die 'upgrade your ack to 2.0+ | for example via homebrew:> brew install ack' unless `ack --version` =~ /ack 2/ plugins = get_list_of_plugins xibs = categorize_xibs(plugins) puts 'XIBs:'.blue pp xibs puts puts 'Processing string files:'.yellow - # additons is a hash containing an array of added translation keys for each plugin + # additions is a hash containing an array of added translation keys for each plugin additions = process_english_strings_in_plugins(plugins, xibs) duplicates = get_additions_duplicates(additions) res = process_english_strings_in_shell(xibs['SHELL'], duplicates) # duplicates will be moved into shell shell_additions = res['to_be_added'] shell_new_strings = res['new_strings'] - menuitems_additions = process_english_menuitems + menu_additions = process_english_menu # insert additions to plugins plugins.each do |plugin| next unless additions[plugin] target = File.join(ENGLISH_LPROJ, "#{plugin}.strings") list = additions[plugin] - duplicates - shell_new_strings insert_additions(list, target) end # insert additions to shell target = File.join(ENGLISH_LPROJ, 'TotalFinder.strings') insert_additions(shell_additions, target) # insert additions to menu items target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') - insert_additions(menuitems_additions, target) + insert_additions(menu_additions, target) unhandled_duplicates = duplicates - shell_new_strings unless unhandled_duplicates.empty? puts puts 'Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:'.yellow puts unhandled_duplicates.join(', ').magenta end end desc 'propagates structure of en.lproj to all other language folders while keeping already translated strings' task :propagate do propagate_from_english_to_other_lprojs end desc 'make stub lproj folders for installer, creates all which exist in plugin' task :stub do stub_installer_lprojs end desc 'exec command in all lproj folders' task :exec do exec_cmd_in_lprojs(ENV['cmd'] || 'ls') end desc 'validates all strings files and checks them for syntax errors' task :validate do validate_strings_files end desc 'validates all strings files and checks them for syntax errors' task :create_localization do create_localizations_for_project end task default: :restart
binaryage/totalfinder-i18n
70ed3f534354e65212d8759dc7df29a131e943ab
ruby: apply automatic rubocop fixes
diff --git a/ruby/tasks.rake b/ruby/tasks.rake index 2373013..fec4cfe 100644 --- a/ruby/tasks.rake +++ b/ruby/tasks.rake @@ -1,703 +1,704 @@ +# frozen_string_literal: true + require 'date' require 'rake' require 'pp' ################################################################################################ # constants ROOT_DIR = File.expand_path('.') FINDER_DIR = '/System/Library/CoreServices/Finder.app' FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') -SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')] +SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')].freeze TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') ################################################################################################ # dependencies begin require 'colored' rescue LoadError raise 'You must "gem install colored" to use terminal colors' end ################################################################################################ # helpers def die(msg, status=1) - puts "Error[#{status||$?}]: #{msg}".red - exit status||$? + puts "Error[#{status || $CHILD_STATUS}]: #{msg}".red + exit status || $CHILD_STATUS end def sys(cmd) puts "> #{cmd}".yellow system(cmd) end ################################################################################################ # routines def write_file(filename, content) - if ENV["dry"] then + if ENV['dry'] puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" return end - - File.open(filename, "w") do |f| + + File.open(filename, 'w') do |f| f.write content end end def append_file(filename, content) - if ENV["dry"] then + if ENV['dry'] puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" return end - - File.open(filename, "a") do |f| + + File.open(filename, 'a') do |f| f.write content end end def get_list_of_plugins(filter=nil) - filter = "*" unless filter + filter ||= '*' plugins = [] Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| - if File.directory?(file) and File.exists? File.join(file, File.basename(file)+".xcodeproj") then + if File.directory?(file) && File.exist?(File.join(file, File.basename(file) + '.xcodeproj')) plugins << File.basename(file) end end plugins.uniq end def ack(dir, glob, regexps) - glob = File.join(dir, "**{,/*/**}", glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) + glob = File.join(dir, '**{,/*/**}', glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) set = [] Dir.glob(glob) do |file| - puts file if ENV["verbose"] + puts file if ENV['verbose'] content = File.read(file) regexps.each do |r| match = content.scan(r) set.concat match.flatten end end set.sort.uniq end def stitch_broken_strings(strings) # example of broken string # "This option will effectively disable the tabs module in TotalFinder. In effect the dual mode and visor functionality will be " # "disabled as well. This may be desired under Mavericks - use native Finder tabs " # "exclusively while keeping benefits of other TotalFinder features.\n\nFor this operation Finder has to be restarted!\nNote: " # "Prior restarting please finish all Finder tasks in progress (like copying or " # "moving files)." - + strings.map do |s| r = /([^\\])(".*?")/m - s.gsub(r) do |x| - $1 + s.gsub(r) do |_x| + Regexp.last_match(1) end end end def extract_menuitems_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| - result.concat ack(dir, "*.{cpp,mm,h}", [ - /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m, + result.concat ack(dir, '*.{cpp,mm,h}', [ + /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m ]) end - + stitch_broken_strings(result.sort.uniq) end def extract_code_strings(folder) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| - result.concat ack(dir, "*.{cpp,mm,m,h}", [ + result.concat ack(dir, '*.{cpp,mm,m,h}', [ /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,\)]/m ]) end - + stitch_broken_strings(result.sort.uniq) end def extract_ui_strings(folder, xibs) dirs = Array(folder) # flexibility to pass multiple directories result = [] dirs.each do |dir| xibs.each do |xib| result.concat ack(dir, "#{xib}.xib", [ /"\^(.*?[^\\])"/m ]) end end result.sort.uniq end def parse_strings_file(filename) - return [] unless File.exists? filename + return [] unless File.exist? filename + File.read(filename).lines end def update_strings(old_strings, new_keys, target) removed_count = 0 count = 0 # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings known_keys = [] strings = old_strings.map do |line| match = line =~ /^"(.*?)"/ # it is a valid key-definition line? next line unless match + count += 1 - unless new_keys.include? $1 then - line = "/* REMOVED #{line.strip} */\n" # *** - removed_count += 1 - else - if known_keys.include? $1 then + if new_keys.include? Regexp.last_match(1) + if known_keys.include? Regexp.last_match(1) line = "/* DUPLICIT #{line.strip} */\n" # *** removed_count += 1 else - known_keys << $1 + known_keys << Regexp.last_match(1) end + else + line = "/* REMOVED #{line.strip} */\n" # *** + removed_count += 1 end line end - + to_be_added = new_keys - known_keys - write_file(target, strings.join("")) + write_file(target, strings.join('')) { - "removed_count" => removed_count, - "count" => count, - "new_strings" => new_keys, - "old_strings" => old_strings, - "output" => strings, - "to_be_added" => to_be_added.sort.uniq + 'removed_count' => removed_count, + 'count' => count, + 'new_strings' => new_keys, + 'old_strings' => old_strings, + 'output' => strings, + 'to_be_added' => to_be_added.sort.uniq } end def update_english_strings(project, src_folder, xibs, additional_strings=[]) target = File.join(ENGLISH_LPROJ, "#{project}.strings") code_strings = extract_code_strings(src_folder) ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) new_strings = code_strings.concat(ui_strings).concat(additional_strings) new_strings.sort.uniq! old_strings = parse_strings_file(target) - + res = update_strings(old_strings, new_strings, target) - - removed_count = res["removed_count"] - strings = res["output"] - count = res["count"] - puts " #{"-#{removed_count}".red}/#{"#{count}".blue} in #{target}" - + removed_count = res['removed_count'] + strings = res['output'] + count = res['count'] + + puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" + res end def update_english_menuitems_strings(src_folder) - target = File.join(ENGLISH_LPROJ, "MenuItems.strings") + target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') - new_strings = extract_menuitems_strings(src_folder).map {|s| "MenuItem:#{s}"} + new_strings = extract_menuitems_strings(src_folder).map { |s| "MenuItem:#{s}" } old_strings = parse_strings_file(target) - + res = update_strings(old_strings, new_strings, target) - - removed_count = res["removed_count"] - strings = res["output"] - count = res["count"] - puts " #{"-#{removed_count}".red}/#{"#{count}".blue} in #{target}" - + removed_count = res['removed_count'] + strings = res['output'] + count = res['count'] + + puts " #{"-#{removed_count}".red}/#{count.to_s.blue} in #{target}" + res end def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) - xibs = Hash.new - + xibs = {} + # xib naming exceptions that don't follow conventions unconventional = { - "SomeXibName" => "SomePluginName" - } - - Dir.glob(File.join(dir, "*.xib")) do |file| - name = File.basename(file, ".xib") + 'SomeXibName' => 'SomePluginName' + } + + Dir.glob(File.join(dir, '*.xib')) do |file| + name = File.basename(file, '.xib') # does the name begin with some plugin name? - plugin = plugins.find { |plugin| plugin==name or name.index(plugin) == 0 } - if plugin.nil? and unconventional["name"] then - plugin = unconventional["name"] - end - - unless plugin.nil? then + plugin = plugins.find { |plugin| (plugin == name) || (name.index(plugin) == 0) } + plugin = unconventional['name'] if plugin.nil? && unconventional['name'] + + unless plugin.nil? xibs[plugin] ||= [] xibs[plugin] << name next end - - xibs["SHELL"] ||= [] - xibs["SHELL"] << name + + xibs['SHELL'] ||= [] + xibs['SHELL'] << name end - + xibs end def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) - additions = Hash.new + additions = {} plugins.each do |plugin| plugin_dir = File.join(dir, plugin) - next unless File.exists? plugin_dir - next if xibs[plugin].nil? or xibs[plugin].size == 0 # an edge case for empty array + next unless File.exist? plugin_dir + next if xibs[plugin].nil? || xibs[plugin].empty? # an edge case for empty array - additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])["to_be_added"] # process just plugin xibs + additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])['to_be_added'] # process just plugin xibs end additions end def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) - update_english_strings("TotalFinder", shell_dir, xibs, duplicates) # process just shell xibs + update_english_strings('TotalFinder', shell_dir, xibs, duplicates) # process just shell xibs end -def process_english_menuitems() - update_english_menuitems_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)["to_be_added"] +def process_english_menuitems + update_english_menuitems_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)['to_be_added'] end def get_additions_duplicates(additions) all = [] - additions.each do |k, v| + additions.each do |_k, v| all.concat v end - + # count occurences and return only duplicities - all.inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys.sort.uniq + all.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys.sort.uniq end def insert_additions(list, target) - return unless list.size>0 - + return if list.empty? + strings = [] strings << "\n" strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" - + list.each do |key| - value = key.gsub("MenuItem:", "") # MenuItems special case - strings << "\"#{key}\" = \"#{value}\";" + value = key.gsub('MenuItem:', '') # MenuItems special case + strings << "\"#{key}\" = \"#{value}\";" end append_file(target, strings.join("\n")) - + puts " #{"+#{list.size}".yellow} in #{target}" end def inprint_strings(source, dest, shared_originals=[]) strings = parse_strings_file(source) originals = [] originals.concat shared_originals originals.concat parse_strings_file(dest) # transform lang back to english index = 0 strings.map! do |line| - index+=1 - next line unless (line.strip[0...1]=='"') + index += 1 + next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ - die "syntax error in #{source.blue}:#{index.to_s} [#{line}]" unless $1 + die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) - line = $1 + " = " + $1 + ";\n"; + line = Regexp.last_match(1) + ' = ' + Regexp.last_match(1) + ";\n" line end # replace translations we already know from previsous version index = 0 originals.each do |original| - index+=1 - next unless (original.strip[0...1]=='"') + index += 1 + next unless original.strip[0...1] == '"' original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ - needle = $1 - haystack = $2 - rest = $3 - die "syntax error in #{dest.blue}:#{index.to_s} [#{original}]" unless $1 and $2 + needle = Regexp.last_match(1) + haystack = Regexp.last_match(2) + rest = Regexp.last_match(3) + die "syntax error in #{dest.blue}:#{index} [#{original}]" unless Regexp.last_match(1) && Regexp.last_match(2) found = false strings.map! do |line| - if (line.index needle) == 0 then - line = needle + " = " + haystack + ";" + rest + "\n"; + if (line.index needle) == 0 + line = needle + ' = ' + haystack + ';' + rest + "\n" found = true end line end end - write_file(dest, strings.join("")) + write_file(dest, strings.join('')) strings end def find_key(key, lines) lines.each do |line| - next unless (line.strip[0...1]=='"') + next unless line.strip[0...1] == '"' + line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ - needle = $1 - haystack = $2 - die "syntax error in #{dest.blue}:#{index.to_s} [#{line}]" unless $1 and $2 - return haystack if needle==key + needle = Regexp.last_match(1) + haystack = Regexp.last_match(2) + die "syntax error in #{dest.blue}:#{index} [#{line}]" unless Regexp.last_match(1) && Regexp.last_match(2) + return haystack if needle == key end - + nil end def post_process_menuitems(dest, shared_originals=[]) strings = parse_strings_file(dest) - + strings.map! do |line| - next line unless (line.strip[0...1]=='"') + next line unless line.strip[0...1] == '"' line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ - die "syntax error in #{source.blue}:#{index.to_s} [#{line}]" unless $1 + die "syntax error in #{source.blue}:#{index} [#{line}]" unless Regexp.last_match(1) + + key = Regexp.last_match(1) + val = Regexp.last_match(2) + rest = Regexp.last_match(3) - key = $1 - val = $2 - rest = $3 - - if (key==val) then + if key == val # try to lookup exitsting val - translated_val = find_key(key.gsub("MenuItem:", ""), shared_originals) - unless translated_val.nil? then - line = key + " = " + translated_val + ";" + rest + "\n"; - end + translated_val = find_key(key.gsub('MenuItem:', ''), shared_originals) + line = key + ' = ' + translated_val + ';' + rest + "\n" unless translated_val.nil? end line end - - File.open(dest, "w") do |f| + + File.open(dest, 'w') do |f| f << strings.join end strings end def propagate_english_to_cwd total = 0 # TotalFinder.strings are master files, some strings may move between files - all = parse_strings_file File.join(Dir.pwd, "TotalFinder.strings") - Dir.glob(File.join(ENGLISH_LPROJ, "*.strings")) do |file| - next if File.basename(file)=="TotalFinder.strings" + all = parse_strings_file File.join(Dir.pwd, 'TotalFinder.strings') + Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| + next if File.basename(file) == 'TotalFinder.strings' + all.concat parse_strings_file(File.join(Dir.pwd, File.basename(file))) end - Dir.glob(File.join(ENGLISH_LPROJ, "*.strings")) do |file| + Dir.glob(File.join(ENGLISH_LPROJ, '*.strings')) do |file| puts " #{File.basename(file)}".yellow total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size end - + # post-process MenuItems.strings - file = "MenuItems.strings" + file = 'MenuItems.strings' puts " post processing #{file.yellow}" total += post_process_menuitems(File.join(Dir.pwd, file), all).size - - puts " -> "+total.to_s.green+" strings processed" + + puts ' -> ' + total.to_s.green + ' strings processed' end def remove_missing_files_in_cwd - files1 = Dir.glob(File.join(ENGLISH_LPROJ, "*")).map {|f| File.basename f } - files2 = Dir.glob(File.join(Dir.pwd, "*")).map {|f| File.basename f } + files1 = Dir.glob(File.join(ENGLISH_LPROJ, '*')).map { |f| File.basename f } + files2 = Dir.glob(File.join(Dir.pwd, '*')).map { |f| File.basename f } to_be_deleted = files2 - files1 - - to_be_deleted.each do |file| + + to_be_deleted.each do |file| puts "deleting '#{file}'".red FileUtils.rm(file) end end def propagate_from_english_to_other_lprojs - glob = ENV["to"] || "*.lproj" + glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do puts dir.blue propagate_english_to_cwd remove_missing_files_in_cwd end end end def create_localizations_for_project - glob = ENV["to"] || "*.lproj" - project = ENV["project"] || die("Project name not defined") + glob = ENV['to'] || '*.lproj' + project = ENV['project'] || die('Project name not defined') Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| Dir.chdir dir do - write_file(File.join(dir, project + ".strings"), "/* no strings */") + write_file(File.join(dir, project + '.strings'), '/* no strings */') end end end def exec_cmd_in_lprojs(cmd) - glob = ENV["to"] || "*.lproj" + glob = ENV['to'] || '*.lproj' Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| puts dir.blue Dir.chdir dir do sys(cmd) end end end -def validate_strings_file path +def validate_strings_file(path) lines = parse_strings_file(path) in_multi_line_comment = false counter = 0 count = lines.size lines.each do |line| counter += 1 - if in_multi_line_comment and line =~ /.*\*\/\w*$/ + if in_multi_line_comment && line =~ /.*\*\/\w*$/ in_multi_line_comment = false next end next if in_multi_line_comment - line = line.gsub(/\r\n?/, "") + "\n" + + line = line.gsub(/\r\n?/, '') + "\n" next if line =~ /^".*?"\s*=\s*".*?";\s*$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ next if line =~ /^\/\*.*?\*\/$/ next if line =~ /^\s*$/ - if line =~ /^\/\*[^\*]*/ then + + if line =~ /^\/\*[^\*]*/ in_multi_line_comment = true next end - puts "line ##{counter}: unrecognized pattern".red+" (fix rakefile if this is a valid pattern)" + puts "line ##{counter}: unrecognized pattern".red + ' (fix rakefile if this is a valid pattern)' puts line puts "mate -l #{counter} \"#{path}\"".yellow return false end true end def validate_strings_files begin require 'cmess/guess_encoding' rescue LoadError die 'You must "gem install cmess" to use character encoding detection' end - glob = ENV["to"] || "*.lproj" + glob = ENV['to'] || '*.lproj' counter = 0 failed = 0 warnings = 0 known_files = [] - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "en.lproj", "*")) do |path| + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*')) do |path| known_files << File.basename(path) end - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "*.lproj")) do |dir| + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, '*.lproj')) do |dir| unrecognized_files = [] missing_files = known_files.dup - Dir.glob(File.join(dir, "*")) do |path| + Dir.glob(File.join(dir, '*')) do |path| file = File.basename(path) - if missing_files.include?(file) then + if missing_files.include?(file) missing_files.delete(file) else unrecognized_files << file end end - if (!missing_files.empty? or !unrecognized_files.empty?) then + if !missing_files.empty? || !unrecognized_files.empty? warnings += 1 - puts "in " + dir.blue + ":" - if (!missing_files.empty?) then - puts " missing files: " + missing_files.join(", ") - end - if (!unrecognized_files.empty?) then - puts " unrecognized files: " + unrecognized_files.join(", ") - end + puts 'in ' + dir.blue + ':' + puts ' missing files: ' + missing_files.join(', ') unless missing_files.empty? + puts ' unrecognized files: ' + unrecognized_files.join(', ') unless unrecognized_files.empty? end end - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, "*.strings")) do |path| + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, '*.strings')) do |path| counter += 1 ok = 1 - input = File.read path - charset = "ASCII" - if input.strip.size>0 then + input = File.read path + charset = 'ASCII' + unless input.strip.empty? charset = CMess::GuessEncoding::Automatic.guess(input) - ok = ((validate_strings_file path) and (charset=="ASCII" or charset=="UTF-8")) + ok = ((validate_strings_file path) && ((charset == 'ASCII') || (charset == 'UTF-8'))) end - puts charset.magenta+" "+path.blue+" "+"ok".yellow if ok - puts charset.magenta+" "+path.blue+" "+"failed".red unless ok - failed +=1 unless ok + puts charset.magenta + ' ' + path.blue + ' ' + 'ok'.yellow if ok + puts charset.magenta + ' ' + path.blue + ' ' + 'failed'.red unless ok + failed += 1 unless ok end all = [] - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "en.lproj", "*.strings")) do |file| + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, 'en.lproj', '*.strings')) do |file| all.concat parse_strings_file(file) end list = [] all.each do |original| - next unless (original.strip[0...1]=='"') + next unless original.strip[0...1] == '"' original =~ /^\s*?"(.*)"\s*?=/ - list << $1 + list << Regexp.last_match(1) end - dups = list.inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys + dups = list.each_with_object(Hash.new(0)) { |v, h| h[v] += 1; }.reject { |_k, v| v == 1 }.keys - if dups.size>0 then + unless dups.empty? puts - puts "found duplicate keys:".red + puts 'found duplicate keys:'.red dups.each { |x| puts " #{x}" } puts - puts "solution:".yellow + " shared keys should be placed in TotalFinder.strings".blue + puts 'solution:'.yellow + ' shared keys should be placed in TotalFinder.strings'.blue puts end - puts "-----------------------------------" - puts "checked "+"#{counter} files".magenta+" and "+(failed>0 ? ("#{failed} failed".red) : ("all is ok".yellow)) + (warnings>0?(" [#{warnings} warnings]".green):("")) + puts '-----------------------------------' + puts 'checked ' + "#{counter} files".magenta + ' and ' + (failed > 0 ? "#{failed} failed".red : 'all is ok'.yellow) + (warnings > 0 ? " [#{warnings} warnings]".green : '') end def stub_installer_lprojs - glob = "*.lproj" + glob = '*.lproj' - english_source = File.join(INSTALLER_RESOURCES_DIR, "en.lproj") - die("need #{english_source}!") unless File.exists?(english_source) + english_source = File.join(INSTALLER_RESOURCES_DIR, 'en.lproj') + die("need #{english_source}!") unless File.exist?(english_source) Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| name = File.basename(dir) - next if name == "en.lproj" + next if name == 'en.lproj' + full_path = File.join(INSTALLER_RESOURCES_DIR, name) - next if File.exists?(full_path) # already have it - puts "Creating stub " + full_path.blue + next if File.exist?(full_path) # already have it + + puts 'Creating stub ' + full_path.blue sys("cp -r \"#{english_source}\" \"#{full_path}\"") end end ################################################################################################ # tasks -desc "switch /Applications/TotalFinder.app into dev mode" +desc 'switch /Applications/TotalFinder.app into dev mode' task :dev do - sys("./bin/dev.sh") + sys('./bin/dev.sh') end -desc "switch /Applications/TotalFinder.app into non-dev mode" +desc 'switch /Applications/TotalFinder.app into non-dev mode' task :undev do - sys("./bin/undev.sh") + sys('./bin/undev.sh') end -desc "restart Finder.app" +desc 'restart Finder.app' task :restart do - sys("./bin/restart.sh") + sys('./bin/restart.sh') end -desc "normalize Finder.app so it contains all our language folders (run with sudo)" +desc 'normalize Finder.app so it contains all our language folders (run with sudo)' task :normalize do lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') Dir.glob(lprojs) do |folder| dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) - if File.exists? dir then - puts dir.blue + " exists".yellow + if File.exist? dir + puts dir.blue + ' exists'.yellow else - if !sys("mkdir -p \"#{dir}\"") then - die("Unable to create a folder. Hint: you should run this as sudo rake normalize") - end - puts dir.blue + " created".green + die('Unable to create a folder. Hint: you should run this as sudo rake normalize') unless sys("mkdir -p \"#{dir}\"") + puts dir.blue + ' created'.green end end end -desc "cherrypicks strings from sources and applies missing strings to en.lproj" +desc 'cherrypicks strings from sources and applies missing strings to en.lproj' task :cherrypick do - die "install ack 2.0+ | for example via homebrew:> brew install ack" if `which ack`=="" - die "upgrade your ack to 2.0+ | for example via homebrew:> brew install ack" unless `ack --version`=~/ack 2/ + die 'install ack 2.0+ | for example via homebrew:> brew install ack' if `which ack` == '' + die 'upgrade your ack to 2.0+ | for example via homebrew:> brew install ack' unless `ack --version` =~ /ack 2/ - plugins = get_list_of_plugins() + plugins = get_list_of_plugins xibs = categorize_xibs(plugins) - puts "XIBs:".blue + puts 'XIBs:'.blue pp xibs puts - puts "Processing string files:".yellow - + puts 'Processing string files:'.yellow + # additons is a hash containing an array of added translation keys for each plugin additions = process_english_strings_in_plugins(plugins, xibs) duplicates = get_additions_duplicates(additions) - res = process_english_strings_in_shell(xibs["SHELL"], duplicates) # duplicates will be moved into shell - shell_additions = res["to_be_added"] - shell_new_strings = res["new_strings"] - - menuitems_additions = process_english_menuitems() + res = process_english_strings_in_shell(xibs['SHELL'], duplicates) # duplicates will be moved into shell + shell_additions = res['to_be_added'] + shell_new_strings = res['new_strings'] + + menuitems_additions = process_english_menuitems # insert additions to plugins plugins.each do |plugin| next unless additions[plugin] + target = File.join(ENGLISH_LPROJ, "#{plugin}.strings") list = additions[plugin] - duplicates - shell_new_strings insert_additions(list, target) end # insert additions to shell - target = File.join(ENGLISH_LPROJ, "TotalFinder.strings") + target = File.join(ENGLISH_LPROJ, 'TotalFinder.strings') insert_additions(shell_additions, target) # insert additions to menu items - target = File.join(ENGLISH_LPROJ, "MenuItems.strings") + target = File.join(ENGLISH_LPROJ, 'MenuItems.strings') insert_additions(menuitems_additions, target) - + unhandled_duplicates = duplicates - shell_new_strings - if unhandled_duplicates.size>0 then - puts - puts "Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:".yellow - puts unhandled_duplicates.join(", ").magenta + unless unhandled_duplicates.empty? + puts + puts 'Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:'.yellow + puts unhandled_duplicates.join(', ').magenta end end -desc "propagates structure of en.lproj to all other language folders while keeping already translated strings" +desc 'propagates structure of en.lproj to all other language folders while keeping already translated strings' task :propagate do propagate_from_english_to_other_lprojs end -desc "make stub lproj folders for installer, creates all which exist in plugin" +desc 'make stub lproj folders for installer, creates all which exist in plugin' task :stub do stub_installer_lprojs end -desc "exec command in all lproj folders" +desc 'exec command in all lproj folders' task :exec do - exec_cmd_in_lprojs(ENV["cmd"] || "ls") + exec_cmd_in_lprojs(ENV['cmd'] || 'ls') end -desc "validates all strings files and checks them for syntax errors" +desc 'validates all strings files and checks them for syntax errors' task :validate do validate_strings_files end -desc "validates all strings files and checks them for syntax errors" +desc 'validates all strings files and checks them for syntax errors' task :create_localization do create_localizations_for_project end -task :default => :restart \ No newline at end of file +task default: :restart
binaryage/totalfinder-i18n
ffc7b115ec6901a5c0470b24f4e44ab547e9b5a1
ruby: git ignore .idea
diff --git a/ruby/.gitignore b/ruby/.gitignore new file mode 100644 index 0000000..723ef36 --- /dev/null +++ b/ruby/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file
binaryage/totalfinder-i18n
acfda85af9c5a9c3557c48b7b57667ca256bbe76
add rubocop config
diff --git a/ruby/.rubocop.yml b/ruby/.rubocop.yml new file mode 100644 index 0000000..d85ac0c --- /dev/null +++ b/ruby/.rubocop.yml @@ -0,0 +1,62 @@ +AllCops: + TargetRubyVersion: 2.7 + Include: + - '*.rb' + - '*.rake' + +Layout/LineLength: + Max: 126 + +Layout/SpaceAroundEqualsInParameterDefault: + EnforcedStyle: no_space + +Metrics/MethodLength: + Enabled: false + +Metrics/AbcSize: + Enabled: false + +Metrics/BlockLength: + Enabled: false + +Metrics/BlockNesting: + Enabled: false + +Metrics/CyclomaticComplexity: + Enabled: false + +Metrics/ClassLength: + Enabled: false + +Style/Documentation: + Enabled: false + +Layout/FirstArrayElementIndentation: + Enabled: false + +Style/GuardClause: + Enabled: false + +Metrics/PerceivedComplexity: + Enabled: false + +Style/TernaryParentheses: + Enabled: false + +Style/RegexpLiteral: + Enabled: false + +Style/RescueStandardError: + Enabled: false + +Style/SafeNavigation: + Enabled: false + +Style/HashEachMethods: + Enabled: false + +Style/HashTransformKeys: + Enabled: false + +Style/HashTransformValues: + Enabled: false \ No newline at end of file
binaryage/totalfinder-i18n
42daa1170a8bc39d49068ba280ef56204d4757ab
move ruby sources under /ruby
diff --git a/rakefile b/rakefile index 2373013..a20ac6a 100644 --- a/rakefile +++ b/rakefile @@ -1,703 +1,3 @@ -require 'date' -require 'rake' -require 'pp' +# frozen_string_literal: true -################################################################################################ -# constants - -ROOT_DIR = File.expand_path('.') -FINDER_DIR = '/System/Library/CoreServices/Finder.app' -FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') -PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') -INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') -ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') -SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')] -TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') - -################################################################################################ -# dependencies - -begin - require 'colored' -rescue LoadError - raise 'You must "gem install colored" to use terminal colors' -end - -################################################################################################ -# helpers - -def die(msg, status=1) - puts "Error[#{status||$?}]: #{msg}".red - exit status||$? -end - -def sys(cmd) - puts "> #{cmd}".yellow - system(cmd) -end - -################################################################################################ -# routines - -def write_file(filename, content) - if ENV["dry"] then - puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" - return - end - - File.open(filename, "w") do |f| - f.write content - end -end - -def append_file(filename, content) - if ENV["dry"] then - puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" - return - end - - File.open(filename, "a") do |f| - f.write content - end -end - -def get_list_of_plugins(filter=nil) - filter = "*" unless filter - - plugins = [] - Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| - if File.directory?(file) and File.exists? File.join(file, File.basename(file)+".xcodeproj") then - plugins << File.basename(file) - end - end - - plugins.uniq -end - -def ack(dir, glob, regexps) - glob = File.join(dir, "**{,/*/**}", glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) - set = [] - Dir.glob(glob) do |file| - puts file if ENV["verbose"] - content = File.read(file) - regexps.each do |r| - match = content.scan(r) - set.concat match.flatten - end - end - set.sort.uniq -end - -def stitch_broken_strings(strings) - # example of broken string - # "This option will effectively disable the tabs module in TotalFinder. In effect the dual mode and visor functionality will be " - # "disabled as well. This may be desired under Mavericks - use native Finder tabs " - # "exclusively while keeping benefits of other TotalFinder features.\n\nFor this operation Finder has to be restarted!\nNote: " - # "Prior restarting please finish all Finder tasks in progress (like copying or " - # "moving files)." - - strings.map do |s| - r = /([^\\])(".*?")/m - s.gsub(r) do |x| - $1 - end - end -end - -def extract_menuitems_strings(folder) - dirs = Array(folder) # flexibility to pass multiple directories - result = [] - dirs.each do |dir| - result.concat ack(dir, "*.{cpp,mm,h}", [ - /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m, - ]) - end - - stitch_broken_strings(result.sort.uniq) -end - -def extract_code_strings(folder) - dirs = Array(folder) # flexibility to pass multiple directories - - result = [] - dirs.each do |dir| - result.concat ack(dir, "*.{cpp,mm,m,h}", [ - /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, - /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,\)]/m - ]) - end - - stitch_broken_strings(result.sort.uniq) -end - -def extract_ui_strings(folder, xibs) - dirs = Array(folder) # flexibility to pass multiple directories - result = [] - dirs.each do |dir| - xibs.each do |xib| - result.concat ack(dir, "#{xib}.xib", [ - /"\^(.*?[^\\])"/m - ]) - end - end - result.sort.uniq -end - -def parse_strings_file(filename) - return [] unless File.exists? filename - File.read(filename).lines -end - -def update_strings(old_strings, new_keys, target) - removed_count = 0 - count = 0 - - # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings - known_keys = [] - strings = old_strings.map do |line| - match = line =~ /^"(.*?)"/ # it is a valid key-definition line? - next line unless match - count += 1 - unless new_keys.include? $1 then - line = "/* REMOVED #{line.strip} */\n" # *** - removed_count += 1 - else - if known_keys.include? $1 then - line = "/* DUPLICIT #{line.strip} */\n" # *** - removed_count += 1 - else - known_keys << $1 - end - end - line - end - - to_be_added = new_keys - known_keys - - write_file(target, strings.join("")) - - { - "removed_count" => removed_count, - "count" => count, - "new_strings" => new_keys, - "old_strings" => old_strings, - "output" => strings, - "to_be_added" => to_be_added.sort.uniq - } -end - -def update_english_strings(project, src_folder, xibs, additional_strings=[]) - target = File.join(ENGLISH_LPROJ, "#{project}.strings") - code_strings = extract_code_strings(src_folder) - ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) - new_strings = code_strings.concat(ui_strings).concat(additional_strings) - new_strings.sort.uniq! - old_strings = parse_strings_file(target) - - res = update_strings(old_strings, new_strings, target) - - removed_count = res["removed_count"] - strings = res["output"] - count = res["count"] - - puts " #{"-#{removed_count}".red}/#{"#{count}".blue} in #{target}" - - res -end - -def update_english_menuitems_strings(src_folder) - target = File.join(ENGLISH_LPROJ, "MenuItems.strings") - - new_strings = extract_menuitems_strings(src_folder).map {|s| "MenuItem:#{s}"} - old_strings = parse_strings_file(target) - - res = update_strings(old_strings, new_strings, target) - - removed_count = res["removed_count"] - strings = res["output"] - count = res["count"] - - puts " #{"-#{removed_count}".red}/#{"#{count}".blue} in #{target}" - - res -end - -def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) - xibs = Hash.new - - # xib naming exceptions that don't follow conventions - unconventional = { - "SomeXibName" => "SomePluginName" - } - - Dir.glob(File.join(dir, "*.xib")) do |file| - name = File.basename(file, ".xib") - # does the name begin with some plugin name? - plugin = plugins.find { |plugin| plugin==name or name.index(plugin) == 0 } - if plugin.nil? and unconventional["name"] then - plugin = unconventional["name"] - end - - unless plugin.nil? then - xibs[plugin] ||= [] - xibs[plugin] << name - next - end - - xibs["SHELL"] ||= [] - xibs["SHELL"] << name - end - - xibs -end - -def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) - additions = Hash.new - plugins.each do |plugin| - plugin_dir = File.join(dir, plugin) - next unless File.exists? plugin_dir - next if xibs[plugin].nil? or xibs[plugin].size == 0 # an edge case for empty array - - additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])["to_be_added"] # process just plugin xibs - end - additions -end - -def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) - update_english_strings("TotalFinder", shell_dir, xibs, duplicates) # process just shell xibs -end - -def process_english_menuitems() - update_english_menuitems_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)["to_be_added"] -end - -def get_additions_duplicates(additions) - all = [] - additions.each do |k, v| - all.concat v - end - - # count occurences and return only duplicities - all.inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys.sort.uniq -end - -def insert_additions(list, target) - return unless list.size>0 - - strings = [] - strings << "\n" - strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" - - list.each do |key| - value = key.gsub("MenuItem:", "") # MenuItems special case - strings << "\"#{key}\" = \"#{value}\";" - end - - append_file(target, strings.join("\n")) - - puts " #{"+#{list.size}".yellow} in #{target}" -end - -def inprint_strings(source, dest, shared_originals=[]) - strings = parse_strings_file(source) - originals = [] - originals.concat shared_originals - originals.concat parse_strings_file(dest) - - # transform lang back to english - index = 0 - strings.map! do |line| - index+=1 - next line unless (line.strip[0...1]=='"') - - line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ - die "syntax error in #{source.blue}:#{index.to_s} [#{line}]" unless $1 - - line = $1 + " = " + $1 + ";\n"; - - line - end - - # replace translations we already know from previsous version - index = 0 - originals.each do |original| - index+=1 - next unless (original.strip[0...1]=='"') - - original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ - needle = $1 - haystack = $2 - rest = $3 - die "syntax error in #{dest.blue}:#{index.to_s} [#{original}]" unless $1 and $2 - - found = false - strings.map! do |line| - if (line.index needle) == 0 then - line = needle + " = " + haystack + ";" + rest + "\n"; - found = true - end - - line - end - end - - write_file(dest, strings.join("")) - - strings -end - -def find_key(key, lines) - lines.each do |line| - next unless (line.strip[0...1]=='"') - line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ - needle = $1 - haystack = $2 - die "syntax error in #{dest.blue}:#{index.to_s} [#{line}]" unless $1 and $2 - return haystack if needle==key - end - - nil -end - -def post_process_menuitems(dest, shared_originals=[]) - strings = parse_strings_file(dest) - - strings.map! do |line| - next line unless (line.strip[0...1]=='"') - - line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ - die "syntax error in #{source.blue}:#{index.to_s} [#{line}]" unless $1 - - key = $1 - val = $2 - rest = $3 - - if (key==val) then - # try to lookup exitsting val - translated_val = find_key(key.gsub("MenuItem:", ""), shared_originals) - unless translated_val.nil? then - line = key + " = " + translated_val + ";" + rest + "\n"; - end - end - - line - end - - File.open(dest, "w") do |f| - f << strings.join - end - - strings -end - -def propagate_english_to_cwd - total = 0 - - # TotalFinder.strings are master files, some strings may move between files - all = parse_strings_file File.join(Dir.pwd, "TotalFinder.strings") - Dir.glob(File.join(ENGLISH_LPROJ, "*.strings")) do |file| - next if File.basename(file)=="TotalFinder.strings" - all.concat parse_strings_file(File.join(Dir.pwd, File.basename(file))) - end - - Dir.glob(File.join(ENGLISH_LPROJ, "*.strings")) do |file| - puts " #{File.basename(file)}".yellow - total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size - end - - # post-process MenuItems.strings - file = "MenuItems.strings" - puts " post processing #{file.yellow}" - total += post_process_menuitems(File.join(Dir.pwd, file), all).size - - puts " -> "+total.to_s.green+" strings processed" -end - -def remove_missing_files_in_cwd - files1 = Dir.glob(File.join(ENGLISH_LPROJ, "*")).map {|f| File.basename f } - files2 = Dir.glob(File.join(Dir.pwd, "*")).map {|f| File.basename f } - to_be_deleted = files2 - files1 - - to_be_deleted.each do |file| - puts "deleting '#{file}'".red - FileUtils.rm(file) - end -end - -def propagate_from_english_to_other_lprojs - glob = ENV["to"] || "*.lproj" - - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| - Dir.chdir dir do - puts dir.blue - propagate_english_to_cwd - remove_missing_files_in_cwd - end - end -end - -def create_localizations_for_project - glob = ENV["to"] || "*.lproj" - project = ENV["project"] || die("Project name not defined") - - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| - Dir.chdir dir do - write_file(File.join(dir, project + ".strings"), "/* no strings */") - end - end -end - -def exec_cmd_in_lprojs(cmd) - glob = ENV["to"] || "*.lproj" - - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| - puts dir.blue - Dir.chdir dir do - sys(cmd) - end - end -end - -def validate_strings_file path - lines = parse_strings_file(path) - - in_multi_line_comment = false - counter = 0 - count = lines.size - lines.each do |line| - counter += 1 - if in_multi_line_comment and line =~ /.*\*\/\w*$/ - in_multi_line_comment = false - next - end - next if in_multi_line_comment - line = line.gsub(/\r\n?/, "") + "\n" - next if line =~ /^".*?"\s*=\s*".*?";\s*$/ - next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ - next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ - next if line =~ /^\/\*.*?\*\/$/ - next if line =~ /^\s*$/ - if line =~ /^\/\*[^\*]*/ then - in_multi_line_comment = true - next - end - - puts "line ##{counter}: unrecognized pattern".red+" (fix rakefile if this is a valid pattern)" - puts line - puts "mate -l #{counter} \"#{path}\"".yellow - return false - end - - true -end - -def validate_strings_files - begin - require 'cmess/guess_encoding' - rescue LoadError - die 'You must "gem install cmess" to use character encoding detection' - end - - glob = ENV["to"] || "*.lproj" - - counter = 0 - failed = 0 - warnings = 0 - - known_files = [] - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "en.lproj", "*")) do |path| - known_files << File.basename(path) - end - - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "*.lproj")) do |dir| - unrecognized_files = [] - missing_files = known_files.dup - - Dir.glob(File.join(dir, "*")) do |path| - file = File.basename(path) - - if missing_files.include?(file) then - missing_files.delete(file) - else - unrecognized_files << file - end - end - - if (!missing_files.empty? or !unrecognized_files.empty?) then - warnings += 1 - - puts "in " + dir.blue + ":" - if (!missing_files.empty?) then - puts " missing files: " + missing_files.join(", ") - end - if (!unrecognized_files.empty?) then - puts " unrecognized files: " + unrecognized_files.join(", ") - end - end - end - - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, "*.strings")) do |path| - counter += 1 - ok = 1 - input = File.read path - charset = "ASCII" - if input.strip.size>0 then - charset = CMess::GuessEncoding::Automatic.guess(input) - ok = ((validate_strings_file path) and (charset=="ASCII" or charset=="UTF-8")) - end - puts charset.magenta+" "+path.blue+" "+"ok".yellow if ok - puts charset.magenta+" "+path.blue+" "+"failed".red unless ok - failed +=1 unless ok - end - - all = [] - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "en.lproj", "*.strings")) do |file| - all.concat parse_strings_file(file) - end - - list = [] - all.each do |original| - next unless (original.strip[0...1]=='"') - - original =~ /^\s*?"(.*)"\s*?=/ - list << $1 - end - - dups = list.inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys - - if dups.size>0 then - puts - puts "found duplicate keys:".red - dups.each { |x| puts " #{x}" } - puts - puts "solution:".yellow + " shared keys should be placed in TotalFinder.strings".blue - puts - end - - puts "-----------------------------------" - puts "checked "+"#{counter} files".magenta+" and "+(failed>0 ? ("#{failed} failed".red) : ("all is ok".yellow)) + (warnings>0?(" [#{warnings} warnings]".green):("")) -end - -def stub_installer_lprojs - glob = "*.lproj" - - english_source = File.join(INSTALLER_RESOURCES_DIR, "en.lproj") - die("need #{english_source}!") unless File.exists?(english_source) - - Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| - name = File.basename(dir) - next if name == "en.lproj" - full_path = File.join(INSTALLER_RESOURCES_DIR, name) - next if File.exists?(full_path) # already have it - puts "Creating stub " + full_path.blue - sys("cp -r \"#{english_source}\" \"#{full_path}\"") - end -end - -################################################################################################ -# tasks - -desc "switch /Applications/TotalFinder.app into dev mode" -task :dev do - sys("./bin/dev.sh") -end - -desc "switch /Applications/TotalFinder.app into non-dev mode" -task :undev do - sys("./bin/undev.sh") -end - -desc "restart Finder.app" -task :restart do - sys("./bin/restart.sh") -end - -desc "normalize Finder.app so it contains all our language folders (run with sudo)" -task :normalize do - lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') - Dir.glob(lprojs) do |folder| - dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) - if File.exists? dir then - puts dir.blue + " exists".yellow - else - if !sys("mkdir -p \"#{dir}\"") then - die("Unable to create a folder. Hint: you should run this as sudo rake normalize") - end - puts dir.blue + " created".green - end - end -end - -desc "cherrypicks strings from sources and applies missing strings to en.lproj" -task :cherrypick do - die "install ack 2.0+ | for example via homebrew:> brew install ack" if `which ack`=="" - die "upgrade your ack to 2.0+ | for example via homebrew:> brew install ack" unless `ack --version`=~/ack 2/ - - plugins = get_list_of_plugins() - xibs = categorize_xibs(plugins) - - puts "XIBs:".blue - pp xibs - - puts - puts "Processing string files:".yellow - - # additons is a hash containing an array of added translation keys for each plugin - additions = process_english_strings_in_plugins(plugins, xibs) - duplicates = get_additions_duplicates(additions) - res = process_english_strings_in_shell(xibs["SHELL"], duplicates) # duplicates will be moved into shell - shell_additions = res["to_be_added"] - shell_new_strings = res["new_strings"] - - menuitems_additions = process_english_menuitems() - - # insert additions to plugins - plugins.each do |plugin| - next unless additions[plugin] - target = File.join(ENGLISH_LPROJ, "#{plugin}.strings") - list = additions[plugin] - duplicates - shell_new_strings - insert_additions(list, target) - end - - # insert additions to shell - target = File.join(ENGLISH_LPROJ, "TotalFinder.strings") - insert_additions(shell_additions, target) - - # insert additions to menu items - target = File.join(ENGLISH_LPROJ, "MenuItems.strings") - insert_additions(menuitems_additions, target) - - unhandled_duplicates = duplicates - shell_new_strings - if unhandled_duplicates.size>0 then - puts - puts "Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:".yellow - puts unhandled_duplicates.join(", ").magenta - end -end - -desc "propagates structure of en.lproj to all other language folders while keeping already translated strings" -task :propagate do - propagate_from_english_to_other_lprojs -end - -desc "make stub lproj folders for installer, creates all which exist in plugin" -task :stub do - stub_installer_lprojs -end - -desc "exec command in all lproj folders" -task :exec do - exec_cmd_in_lprojs(ENV["cmd"] || "ls") -end - -desc "validates all strings files and checks them for syntax errors" -task :validate do - validate_strings_files -end - -desc "validates all strings files and checks them for syntax errors" -task :create_localization do - create_localizations_for_project -end - -task :default => :restart \ No newline at end of file +import 'ruby/tasks.rake' \ No newline at end of file diff --git a/ruby/tasks.rake b/ruby/tasks.rake new file mode 100644 index 0000000..2373013 --- /dev/null +++ b/ruby/tasks.rake @@ -0,0 +1,703 @@ +require 'date' +require 'rake' +require 'pp' + +################################################################################################ +# constants + +ROOT_DIR = File.expand_path('.') +FINDER_DIR = '/System/Library/CoreServices/Finder.app' +FINDER_RESOURCES_DIR = File.join(FINDER_DIR, 'Contents/Resources') +PLUGIN_RESOURCES_DIR = File.join(ROOT_DIR, 'plugin') +INSTALLER_RESOURCES_DIR = File.join(ROOT_DIR, 'installer') +ENGLISH_LPROJ = File.join(PLUGIN_RESOURCES_DIR, 'en.lproj') +SHELL_SOURCES = [File.join(ROOT_DIR, '..', 'shell'), File.join(ROOT_DIR, '..', 'frameworks')] +TOTALFINDER_PLUGINS_SOURCES = File.join(ROOT_DIR, '..', 'plugins') + +################################################################################################ +# dependencies + +begin + require 'colored' +rescue LoadError + raise 'You must "gem install colored" to use terminal colors' +end + +################################################################################################ +# helpers + +def die(msg, status=1) + puts "Error[#{status||$?}]: #{msg}".red + exit status||$? +end + +def sys(cmd) + puts "> #{cmd}".yellow + system(cmd) +end + +################################################################################################ +# routines + +def write_file(filename, content) + if ENV["dry"] then + puts "in dry mode: would rewrite #{filename.blue} with content of size #{content.size}" + return + end + + File.open(filename, "w") do |f| + f.write content + end +end + +def append_file(filename, content) + if ENV["dry"] then + puts "in dry mode: would append to #{filename.blue} content of size #{content.size}" + return + end + + File.open(filename, "a") do |f| + f.write content + end +end + +def get_list_of_plugins(filter=nil) + filter = "*" unless filter + + plugins = [] + Dir.glob(File.join(TOTALFINDER_PLUGINS_SOURCES, filter)) do |file| + if File.directory?(file) and File.exists? File.join(file, File.basename(file)+".xcodeproj") then + plugins << File.basename(file) + end + end + + plugins.uniq +end + +def ack(dir, glob, regexps) + glob = File.join(dir, "**{,/*/**}", glob) # follow symlinks (http://stackoverflow.com/a/2724048/84283) + set = [] + Dir.glob(glob) do |file| + puts file if ENV["verbose"] + content = File.read(file) + regexps.each do |r| + match = content.scan(r) + set.concat match.flatten + end + end + set.sort.uniq +end + +def stitch_broken_strings(strings) + # example of broken string + # "This option will effectively disable the tabs module in TotalFinder. In effect the dual mode and visor functionality will be " + # "disabled as well. This may be desired under Mavericks - use native Finder tabs " + # "exclusively while keeping benefits of other TotalFinder features.\n\nFor this operation Finder has to be restarted!\nNote: " + # "Prior restarting please finish all Finder tasks in progress (like copying or " + # "moving files)." + + strings.map do |s| + r = /([^\\])(".*?")/m + s.gsub(r) do |x| + $1 + end + end +end + +def extract_menuitems_strings(folder) + dirs = Array(folder) # flexibility to pass multiple directories + result = [] + dirs.each do |dir| + result.concat ack(dir, "*.{cpp,mm,h}", [ + /\$M\s*\(\s*@\s*"(.*?)"\s*\)/m, + ]) + end + + stitch_broken_strings(result.sort.uniq) +end + +def extract_code_strings(folder) + dirs = Array(folder) # flexibility to pass multiple directories + + result = [] + dirs.each do |dir| + result.concat ack(dir, "*.{cpp,mm,m,h}", [ + /\$+\s*\(\s*@\s*"(.*?)"\s*\)/m, + /\$NSLocalizedString\s*\(\s*@\s*"(.*?)"\s*[,\)]/m + ]) + end + + stitch_broken_strings(result.sort.uniq) +end + +def extract_ui_strings(folder, xibs) + dirs = Array(folder) # flexibility to pass multiple directories + result = [] + dirs.each do |dir| + xibs.each do |xib| + result.concat ack(dir, "#{xib}.xib", [ + /"\^(.*?[^\\])"/m + ]) + end + end + result.sort.uniq +end + +def parse_strings_file(filename) + return [] unless File.exists? filename + File.read(filename).lines +end + +def update_strings(old_strings, new_keys, target) + removed_count = 0 + count = 0 + + # comment out existing strings as REMOVED or DUPLICIT if they are not present in new_strings + known_keys = [] + strings = old_strings.map do |line| + match = line =~ /^"(.*?)"/ # it is a valid key-definition line? + next line unless match + count += 1 + unless new_keys.include? $1 then + line = "/* REMOVED #{line.strip} */\n" # *** + removed_count += 1 + else + if known_keys.include? $1 then + line = "/* DUPLICIT #{line.strip} */\n" # *** + removed_count += 1 + else + known_keys << $1 + end + end + line + end + + to_be_added = new_keys - known_keys + + write_file(target, strings.join("")) + + { + "removed_count" => removed_count, + "count" => count, + "new_strings" => new_keys, + "old_strings" => old_strings, + "output" => strings, + "to_be_added" => to_be_added.sort.uniq + } +end + +def update_english_strings(project, src_folder, xibs, additional_strings=[]) + target = File.join(ENGLISH_LPROJ, "#{project}.strings") + code_strings = extract_code_strings(src_folder) + ui_strings = extract_ui_strings(PLUGIN_RESOURCES_DIR, xibs) + new_strings = code_strings.concat(ui_strings).concat(additional_strings) + new_strings.sort.uniq! + old_strings = parse_strings_file(target) + + res = update_strings(old_strings, new_strings, target) + + removed_count = res["removed_count"] + strings = res["output"] + count = res["count"] + + puts " #{"-#{removed_count}".red}/#{"#{count}".blue} in #{target}" + + res +end + +def update_english_menuitems_strings(src_folder) + target = File.join(ENGLISH_LPROJ, "MenuItems.strings") + + new_strings = extract_menuitems_strings(src_folder).map {|s| "MenuItem:#{s}"} + old_strings = parse_strings_file(target) + + res = update_strings(old_strings, new_strings, target) + + removed_count = res["removed_count"] + strings = res["output"] + count = res["count"] + + puts " #{"-#{removed_count}".red}/#{"#{count}".blue} in #{target}" + + res +end + +def categorize_xibs(plugins, dir=PLUGIN_RESOURCES_DIR) + xibs = Hash.new + + # xib naming exceptions that don't follow conventions + unconventional = { + "SomeXibName" => "SomePluginName" + } + + Dir.glob(File.join(dir, "*.xib")) do |file| + name = File.basename(file, ".xib") + # does the name begin with some plugin name? + plugin = plugins.find { |plugin| plugin==name or name.index(plugin) == 0 } + if plugin.nil? and unconventional["name"] then + plugin = unconventional["name"] + end + + unless plugin.nil? then + xibs[plugin] ||= [] + xibs[plugin] << name + next + end + + xibs["SHELL"] ||= [] + xibs["SHELL"] << name + end + + xibs +end + +def process_english_strings_in_plugins(plugins, xibs, dir=TOTALFINDER_PLUGINS_SOURCES) + additions = Hash.new + plugins.each do |plugin| + plugin_dir = File.join(dir, plugin) + next unless File.exists? plugin_dir + next if xibs[plugin].nil? or xibs[plugin].size == 0 # an edge case for empty array + + additions[plugin] = update_english_strings(plugin, plugin_dir, xibs[plugin])["to_be_added"] # process just plugin xibs + end + additions +end + +def process_english_strings_in_shell(xibs, duplicates, shell_dir=SHELL_SOURCES) + update_english_strings("TotalFinder", shell_dir, xibs, duplicates) # process just shell xibs +end + +def process_english_menuitems() + update_english_menuitems_strings([TOTALFINDER_PLUGINS_SOURCES, SHELL_SOURCES].flatten)["to_be_added"] +end + +def get_additions_duplicates(additions) + all = [] + additions.each do |k, v| + all.concat v + end + + # count occurences and return only duplicities + all.inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys.sort.uniq +end + +def insert_additions(list, target) + return unless list.size>0 + + strings = [] + strings << "\n" + strings << "/* NEW STRINGS - TODO: SORT THEM IN OR CREATE A NEW SECTION */\n" + + list.each do |key| + value = key.gsub("MenuItem:", "") # MenuItems special case + strings << "\"#{key}\" = \"#{value}\";" + end + + append_file(target, strings.join("\n")) + + puts " #{"+#{list.size}".yellow} in #{target}" +end + +def inprint_strings(source, dest, shared_originals=[]) + strings = parse_strings_file(source) + originals = [] + originals.concat shared_originals + originals.concat parse_strings_file(dest) + + # transform lang back to english + index = 0 + strings.map! do |line| + index+=1 + next line unless (line.strip[0...1]=='"') + + line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;\s*?/ + die "syntax error in #{source.blue}:#{index.to_s} [#{line}]" unless $1 + + line = $1 + " = " + $1 + ";\n"; + + line + end + + # replace translations we already know from previsous version + index = 0 + originals.each do |original| + index+=1 + next unless (original.strip[0...1]=='"') + + original =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ + needle = $1 + haystack = $2 + rest = $3 + die "syntax error in #{dest.blue}:#{index.to_s} [#{original}]" unless $1 and $2 + + found = false + strings.map! do |line| + if (line.index needle) == 0 then + line = needle + " = " + haystack + ";" + rest + "\n"; + found = true + end + + line + end + end + + write_file(dest, strings.join("")) + + strings +end + +def find_key(key, lines) + lines.each do |line| + next unless (line.strip[0...1]=='"') + line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ + needle = $1 + haystack = $2 + die "syntax error in #{dest.blue}:#{index.to_s} [#{line}]" unless $1 and $2 + return haystack if needle==key + end + + nil +end + +def post_process_menuitems(dest, shared_originals=[]) + strings = parse_strings_file(dest) + + strings.map! do |line| + next line unless (line.strip[0...1]=='"') + + line =~ /^\s*?(".*")\s*?=\s*?(".*")\s*?;(.*)$/ + die "syntax error in #{source.blue}:#{index.to_s} [#{line}]" unless $1 + + key = $1 + val = $2 + rest = $3 + + if (key==val) then + # try to lookup exitsting val + translated_val = find_key(key.gsub("MenuItem:", ""), shared_originals) + unless translated_val.nil? then + line = key + " = " + translated_val + ";" + rest + "\n"; + end + end + + line + end + + File.open(dest, "w") do |f| + f << strings.join + end + + strings +end + +def propagate_english_to_cwd + total = 0 + + # TotalFinder.strings are master files, some strings may move between files + all = parse_strings_file File.join(Dir.pwd, "TotalFinder.strings") + Dir.glob(File.join(ENGLISH_LPROJ, "*.strings")) do |file| + next if File.basename(file)=="TotalFinder.strings" + all.concat parse_strings_file(File.join(Dir.pwd, File.basename(file))) + end + + Dir.glob(File.join(ENGLISH_LPROJ, "*.strings")) do |file| + puts " #{File.basename(file)}".yellow + total += inprint_strings(file, File.join(Dir.pwd, File.basename(file)), all).size + end + + # post-process MenuItems.strings + file = "MenuItems.strings" + puts " post processing #{file.yellow}" + total += post_process_menuitems(File.join(Dir.pwd, file), all).size + + puts " -> "+total.to_s.green+" strings processed" +end + +def remove_missing_files_in_cwd + files1 = Dir.glob(File.join(ENGLISH_LPROJ, "*")).map {|f| File.basename f } + files2 = Dir.glob(File.join(Dir.pwd, "*")).map {|f| File.basename f } + to_be_deleted = files2 - files1 + + to_be_deleted.each do |file| + puts "deleting '#{file}'".red + FileUtils.rm(file) + end +end + +def propagate_from_english_to_other_lprojs + glob = ENV["to"] || "*.lproj" + + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| + Dir.chdir dir do + puts dir.blue + propagate_english_to_cwd + remove_missing_files_in_cwd + end + end +end + +def create_localizations_for_project + glob = ENV["to"] || "*.lproj" + project = ENV["project"] || die("Project name not defined") + + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| + Dir.chdir dir do + write_file(File.join(dir, project + ".strings"), "/* no strings */") + end + end +end + +def exec_cmd_in_lprojs(cmd) + glob = ENV["to"] || "*.lproj" + + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| + puts dir.blue + Dir.chdir dir do + sys(cmd) + end + end +end + +def validate_strings_file path + lines = parse_strings_file(path) + + in_multi_line_comment = false + counter = 0 + count = lines.size + lines.each do |line| + counter += 1 + if in_multi_line_comment and line =~ /.*\*\/\w*$/ + in_multi_line_comment = false + next + end + next if in_multi_line_comment + line = line.gsub(/\r\n?/, "") + "\n" + next if line =~ /^".*?"\s*=\s*".*?";\s*$/ + next if line =~ /^".*?"\s*=\s*".*?";\s*\/\*.*?\*\/$/ + next if line =~ /^".*?"\s*=\s*".*?";\s*\/\/.*?$/ + next if line =~ /^\/\*.*?\*\/$/ + next if line =~ /^\s*$/ + if line =~ /^\/\*[^\*]*/ then + in_multi_line_comment = true + next + end + + puts "line ##{counter}: unrecognized pattern".red+" (fix rakefile if this is a valid pattern)" + puts line + puts "mate -l #{counter} \"#{path}\"".yellow + return false + end + + true +end + +def validate_strings_files + begin + require 'cmess/guess_encoding' + rescue LoadError + die 'You must "gem install cmess" to use character encoding detection' + end + + glob = ENV["to"] || "*.lproj" + + counter = 0 + failed = 0 + warnings = 0 + + known_files = [] + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "en.lproj", "*")) do |path| + known_files << File.basename(path) + end + + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "*.lproj")) do |dir| + unrecognized_files = [] + missing_files = known_files.dup + + Dir.glob(File.join(dir, "*")) do |path| + file = File.basename(path) + + if missing_files.include?(file) then + missing_files.delete(file) + else + unrecognized_files << file + end + end + + if (!missing_files.empty? or !unrecognized_files.empty?) then + warnings += 1 + + puts "in " + dir.blue + ":" + if (!missing_files.empty?) then + puts " missing files: " + missing_files.join(", ") + end + if (!unrecognized_files.empty?) then + puts " unrecognized files: " + unrecognized_files.join(", ") + end + end + end + + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob, "*.strings")) do |path| + counter += 1 + ok = 1 + input = File.read path + charset = "ASCII" + if input.strip.size>0 then + charset = CMess::GuessEncoding::Automatic.guess(input) + ok = ((validate_strings_file path) and (charset=="ASCII" or charset=="UTF-8")) + end + puts charset.magenta+" "+path.blue+" "+"ok".yellow if ok + puts charset.magenta+" "+path.blue+" "+"failed".red unless ok + failed +=1 unless ok + end + + all = [] + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, "en.lproj", "*.strings")) do |file| + all.concat parse_strings_file(file) + end + + list = [] + all.each do |original| + next unless (original.strip[0...1]=='"') + + original =~ /^\s*?"(.*)"\s*?=/ + list << $1 + end + + dups = list.inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys + + if dups.size>0 then + puts + puts "found duplicate keys:".red + dups.each { |x| puts " #{x}" } + puts + puts "solution:".yellow + " shared keys should be placed in TotalFinder.strings".blue + puts + end + + puts "-----------------------------------" + puts "checked "+"#{counter} files".magenta+" and "+(failed>0 ? ("#{failed} failed".red) : ("all is ok".yellow)) + (warnings>0?(" [#{warnings} warnings]".green):("")) +end + +def stub_installer_lprojs + glob = "*.lproj" + + english_source = File.join(INSTALLER_RESOURCES_DIR, "en.lproj") + die("need #{english_source}!") unless File.exists?(english_source) + + Dir.glob(File.join(PLUGIN_RESOURCES_DIR, glob)) do |dir| + name = File.basename(dir) + next if name == "en.lproj" + full_path = File.join(INSTALLER_RESOURCES_DIR, name) + next if File.exists?(full_path) # already have it + puts "Creating stub " + full_path.blue + sys("cp -r \"#{english_source}\" \"#{full_path}\"") + end +end + +################################################################################################ +# tasks + +desc "switch /Applications/TotalFinder.app into dev mode" +task :dev do + sys("./bin/dev.sh") +end + +desc "switch /Applications/TotalFinder.app into non-dev mode" +task :undev do + sys("./bin/undev.sh") +end + +desc "restart Finder.app" +task :restart do + sys("./bin/restart.sh") +end + +desc "normalize Finder.app so it contains all our language folders (run with sudo)" +task :normalize do + lprojs = File.join(PLUGIN_RESOURCES_DIR, '*.lproj') + Dir.glob(lprojs) do |folder| + dir = File.join(FINDER_RESOURCES_DIR, File.basename(folder)) + if File.exists? dir then + puts dir.blue + " exists".yellow + else + if !sys("mkdir -p \"#{dir}\"") then + die("Unable to create a folder. Hint: you should run this as sudo rake normalize") + end + puts dir.blue + " created".green + end + end +end + +desc "cherrypicks strings from sources and applies missing strings to en.lproj" +task :cherrypick do + die "install ack 2.0+ | for example via homebrew:> brew install ack" if `which ack`=="" + die "upgrade your ack to 2.0+ | for example via homebrew:> brew install ack" unless `ack --version`=~/ack 2/ + + plugins = get_list_of_plugins() + xibs = categorize_xibs(plugins) + + puts "XIBs:".blue + pp xibs + + puts + puts "Processing string files:".yellow + + # additons is a hash containing an array of added translation keys for each plugin + additions = process_english_strings_in_plugins(plugins, xibs) + duplicates = get_additions_duplicates(additions) + res = process_english_strings_in_shell(xibs["SHELL"], duplicates) # duplicates will be moved into shell + shell_additions = res["to_be_added"] + shell_new_strings = res["new_strings"] + + menuitems_additions = process_english_menuitems() + + # insert additions to plugins + plugins.each do |plugin| + next unless additions[plugin] + target = File.join(ENGLISH_LPROJ, "#{plugin}.strings") + list = additions[plugin] - duplicates - shell_new_strings + insert_additions(list, target) + end + + # insert additions to shell + target = File.join(ENGLISH_LPROJ, "TotalFinder.strings") + insert_additions(shell_additions, target) + + # insert additions to menu items + target = File.join(ENGLISH_LPROJ, "MenuItems.strings") + insert_additions(menuitems_additions, target) + + unhandled_duplicates = duplicates - shell_new_strings + if unhandled_duplicates.size>0 then + puts + puts "Found these shared keys in plugins and shell, we moved them to TotalFinder.strings:".yellow + puts unhandled_duplicates.join(", ").magenta + end +end + +desc "propagates structure of en.lproj to all other language folders while keeping already translated strings" +task :propagate do + propagate_from_english_to_other_lprojs +end + +desc "make stub lproj folders for installer, creates all which exist in plugin" +task :stub do + stub_installer_lprojs +end + +desc "exec command in all lproj folders" +task :exec do + exec_cmd_in_lprojs(ENV["cmd"] || "ls") +end + +desc "validates all strings files and checks them for syntax errors" +task :validate do + validate_strings_files +end + +desc "validates all strings files and checks them for syntax errors" +task :create_localization do + create_localizations_for_project +end + +task :default => :restart \ No newline at end of file
binaryage/totalfinder-i18n
4f8c3343c5e8fc58e3b2499f205ba593ecfba5b2
crashwatcher: update gist.rb
diff --git a/crashwatcher/ruby/vendor/gist.rb b/crashwatcher/ruby/vendor/gist.rb index ea65be8..dd68b3a 100755 --- a/crashwatcher/ruby/vendor/gist.rb +++ b/crashwatcher/ruby/vendor/gist.rb @@ -1,578 +1,652 @@ #!/usr/bin/env ruby # https://github.com/defunkt/gist/blob/master/lib/gist.rb require 'net/https' require 'cgi' require 'uri' begin require 'json' rescue LoadError require File.join File.dirname(__FILE__), 'json.rb' end # It just gists. module Gist extend self - VERSION = '4.6.2' + VERSION = '6.0.0' # A list of clipboard commands with copy and paste support. CLIPBOARD_COMMANDS = { - 'pbcopy' => 'pbpaste', - 'xclip' => 'xclip -o', - 'xsel -i' => 'xsel -o', - 'putclip' => 'getclip', + 'pbcopy' => 'pbpaste', + 'xclip' => 'xclip -o', + 'xsel -i' => 'xsel -o', + 'putclip' => 'getclip', } - GITHUB_API_URL = URI("https://api.github.com/") - GIT_IO_URL = URI("https://git.io") + GITHUB_API_URL = URI("https://api.github.com/") + GITHUB_URL = URI("https://github.com/") + GIT_IO_URL = URI("https://git.io") GITHUB_BASE_PATH = "" - GHE_BASE_PATH = "/api/v3" + GHE_BASE_PATH = "/api/v3" - URL_ENV_NAME = "GITHUB_URL" + GITHUB_CLIENT_ID = '4f7ec0d4eab38e74384e' - USER_AGENT = "gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})" + URL_ENV_NAME = "GITHUB_URL" + CLIENT_ID_ENV_NAME = "GIST_CLIENT_ID" + + USER_AGENT = "gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})" # Exception tag for errors raised while gisting. - module Error; + module Error + ; + def self.exception(*args) RuntimeError.new(*args).extend(self) end end - class ClipboardError < RuntimeError; include Error end + + class ClipboardError < RuntimeError + include Error + end # helper module for authentication token actions module AuthTokenFile def self.filename if ENV.key?(URL_ENV_NAME) - File.expand_path "~/.gist.#{ENV[URL_ENV_NAME].gsub(/:/, '.').gsub(/[^a-z0-9.]/, '')}" + File.expand_path "~/.gist.#{ENV[URL_ENV_NAME].gsub(/:/, '.').gsub(/[^a-z0-9.-]/, '')}" else File.expand_path "~/.gist" end end def self.read File.read(filename).chomp end def self.write(token) File.open(filename, 'w', 0600) do |f| f.write token end end end # auth token for authentication # # @return [String] string value of access token or `nil`, if not found def auth_token @token ||= AuthTokenFile.read rescue nil end # Upload a gist to https://gist.github.com # # @param [String] content the code you'd like to gist # @param [Hash] options more detailed options, see # the documentation for {multi_gist} # # @see http://developer.github.com/v3/gists/ def gist(content, options = {}) filename = options[:filename] || default_filename multi_gist({filename => content}, options) end def default_filename "gistfile1.txt" end # Upload a gist to https://gist.github.com # # @param [Hash] files the code you'd like to gist: filename => content # @param [Hash] options more detailed options # # @option options [String] :description the description # @option options [Boolean] :public (false) is this gist public # @option options [Boolean] :anonymous (false) is this gist anonymous # @option options [String] :access_token (`File.read("~/.gist")`) The OAuth2 access token. # @option options [String] :update the URL or id of a gist to update # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful. # @option options [Boolean] :open (false) Open the resulting URL in a browser. # @option options [Boolean] :skip_empty (false) Skip gisting empty files. # @option options [Symbol] :output (:all) The type of return value you'd like: # :html_url gives a String containing the url to the gist in a browser # :short_url gives a String contianing a git.io url that redirects to html_url # :javascript gives a String containing a script tag suitable for embedding the gist # :all gives a Hash containing the parsed json response from the server # # @return [String, Hash] the return value as configured by options[:output] # @raise [Gist::Error] if something went wrong # # @see http://developer.github.com/v3/gists/ - def multi_gist(files, options={}) + def multi_gist(files, options = {}) + if options[:anonymous] + raise 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \ + '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)' + else + access_token = (options[:access_token] || auth_token()) + end + json = {} json[:description] = options[:description] if options[:description] json[:public] = !!options[:public] json[:files] = {} files.each_pair do |(name, content)| if content.to_s.strip == "" raise "Cannot gist empty files" unless options[:skip_empty] else name = name == "-" ? default_filename : File.basename(name) json[:files][name] = {:content => content} end end return if json[:files].empty? && options[:skip_empty] existing_gist = options[:update].to_s.split("/").last - if options[:anonymous] - access_token = nil - else - access_token = (options[:access_token] || auth_token()) - end url = "#{base_path}/gists" url << "/" << CGI.escape(existing_gist) if existing_gist.to_s != '' - url << "?access_token=" << CGI.escape(access_token) if access_token.to_s != '' request = Net::HTTP::Post.new(url) + request['Authorization'] = "token #{access_token}" if access_token.to_s != '' request.body = JSON.dump(json) request.content_type = 'application/json' retried = false begin response = http(api_url, request) if Net::HTTPSuccess === response on_success(response.body, options) else raise "Got #{response.class} from gist: #{response.body}" end rescue => e raise if retried retried = true retry end rescue => e raise e.extend Error end # List all gists(private also) for authenticated user # otherwise list public gists for given username (optional argument) # # @param [String] user # @deprecated # # see https://developer.github.com/v3/gists/#list-gists def list_gists(user = "") url = "#{base_path}" if user == "" access_token = auth_token() if access_token.to_s != '' - url << "/gists?access_token=" << CGI.escape(access_token) + url << "/gists" request = Net::HTTP::Get.new(url) + request['Authorization'] = "token #{access_token}" response = http(api_url, request) pretty_gist(response) else raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists." end else url << "/users/#{user}/gists" request = Net::HTTP::Get.new(url) response = http(api_url, request) pretty_gist(response) end end def list_all_gists(user = "") url = "#{base_path}" if user == "" - access_token = auth_token() - if access_token.to_s != '' - url << "/gists?per_page=100&access_token=" << CGI.escape(access_token) - get_gist_pages(url) - else - raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists." - end - + url << "/gists?per_page=100" else url << "/users/#{user}/gists?per_page=100" - get_gist_pages(url) end + get_gist_pages(url, auth_token()) end - def read_gist(id, file_name=nil) + def read_gist(id, file_name = nil, options = {}) url = "#{base_path}/gists/#{id}" - access_token = auth_token() + access_token = (options[:access_token] || auth_token()) if access_token.to_s != '' url << "?access_token=" << CGI.escape(access_token) end request = Net::HTTP::Get.new(url) + request['Authorization'] = "token #{access_token}" if access_token.to_s != '' response = http(api_url, request) if response.code == '200' body = JSON.parse(response.body) files = body["files"] if file_name file = files[file_name] raise Error, "Gist with id of #{id} and file #{file_name} does not exist." unless file else file = files.values.first end - puts file["content"] + file["content"] else raise Error, "Gist with id of #{id} does not exist." end end def delete_gist(id) id = id.split("/").last url = "#{base_path}/gists/#{id}" access_token = auth_token() if access_token.to_s != '' - url << "?access_token=" << CGI.escape(access_token) - request = Net::HTTP::Delete.new(url) + request["Authorization"] = "token #{access_token}" response = http(api_url, request) else raise Error, "Not authenticated. Use 'gist --login' to login." end if response.code == '204' puts "Deleted!" else raise Error, "Gist with id of #{id} does not exist." end end - def get_gist_pages(url) + def get_gist_pages(url, access_token = "") request = Net::HTTP::Get.new(url) + request['Authorization'] = "token #{access_token}" if access_token.to_s != '' response = http(api_url, request) pretty_gist(response) link_header = response.header['link'] if link_header - links = Hash[ link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') } ].invert - get_gist_pages(links['next']) if links['next'] + links = Hash[link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') }].invert + get_gist_pages(links['next'], access_token) if links['next'] end end # return prettified string result of response body for all gists # # @params [Net::HTTPResponse] response # @return [String] prettified result of listing all gists # # see https://developer.github.com/v3/gists/#response def pretty_gist(response) body = JSON.parse(response.body) if response.code == '200' body.each do |gist| description = "#{gist['description'] || gist['files'].keys.join(" ")} #{gist['public'] ? '' : '(secret)'}" puts "#{gist['html_url']} #{description.tr("\n", " ")}\n" $stdout.flush end else raise Error, body['message'] end end # Convert long github urls into short git.io ones # # @param [String] url # @return [String] shortened url, or long url if shortening fails def shorten(url) request = Net::HTTP::Post.new("/create") request.set_form_data(:url => url) response = http(GIT_IO_URL, request) case response.code when "200" URI.join(GIT_IO_URL, response.body).to_s when "201" response['Location'] else url end end # Convert github url into raw file url # # Unfortunately the url returns from github's api is legacy, # we have to taking a HTTPRedirection before appending it # with '/raw'. Let's looking forward for github's api fix :) # # @param [String] url # @return [String] the raw file url def rawify(url) uri = URI(url) request = Net::HTTP::Get.new(uri.path) response = http(uri, request) if Net::HTTPSuccess === response url + '/raw' elsif Net::HTTPRedirection === response rawify(response.header['location']) end end # Log the user into gist. # + def login!(credentials = {}) + if (login_url == GITHUB_URL || ENV.key?(CLIENT_ID_ENV_NAME)) && credentials.empty? && !ENV.key?('GIST_USE_USERNAME_AND_PASSWORD') + device_flow_login! + else + access_token_login!(credentials) + end + end + + def device_flow_login! + puts "Requesting login parameters..." + request = Net::HTTP::Post.new("/login/device/code") + request.body = JSON.dump({ + :scope => 'gist', + :client_id => client_id, + }) + request.content_type = 'application/json' + request['accept'] = "application/json" + response = http(login_url, request) + + if response.code != '200' + raise Error, "HTTP #{response.code}: #{response.body}" + end + + body = JSON.parse(response.body) + + puts "Please sign in at #{body['verification_uri']}" + puts " and enter code: #{body['user_code']}" + device_code = body['device_code'] + interval = body['interval'] + + loop do + sleep(interval.to_i) + request = Net::HTTP::Post.new("/login/oauth/access_token") + request.body = JSON.dump({ + :client_id => client_id, + :grant_type => 'urn:ietf:params:oauth:grant-type:device_code', + :device_code => device_code + }) + request.content_type = 'application/json' + request['Accept'] = 'application/json' + response = http(login_url, request) + if response.code != '200' + raise Error, "HTTP #{response.code}: #{response.body}" + end + body = JSON.parse(response.body) + break unless body['error'] == 'authorization_pending' + end + + if body['error'] + raise Error, body['error_description'] + end + + AuthTokenFile.write JSON.parse(response.body)['access_token'] + + puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/connections/applications/#{client_id}" + end + + # Logs the user into gist. + # # This method asks the user for a username and password, and tries to obtain # and OAuth2 access token, which is then stored in ~/.gist # # @raise [Gist::Error] if something went wrong - # @param [Hash] credentials login details - # @option credentials [String] :username - # @option credentials [String] :password # @see http://developer.github.com/v3/oauth/ - def login!(credentials={}) - puts "Obtaining OAuth2 access_token from github." + def access_token_login!(credentials = {}) + puts "Obtaining OAuth2 access_token from GitHub." loop do print "GitHub username: " username = credentials[:username] || $stdin.gets.strip print "GitHub password: " password = credentials[:password] || begin - `stty -echo` rescue nil - $stdin.gets.strip - ensure - `stty echo` rescue nil - end + `stty -echo` rescue nil + $stdin.gets.strip + ensure + `stty echo` rescue nil + end puts "" request = Net::HTTP::Post.new("#{base_path}/authorizations") request.body = JSON.dump({ - :scopes => [:gist], - :note => "The gist gem (#{Time.now})", - :note_url => "https://github.com/ConradIrwin/gist" - }) + :scopes => [:gist], + :note => "The gist gem (#{Time.now})", + :note_url => "https://github.com/ConradIrwin/gist" + }) request.content_type = 'application/json' request.basic_auth(username, password) response = http(api_url, request) if Net::HTTPUnauthorized === response && response['X-GitHub-OTP'] print "2-factor auth code: " twofa_code = $stdin.gets.strip puts "" request['X-GitHub-OTP'] = twofa_code response = http(api_url, request) end if Net::HTTPCreated === response AuthTokenFile.write JSON.parse(response.body)['token'] puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens" return elsif Net::HTTPUnauthorized === response puts "Error: #{JSON.parse(response.body)['message']}" next else raise "Got #{response.class} from gist: #{response.body}" end end rescue => e raise e.extend Error end # Return HTTP connection # # @param [URI::HTTP] The URI to which to connect # @return [Net::HTTP] def http_connection(uri) env = ENV['http_proxy'] || ENV['HTTP_PROXY'] connection = if env proxy = URI(env) - Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port) + if proxy.user + Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(uri.host, uri.port) + else + Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port) + end else Net::HTTP.new(uri.host, uri.port) end if uri.scheme == "https" connection.use_ssl = true connection.verify_mode = OpenSSL::SSL::VERIFY_NONE end connection.open_timeout = 10 connection.read_timeout = 10 connection end # Run an HTTP operation # # @param [URI::HTTP] The URI to which to connect # @param [Net::HTTPRequest] The request to make # @return [Net::HTTPResponse] def http(url, request) request['User-Agent'] = USER_AGENT http_connection(url).start do |http| http.request request end rescue Timeout::Error raise "Could not connect to #{api_url}" end # Called after an HTTP response to gist to perform post-processing. # # @param [String] body the text body from the github api # @param [Hash] options more detailed options, see # the documentation for {multi_gist} - def on_success(body, options={}) + def on_success(body, options = {}) json = JSON.parse(body) output = case options[:output] when :javascript %Q{<script src="#{json['html_url']}.js"></script>} when :html_url json['html_url'] when :raw_url rawify(json['html_url']) when :short_url shorten(json['html_url']) when :short_raw_url shorten(rawify(json['html_url'])) else json end Gist.copy(output.to_s) if options[:copy] Gist.open(json['html_url']) if options[:open] output end # Copy a string to the clipboard. # # @param [String] content # @raise [Gist::Error] if no clipboard integration could be found # def copy(content) IO.popen(clipboard_command(:copy), 'r+') { |clip| clip.print content } unless paste == content message = 'Copying to clipboard failed.' if ENV["TMUX"] && clipboard_command(:copy) == 'pbcopy' message << "\nIf you're running tmux on a mac, try http://robots.thoughtbot.com/post/19398560514/how-to-copy-and-paste-with-tmux-on-mac-os-x" end raise Error, message end rescue Error => e raise ClipboardError, e.message + "\nAttempted to copy: #{content}" end # Get a string from the clipboard. # # @param [String] content # @raise [Gist::Error] if no clipboard integration could be found def paste `#{clipboard_command(:paste)}` end # Find command from PATH environment. # # @param [String] cmd command name to find # @param [String] options PATH environment variable # @return [String] the command found - def which(cmd, path=ENV['PATH']) + def which(cmd, path = ENV['PATH']) if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/ - path.split(File::PATH_SEPARATOR).each {|dir| - f = File.join(dir, cmd+".exe") + path.split(File::PATH_SEPARATOR).each { |dir| + f = File.join(dir, cmd + ".exe") return f if File.executable?(f) && !File.directory?(f) } nil else return system("which #{cmd} > /dev/null 2>&1") end end # Get the command to use for the clipboard action. # # @param [Symbol] action either :copy or :paste # @return [String] the command to run # @raise [Gist::ClipboardError] if no clipboard integration could be found def clipboard_command(action) command = CLIPBOARD_COMMANDS.keys.detect do |cmd| which cmd end raise ClipboardError, <<-EOT unless command Could not find copy command, tried: #{CLIPBOARD_COMMANDS.values.join(' || ')} EOT action == :copy ? command : CLIPBOARD_COMMANDS[command] end # Open a URL in a browser. # # @param [String] url # @raise [RuntimeError] if no browser integration could be found # # This method was heavily inspired by defunkt's Gist#open, # @see https://github.com/defunkt/gist/blob/bca9b29/lib/gist.rb#L157 def open(url) command = if ENV['BROWSER'] ENV['BROWSER'] elsif RUBY_PLATFORM =~ /darwin/ 'open' elsif RUBY_PLATFORM =~ /linux/ %w( sensible-browser xdg-open firefox firefox-bin ).detect do |cmd| which cmd end elsif ENV['OS'] == 'Windows_NT' || RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw|wince/i 'start ""' else raise "Could not work out how to use a browser." end `#{command} #{url}` end # Get the API base path def base_path ENV.key?(URL_ENV_NAME) ? GHE_BASE_PATH : GITHUB_BASE_PATH end + def login_url + ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_URL + end + # Get the API URL def api_url ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_API_URL end + def client_id + ENV.key?(CLIENT_ID_ENV_NAME) ? URI(ENV[CLIENT_ID_ENV_NAME]) : GITHUB_CLIENT_ID + end + def legacy_private_gister? return unless which('git') `git config --global gist.private` =~ /\Ayes|1|true|on\z/i end - def should_be_public?(options={}) + def should_be_public?(options = {}) if options.key? :private !options[:private] else !Gist.legacy_private_gister? end end -end +end \ No newline at end of file
binaryage/totalfinder-i18n
8eb426165afa731fd37ba13160e69ca2fa33ea92
crashwatcher: add .idea to gitignores
diff --git a/crashwatcher/ruby/.gitignore b/crashwatcher/ruby/.gitignore new file mode 100644 index 0000000..723ef36 --- /dev/null +++ b/crashwatcher/ruby/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file
binaryage/totalfinder-i18n
8263f2d33115cefc45eb2e78bca6fb07dc758224
crashwatcher: update rubocop config and make it happy again
diff --git a/crashwatcher/ruby/.rubocop.yml b/crashwatcher/ruby/.rubocop.yml index 5257a13..11edbbd 100644 --- a/crashwatcher/ruby/.rubocop.yml +++ b/crashwatcher/ruby/.rubocop.yml @@ -1,64 +1,65 @@ AllCops: - TargetRubyVersion: 2.6 + TargetRubyVersion: 2.7 Include: - '**/*.rb' - '**/Gemfile' - '**/Rakefile' - '**/rakefile' Exclude: - '_node/**/*' - 'vendor/**/*' + NewCops: enable Metrics/LineLength: Max: 126 Layout/SpaceAroundEqualsInParameterDefault: EnforcedStyle: no_space Metrics/MethodLength: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false Metrics/BlockNesting: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/ClassLength: Enabled: false Style/Documentation: Enabled: false -Layout/IndentFirstArrayElement: +Layout/FirstArrayElementIndentation: Enabled: false Style/GuardClause: Enabled: false Metrics/PerceivedComplexity: Enabled: false Style/TernaryParentheses: Enabled: false Style/RegexpLiteral: Enabled: false Style/RescueStandardError: Enabled: false Style/SafeNavigation: Enabled: false -Lint/HandleExceptions: +Lint/SuppressedException: Enabled: false Style/SpecialGlobalVars: Enabled: false diff --git a/crashwatcher/ruby/extract-crash-info.rb b/crashwatcher/ruby/extract-crash-info.rb index f9923ca..5788ace 100755 --- a/crashwatcher/ruby/extract-crash-info.rb +++ b/crashwatcher/ruby/extract-crash-info.rb @@ -1,115 +1,115 @@ #!/usr/bin/env ruby # frozen_string_literal: true def parse_module_version(content) m = content.match(/\+\s*com.binaryage.totalfinder\s*\((.*?)\)/m) return nil if m.nil? # m[1] == 1.5.18 - 1.5.18 m[1].split('-')[0].strip end def parse_special_info(content) # "recent swizzled method" can appear in TotalFinder crash logs since v1.4.18 m = content.match(/recent swizzled method:(.*?)\n/m) return nil if m.nil? m[1].strip end def parse_plugin_identifier(content) m = content.match(/PlugIn Identifier:(.*?)\n/m) return nil if m.nil? m[1] end def find_first_ba_module(content) addresses = [] ranges = [] content.lines.each do |line| # extract addresses from callstacks on all threads # 8 com.apple.AppKit 0x00007fff88a0d68f -[NSApplication run] + 395 addresses << Regexp.last_match(1).to_i(16) if line =~ /^\s*\d+\s+.*?0x([0-9a-f]+)\s/ # extract loaded module ranges, filter out only com.binaryage related # 0x1181c2000 - 0x1181c3ff7 +com.binaryage.totalfinder.nodesktopdots ##VERSION## (##VERSION##) <...> /some/path if line =~ /^\s*0x([0-9a-f]+)\s+-\s+0x([0-9a-f]+)\s+.*?(com\.binaryage.*?)\s/ ranges << [Regexp.last_match(1).to_i(16), Regexp.last_match(2).to_i(16), Regexp.last_match(3)] end end # test if any address is present inside our ranges addresses.each do |address| ranges.each do |range| hit = address >= range[0] && address <= range[1] return range[2] if hit end end nil end file = File.absolute_path(ARGV[0]) # this is just a special sanity check to include related-crash-report.rb errors in case related-crash-report.rb throws related_script_path = File.join(File.dirname(File.absolute_path(__FILE__)), 'related-crash-report.rb') system(related_script_path, file, err: :out) result = $?.exitstatus throw "The crash report '#{file}' is not related to TotalFinder" if result != 3 content = File.read(file) res = 'TotalFinder ' begin module_version = parse_module_version(content) res += "#{module_version} " if module_version plugin = parse_special_info(content) plugin ||= parse_plugin_identifier(content) plugin ||= find_first_ba_module(content) plugin.strip! if plugin - res += 'crashed in ' + plugin.gsub('com.binaryage.totalfinder.', '') + ' ' if plugin + res += "crashed in #{plugin.gsub('com.binaryage.totalfinder.', '')} " if plugin rescue # ignored end details = [] begin version = content.match(/Version:(.*?)\n/m)[1].split(' ')[0] - details << 'v' + version.strip + details << "v#{version.strip}" rescue # ignored end begin version = content.match(/OS Version:.*?\((.*?)\)\n/m)[1] - details << 'OS ' + version.strip + details << "OS #{version.strip}" rescue # ignored end begin type = content.match(/Exception Type:(.*?)\n/m)[1] x = type.match(/(.*?)\(.*\)/) type = x[1] if x # remove braced part if present type.downcase! type.sub!('exc_', '') type.sub!('_', ' ') details << type.strip rescue # ignored end begin thread = content.match(/Crashed Thread:(.*?)\n/m)[1].split(' ')[0] - details << 'thread ' + thread.strip + details << "thread #{thread.strip}" rescue # ignored end res += "| #{details.join(', ')}" puts res
binaryage/totalfinder-i18n
b2774b9505f3589140ef6c5cc922a38a10e77bc7
add gray icon for preferences toolbar under Big Sur
diff --git a/plugin/totalfinder_gray.png b/plugin/totalfinder_gray.png new file mode 100644 index 0000000..09eda26 Binary files /dev/null and b/plugin/totalfinder_gray.png differ
binaryage/totalfinder-i18n
1a84139976b29dbb4afdb04b95f2b993de73fc5b
migrate about preferences to WKWebView and tweak constraints
diff --git a/plugin/ShellPreferences.xib b/plugin/ShellPreferences.xib index 97aa7cf..2bbeb65 100644 --- a/plugin/ShellPreferences.xib +++ b/plugin/ShellPreferences.xib @@ -1,320 +1,317 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="17140" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> - <plugIn identifier="com.apple.WebKitIBPlugin" version="15400"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="17140"/> + <plugIn identifier="com.apple.WebKit2IBPlugin" version="17140"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="TFShellPreferencesController"> <connections> - <outlet property="$aboutContent" destination="133" id="228"/> + <outlet property="$aboutContent" destination="Eql-JN-ZhJ" id="oqr-Ms-hyJ"/> <outlet property="$aboutPreferences" destination="1" id="229"/> <outlet property="$dockPreferences" destination="333" id="365"/> <outlet property="$menusPreferences" destination="316" id="366"/> <outlet property="$registerButton" destination="96" id="233"/> <outlet property="$registeredTo" destination="95" id="232"/> <outlet property="$registrationPreferences" destination="7" id="230"/> <outlet property="$tabsPreferences" destination="8uq-4v-kht" id="iLo-k4-P2D"/> <outlet property="$titleInAbout" destination="293" id="303"/> <outlet property="$titleInRegistration" destination="97" id="304"/> <outlet property="$titleInUpdates" destination="258" id="305"/> <outlet property="$updatesPreferences" destination="87" id="231"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="7" userLabel="Registration Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="101"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="440" translatesAutoresizingMaskIntoConstraints="NO" id="97"> <rect key="frame" x="18" y="53" width="444" height="28"/> <constraints> <constraint firstAttribute="width" constant="440" id="hTq-0b-4ws"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="98"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="96"> <rect key="frame" x="20" y="2" width="61" height="19"/> <buttonCell key="cell" type="roundRect" title="Register" bezelStyle="roundedRect" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="99"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="cellTitle"/> </buttonCell> <connections> <action selector="$showLicensingWindow:" target="-2" id="306"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="95"> <rect key="frame" x="18" y="29" width="146" height="16"/> <textFieldCell key="cell" lineBreakMode="truncatingTail" sendsActionOnEndEditing="YES" title="Registered to John Doe" usesSingleLineMode="YES" id="100"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="97" firstAttribute="top" secondItem="7" secondAttribute="top" constant="20" symbolic="YES" id="120"/> <constraint firstItem="97" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="121"/> <constraint firstItem="95" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="128"/> <constraint firstItem="96" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="130"/> <constraint firstItem="95" firstAttribute="top" secondItem="97" secondAttribute="bottom" constant="8" symbolic="YES" id="246"/> <constraint firstItem="96" firstAttribute="top" secondItem="95" secondAttribute="bottom" constant="8" symbolic="YES" id="247"/> </constraints> <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="215" userLabel="Registration Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="7" id="217"/> <outlet property="owner_" destination="-2" id="216"/> </connections> </customObject> <customView id="87" userLabel="Updates Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="140"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="152"> - <rect key="frame" x="38" y="42" width="203" height="11"/> + <rect key="frame" x="38" y="44" width="205" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Automatically check the website for updates" id="162"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="154"> - <rect key="frame" x="38" y="5" width="152" height="11"/> + <rect key="frame" x="38" y="5" width="153" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Participate in TotalFinder testing" id="161"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button translatesAutoresizingMaskIntoConstraints="NO" id="155" userLabel="Check Box"> - <rect key="frame" x="18" y="18" width="152" height="18"/> + <rect key="frame" x="18" y="19" width="159" height="18"/> <buttonCell key="cell" type="check" title="^Include pre-releases" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="160"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderUsePreReleases" id="211"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="156"> - <rect key="frame" x="18" y="55" width="142" height="18"/> + <rect key="frame" x="18" y="58" width="148" height="18"/> <buttonCell key="cell" type="check" title="^Check for Updates" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="159"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderCheckForUpdates" id="Mgr-b0-keU"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="157"> - <rect key="frame" x="165" y="56" width="78" height="16"/> + <rect key="frame" x="172" y="57" width="74" height="16"/> <buttonCell key="cell" type="push" title="^Check Now" bezelStyle="rounded" alignment="center" controlSize="mini" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="158"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="miniSystem"/> </buttonCell> <connections> <action selector="$checkForUpdates:" target="-2" id="235"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="258"> - <rect key="frame" x="18" y="92" width="194" height="28"/> + <rect key="frame" x="18" y="92" width="191" height="28"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="259"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="156" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="196"/> <constraint firstItem="157" firstAttribute="leading" secondItem="156" secondAttribute="trailing" constant="8" symbolic="YES" id="197"/> <constraint firstItem="155" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="204"/> <constraint firstItem="154" firstAttribute="leading" secondItem="152" secondAttribute="leading" id="205"/> <constraint firstItem="155" firstAttribute="top" secondItem="152" secondAttribute="bottom" constant="8" symbolic="YES" id="248"/> <constraint firstItem="258" firstAttribute="top" secondItem="87" secondAttribute="top" constant="20" symbolic="YES" id="262"/> <constraint firstItem="157" firstAttribute="bottom" secondItem="156" secondAttribute="bottom" id="267"/> <constraint firstItem="258" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="268"/> <constraint firstItem="157" firstAttribute="top" secondItem="87" secondAttribute="top" constant="68" id="269"/> <constraint firstItem="154" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="40" id="277"/> <constraint firstAttribute="bottom" secondItem="155" secondAttribute="bottom" constant="20" symbolic="YES" id="278"/> <constraint firstAttribute="bottom" secondItem="154" secondAttribute="bottom" constant="5" id="283"/> <constraint firstItem="154" firstAttribute="top" secondItem="155" secondAttribute="bottom" constant="4" id="284"/> <constraint firstItem="152" firstAttribute="top" secondItem="156" secondAttribute="bottom" constant="4" id="285"/> </constraints> </customView> <customObject id="218" userLabel="Updates Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="87" id="224"/> <outlet property="owner_" destination="-2" id="219"/> </connections> </customObject> <customView id="1" userLabel="About Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="227"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> - <webView translatesAutoresizingMaskIntoConstraints="NO" id="133"> - <rect key="frame" x="20" y="28" width="440" height="119"/> - <constraints> - <constraint firstAttribute="height" constant="119" id="307"/> - </constraints> - <webPreferences key="preferences" defaultFontSize="12" defaultFixedFontSize="12"> - <nil key="identifier"/> - </webPreferences> + <wkWebView wantsLayer="YES" allowsLinkPreview="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Eql-JN-ZhJ"> + <rect key="frame" x="20" y="26" width="440" height="121"/> + <wkWebViewConfiguration key="configuration" allowsAirPlayForMediaPlayback="NO"> + <audiovisualMediaTypes key="mediaTypesRequiringUserActionForPlayback" none="YES"/> + <wkPreferences key="preferences"/> + </wkWebViewConfiguration> <connections> - <outlet property="policyDelegate" destination="-2" id="236"/> + <outlet property="navigationDelegate" destination="-2" id="Vbx-6W-if8"/> </connections> - </webView> + </wkWebView> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="440" translatesAutoresizingMaskIntoConstraints="NO" id="134"> - <rect key="frame" x="18" y="155" width="444" height="16"/> + <rect key="frame" x="18" y="155" width="207" height="16"/> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Thank you for using TotalFinder!" usesSingleLineMode="YES" id="135"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="293"> <rect key="frame" x="18" y="179" width="444" height="28"/> - <constraints> - <constraint firstAttribute="width" constant="440" id="25p-5M-1IT"/> - </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="294"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="308"> - <rect key="frame" x="20" y="-1" width="182" height="19"/> + <rect key="frame" x="20" y="-1" width="184" height="19"/> <buttonCell key="cell" type="roundRect" title="^Reset TotalFinder to defaults" bezelStyle="roundedRect" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="309"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="cellTitle"/> </buttonCell> <connections> <action selector="$resetToDefaults:" target="-2" id="315"/> </connections> </button> </subviews> <constraints> - <constraint firstItem="133" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="148"/> - <constraint firstAttribute="trailing" secondItem="133" secondAttribute="trailing" constant="20" symbolic="YES" id="150"/> <constraint firstItem="293" firstAttribute="top" secondItem="1" secondAttribute="top" constant="20" symbolic="YES" id="297"/> <constraint firstItem="293" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="298"/> <constraint firstItem="308" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="312"/> <constraint firstItem="308" firstAttribute="bottom" secondItem="1" secondAttribute="bottom" id="314"/> <constraint firstItem="134" firstAttribute="leading" secondItem="293" secondAttribute="leading" id="Cxh-45-C83"/> <constraint firstItem="134" firstAttribute="top" secondItem="293" secondAttribute="bottom" constant="8" symbolic="YES" id="Omi-6z-SoP"/> - <constraint firstItem="134" firstAttribute="trailing" secondItem="133" secondAttribute="trailing" id="iWI-4i-aCd"/> - <constraint firstItem="133" firstAttribute="top" secondItem="134" secondAttribute="bottom" constant="8" symbolic="YES" id="lyt-Gf-2Gt"/> + <constraint firstItem="Eql-JN-ZhJ" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="gfi-IP-7vv"/> + <constraint firstAttribute="trailing" secondItem="293" secondAttribute="trailing" constant="20" symbolic="YES" id="h8U-fO-ZuI"/> + <constraint firstAttribute="trailing" secondItem="Eql-JN-ZhJ" secondAttribute="trailing" constant="20" symbolic="YES" id="hwM-lS-swU"/> + <constraint firstItem="Eql-JN-ZhJ" firstAttribute="top" secondItem="134" secondAttribute="bottom" constant="8" symbolic="YES" id="iw5-5v-851"/> + <constraint firstItem="308" firstAttribute="top" secondItem="Eql-JN-ZhJ" secondAttribute="bottom" constant="8" symbolic="YES" id="klM-UO-YWF"/> </constraints> + <point key="canvasLocation" x="139" y="150"/> </customView> <customObject id="221" userLabel="About Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="225"/> <outlet property="owner_" destination="-2" id="222"/> </connections> </customObject> <customView id="333" userLabel="Dock Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="34"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="348"> - <rect key="frame" x="18" y="8" width="171" height="18"/> + <rect key="frame" x="18" y="8" width="177" height="18"/> <buttonCell key="cell" type="check" title="^Keep original Dock icon" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="349"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderDontCustomizeDockIcon" id="369"/> </connections> </button> </subviews> <constraints> <constraint firstItem="348" firstAttribute="leading" secondItem="333" secondAttribute="leading" constant="20" symbolic="YES" id="356"/> <constraint firstItem="348" firstAttribute="centerY" secondItem="333" secondAttribute="centerY" id="370"/> </constraints> </customView> <customView id="8uq-4v-kht" userLabel="Tabs Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="64"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="J6d-M3-FOb"> - <rect key="frame" x="18" y="37" width="173" height="18"/> + <rect key="frame" x="18" y="36" width="180" height="18"/> <buttonCell key="cell" type="check" title="^Disable tabs completely" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="eeg-k4-55d"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <action selector="$disableTabsCompletely:" target="-2" id="OeT-jd-1nq"/> <binding destination="94" name="value" keyPath="values.TotalFinderTabsDisabled" id="xA9-mr-Dgn"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="wo8-mU-gzk"> - <rect key="frame" x="39" y="20" width="357" height="11"/> + <rect key="frame" x="39" y="18" width="358" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^This will effectively disable tabs, dual mode and visor. Finder restart is needed." id="2MQ-dx-5TV"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="J6d-M3-FOb" firstAttribute="leading" secondItem="8uq-4v-kht" secondAttribute="leading" constant="20" symbolic="YES" id="J6s-HG-TwS"/> <constraint firstItem="J6d-M3-FOb" firstAttribute="top" secondItem="8uq-4v-kht" secondAttribute="top" constant="11" id="LbD-yg-Erj"/> <constraint firstItem="wo8-mU-gzk" firstAttribute="leading" secondItem="J6d-M3-FOb" secondAttribute="leading" constant="21" id="lfA-yT-amC"/> <constraint firstItem="wo8-mU-gzk" firstAttribute="top" secondItem="J6d-M3-FOb" secondAttribute="bottom" constant="8" id="pO7-UY-2E2"/> </constraints> </customView> <customObject id="345" userLabel="Dock Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="333" id="358"/> <outlet property="owner_" destination="-2" id="347"/> </connections> </customObject> <customObject id="mbL-Rz-ge5" userLabel="Tabs Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="8uq-4v-kht" id="ahm-Fv-KC7"/> <outlet property="owner_" destination="-2" id="4OD-Ed-CB4"/> </connections> </customObject> <customView id="316" userLabel="Menus Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="34"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="317"> - <rect key="frame" x="18" y="8" width="161" height="18"/> + <rect key="frame" x="18" y="8" width="167" height="18"/> <buttonCell key="cell" type="check" title="^Hide icon in Menu Bar" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="318"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderShowStatusItem" id="367"> <dictionary key="options"> <string key="NSValueTransformerName">NSNegateBoolean</string> </dictionary> </binding> </connections> </button> </subviews> <constraints> <constraint firstItem="317" firstAttribute="leading" secondItem="316" secondAttribute="leading" constant="20" symbolic="YES" id="322"/> <constraint firstItem="317" firstAttribute="centerY" secondItem="316" secondAttribute="centerY" id="371"/> </constraints> </customView> <customObject id="342" userLabel="Menus Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="316" id="357"/> <outlet property="owner_" destination="-2" id="344"/> </connections> </customObject> <userDefaultsController id="94" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document>
binaryage/totalfinder-i18n
9964331c16520a6136ec71b43ed1ed9126251938
Fixed typo on line 08
diff --git a/crashwatcher/es.lproj/Localizable.strings b/crashwatcher/es.lproj/Localizable.strings index c45e35e..468107e 100644 --- a/crashwatcher/es.lproj/Localizable.strings +++ b/crashwatcher/es.lproj/Localizable.strings @@ -1,20 +1,20 @@ "crashDialogHeader" = "TotalFinder se ha cerrado inesperadamente"; "crashDialogMsg" = "Lo sentimos, pero ha habido un problema inesperado con TotalFinder y Finder se cerró."; "crashDialogNote" = "Nota: Finder fue reiniciado automáticamente, pero debe abrir TotalFinder manualmente para volver a utilizarlo."; "crashDialogExplanation" = "El botón Enviar subirá un reporte sobre el error a gist.github.com, y abrirá una ventana de Mail con una plantilla."; "failDialogHeader" = "No se pudo subir el informe de error a gist.github.com"; "failDialogMsg1" = "Ouch! No pude encontrar el informe de error en ~/Logs/CrashReporter."; -"failDialogMsg2" = "Pude encontrar el informe de error, pero por alguna razon no pude subirlo a gist.github.com\n\n%@\n\nSi es urgente me lo puedes mandar manualmente:\n%@"; +"failDialogMsg2" = "Pude encontrar el informe de error, pero por alguna razón no pude subirlo a gist.github.com\n\n%@\n\nSi es urgente me lo puedes mandar manualmente:\n%@"; "failDialogOK" = "OK"; -"sendReportButton" = "Enviar email"; +"sendReportButton" = "Enviar correo electrónico"; "cancelButton" = "Cancelar"; "emailTemplate" = "Hi Antonin,\n\nMy %@ just crashed!\n\nThe crash report is available here:\n%@\n\n>\n> Podrías ayudarme explicando que pasó antes del fallo.\n> Aprecio tu ayuda y leo los informes de errores, pero, por favor, no esperes una respuesta directa de mí.\n> Para obtener más ayuda, abre un tema en:\n> https://discuss.binaryage.com.\n>\n> Gracias, Antonin"; "countdownMsgSecondsPlural" = "Faltan %d segundos."; "countdownMsgSecondSingular" = "Falta %d segundo."; "countdownMsgMinutesPlural" = "Faltan %d minutos."; "countdownMsgMinuteSingular" = "Falta %d minuto.";
binaryage/totalfinder-i18n
ad44793fb23cc33fa063ad76a5aed4307d44c252
remove "Freelance Windows" localizations
diff --git a/plugin/ar.lproj/Tabs.strings b/plugin/ar.lproj/Tabs.strings index 44d336c..4ad32cb 100644 --- a/plugin/ar.lproj/Tabs.strings +++ b/plugin/ar.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - نسخة غير مسجلة"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - بقي يوم واحد - اشتر الآن!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - بقي يومان - اشتر الآن!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - بقي ثلاثة أيام - اشتر الآن!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - بقي أربعة أيام - اشتر الآن!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - بقي خمسة أيام - اشتر الآن!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - بقي %d ايام - اشتر الآن!"; "Close Tab" = "اغلق علامة التبويب"; "Toggle Dual Mode" = "غير وضع ثنائي الواجهة"; "New Tab" = "علامة تبويب جديدة"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "استعمل لوحة علامات تبويب ضيقة"; "Open new tabs with previous location" = "افتح علامات تبويب جديدة بأماكن قديمة"; - -/* preferences */ -"Freelance Windows" = "نوافذ مستقلة"; diff --git a/plugin/be.lproj/Tabs.strings b/plugin/be.lproj/Tabs.strings index dc50ca3..593c1c8 100644 --- a/plugin/be.lproj/Tabs.strings +++ b/plugin/be.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - незарэгістраваная версія"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - застаўся 1 дзень - купіце зараз!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - засталося 2 дні - купіце зараз!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - засталося 3 дні - купіце зараз!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - засталося 4 дні - купіце зараз!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - засталося 5 дзен - купіце зараз!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - засталося %d днен - купіце зараз!"; "Close Tab" = "Зачыніць укладку"; "Toggle Dual Mode" = "Здвоены рэжым"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Вузкая панэль укладак"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Незалежныя вокны"; diff --git a/plugin/bg.lproj/Tabs.strings b/plugin/bg.lproj/Tabs.strings index 649f8e6..f9f859d 100644 --- a/plugin/bg.lproj/Tabs.strings +++ b/plugin/bg.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - нерегистрирана версия"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - Остава 1 ден - Купете сега!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - Остават 2 дни - Купете сега!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - Остават 3 дни - Купете сега!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - Остават 4 дни - Купете сега!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - Остават 5 дни - Купете сега!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - Остават %d дни - Купете сега!"; "Close Tab" = "Затвори раздела"; "Toggle Dual Mode" = "Двупанелен режим"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Тясна лента с раздели"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Независими прозорци"; diff --git a/plugin/bn.lproj/Tabs.strings b/plugin/bn.lproj/Tabs.strings index 132f0d0..09b7be2 100644 --- a/plugin/bn.lproj/Tabs.strings +++ b/plugin/bn.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "টোটালফাইন্ডার - নিবন্ধিত হয়নি"; "TotalFinder - 1 day left - buy now!" = "টোটালফাইন্ডার - ১ দিন বাকী - নিবন্ধন করো!"; "TotalFinder - 2 days left - buy now!" = "টোটালফাইন্ডার - ২ দিন বাকী - নিবন্ধন করো!"; "TotalFinder - 3 days left - buy now!" = "টোটালফাইন্ডার - ৩ দিন বাকী - নিবন্ধন করো!"; "TotalFinder - 4 days left - buy now!" = "টোটালফাইন্ডার - ৪ দিন বাকী - নিবন্ধন করো!"; "TotalFinder - 5 days left - buy now!" = "টোটালফাইন্ডার - ৫ দিন বাকী - নিবন্ধন করো!"; "TotalFinder - %d days left - buy now!" = "টোটালফাইন্ডার - %d দিন বাকী - নিবন্ধন করো!"; "Close Tab" = "ট্যাব বন্ধ"; "Toggle Dual Mode" = "ডুয়েল মোড টগল করবে"; "New Tab" = "নতুন ট্যাব"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "চিকন ট্যাব বার ব্যবহার করবে"; "Open new tabs with previous location" = "আগের লোকেশনে নতুন ট্যাব খুলবে"; - -/* preferences */ -"Freelance Windows" = "ফ্রিল্যান্স উইন্ডোজ"; diff --git a/plugin/ca.lproj/Tabs.strings b/plugin/ca.lproj/Tabs.strings index 9bb7f5a..f8f26ef 100644 --- a/plugin/ca.lproj/Tabs.strings +++ b/plugin/ca.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versió sense registrar"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - Queda 1 dia - compri ara!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - Queden 2 dies - compri ara!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - Queden 3 dies - compri ara!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - Queden 4 dies - compri ara!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - Queden 5 dies - compri ara"; "TotalFinder - %d days left - buy now!" = "TotalFinder - Queden %d dies - compri ara!"; "Close Tab" = "Tancar pestanya"; "Toggle Dual Mode" = "Activar/desactivar mode dual"; "New Tab" = "Nova pestanya"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "Fer servir una barrar de pestanyes estreta"; "Open new tabs with previous location" = "Obrir noves pestanyes amb la ruta prèvia"; - -/* preferences */ -"Freelance Windows" = "No agrupar les finestres"; diff --git a/plugin/cs.lproj/Tabs.strings b/plugin/cs.lproj/Tabs.strings index 02f0b26..2835dff 100644 --- a/plugin/cs.lproj/Tabs.strings +++ b/plugin/cs.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - neregistrovaná verze"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - zbývá 1 den - koupit teď!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - zbývají 2 dny - koupit teď!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - zbývají 3 dny - koupit teď!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - zbývají 4 dny - koupit teď!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - zbývá 5 dnů - koupit teď!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - zbývá %d dnů - koupit teď!"; "Close Tab" = "Zavřít tab"; "Toggle Dual Mode" = "Přepnout dualní panel"; "New Tab" = "Nový tab"; "Use narrow Tabs Bar" = "Štíhlé taby"; "Open new tabs with previous location" = "Otevírat nové taby v předchozí lokaci"; - -/* preferences */ -"Freelance Windows" = "Volná okna"; diff --git a/plugin/cy.lproj/Tabs.strings b/plugin/cy.lproj/Tabs.strings index 64f2f51..5a9e868 100644 --- a/plugin/cy.lproj/Tabs.strings +++ b/plugin/cy.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - Fersiwn digofrestredig"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - chwith 1 diwrnod - brynu nawr!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - chwith 2 ddiwrnod - brynu nawr!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - Gadawodd 3 diwrnod - brynu nawr!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - chwith 4 diwrnod - brynu nawr!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - Gadawodd 5 diwrnod - brynu nawr!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - Gadawodd %d diwrnod - brynu nawr!"; "Close Tab" = "Tab Agos"; "Toggle Dual Mode" = "Modd togl deuol"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Defnyddiwch y bar cul Tabs"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Ffenestri Llawrydd"; diff --git a/plugin/da.lproj/Tabs.strings b/plugin/da.lproj/Tabs.strings index e1a11f8..6ed6040 100644 --- a/plugin/da.lproj/Tabs.strings +++ b/plugin/da.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - ikke-registreret version"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dag tilbage - køb nu!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dage tilbage - køb nu!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dage tilbage - køb nu!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dage tilbage - køb nu!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dage tilbage - køb nu!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dage tilbage - køb nu!"; "Close Tab" = "Luk fane"; "Toggle Dual Mode" = "Skift Dual-mode"; "New Tab" = "Ny fane"; "Use narrow Tabs Bar" = "Brug smal fanebar"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Freelance vinduer"; diff --git a/plugin/de.lproj/Tabs.strings b/plugin/de.lproj/Tabs.strings index 98968f1..962879e 100644 --- a/plugin/de.lproj/Tabs.strings +++ b/plugin/de.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - Unregistrierte Version"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 Tag verbleibend - jetzt kaufen!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 Tage verbleibend - jetzt kaufen!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 Tage verbleibend - jetzt kaufen!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 Tage verbleibend - jetzt kaufen!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 Tage verbleibend - jetzt kaufen!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d Tage verbleibend - jetzt kaufen!"; "Close Tab" = "Tab schließen"; "Toggle Dual Mode" = "Dual-Modus an/aus"; "New Tab" = "Neuer Tab"; "Use narrow Tabs Bar" = "Benutze schmale Tableiste"; "Open new tabs with previous location" = "Neue Tabs an zuletzt besuchtem Ort öffnen"; - -/* preferences */ -"Freelance Windows" = "Unabhängige Fenster"; diff --git a/plugin/el.lproj/Tabs.strings b/plugin/el.lproj/Tabs.strings index e4eafb5..8a8c378 100644 --- a/plugin/el.lproj/Tabs.strings +++ b/plugin/el.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - αδήλωτη έκδοση"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 ημέρα έμεινε - αγορά!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 ημέρες έμειναν - αγορά!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 ημέρες έμειναν - αγορά!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 ημέρες έμειναν - αγορά!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 ημέρες έμειναν - αγορά!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d ημέρες έμειναν - αγορά!"; "Close Tab" = "Κλείσιμο καρτέλας"; "Toggle Dual Mode" = "Εναλλαγή Dual mode"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Σμίκρυνση καρτελών"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Ελεύθερα παράθυρα"; diff --git a/plugin/en.lproj/Tabs.strings b/plugin/en.lproj/Tabs.strings index 5b0df93..c5d96cb 100644 --- a/plugin/en.lproj/Tabs.strings +++ b/plugin/en.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - unregistered version"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 day left - buy now!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 days left - buy now!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 days left - buy now!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 days left - buy now!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 days left - buy now!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d days left - buy now!"; "Close Tab" = "Close Tab"; "Toggle Dual Mode" = "Toggle Dual Mode"; "New Tab" = "New Tab"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "Use narrow Tabs Bar"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Freelance Windows"; diff --git a/plugin/es.lproj/Tabs.strings b/plugin/es.lproj/Tabs.strings index 905fe49..b54ca40 100644 --- a/plugin/es.lproj/Tabs.strings +++ b/plugin/es.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versión no registrada"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 día restante - ¡cómpralo ahora!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 días restantes - ¡cómpralo ahora!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 días restantes - ¡cómpralo ahora!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 días restantes - ¡cómpralo ahora!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 días restantes - ¡cómpralo ahora!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d días restantes - ¡cómpralo ahora!"; "Close Tab" = "Cerrar pestaña"; "Toggle Dual Mode" = "Desplegar modo dual"; "New Tab" = "Nueva pestaña"; "Use narrow Tabs Bar" = "Usar barra de pestañas estrecha"; "Open new tabs with previous location" = "Abrir nuevas pestañas en la carpeta actual"; - -/* preferences */ -"Freelance Windows" = "No agrupar ventanas"; diff --git a/plugin/et.lproj/Tabs.strings b/plugin/et.lproj/Tabs.strings index 4e12b3c..0ed436f 100644 --- a/plugin/et.lproj/Tabs.strings +++ b/plugin/et.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - registreerimata versioon"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 päev jäänud - osta kohe!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 päeva jäänud - osta kohe!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 päeva jäänud - osta kohe!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 päeva jäänud - osta kohe!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 päeva jäänud - osta kohe!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d päeva jäänud - osta kohe!"; "Close Tab" = "Sulge Vaheleht"; "Toggle Dual Mode" = "Lülitu Paarisaknarežiimi"; "New Tab" = "Uus Vaheleht"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "Kitsas Vaheleheriba"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Ava Uues Aknas"; diff --git a/plugin/fi.lproj/Tabs.strings b/plugin/fi.lproj/Tabs.strings index 9bec4dd..2f5bf87 100644 --- a/plugin/fi.lproj/Tabs.strings +++ b/plugin/fi.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - rekisteröimätön versio"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 päivä jäljellä - osta nyt!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 päivää jäljellä - osta nyt!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 päivää jäljellä - osta nyt!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 päivää jäljellä - osta nyt!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 päivää jäljellä - osta nyt!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d päivää jäljellä - osta nyt!"; "Close Tab" = "Sulje välilehti"; "Toggle Dual Mode" = "Kaksoispaneeliselaus"; "New Tab" = "Uusi välilehti"; "Use narrow Tabs Bar" = "Ohuempi välilehtipalkki"; "Open new tabs with previous location" = "Avaa edelliset välilehdet uudelleen"; - -/* preferences */ -"Freelance Windows" = "Älä avaa uusia ikkunoita välilehtiin"; diff --git a/plugin/fr.lproj/Tabs.strings b/plugin/fr.lproj/Tabs.strings index 8e26520..0f9ed86 100644 --- a/plugin/fr.lproj/Tabs.strings +++ b/plugin/fr.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - version non enregistrée"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - Encore 1 jour - Acheter !"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - Encore 2 jours - Acheter !"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - Encore 3 jours - Acheter !"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - Encore 4 jours - Acheter !"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - Encore 5 jours - Acheter !"; "TotalFinder - %d days left - buy now!" = "TotalFinder - Encore %d jours - Acheter !"; "Close Tab" = "Fermer l'onglet"; "Toggle Dual Mode" = "Commuter le mode double"; "New Tab" = "Nouvel onglet"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "Utiliser une barre d'onglets compacte"; "Open new tabs with previous location" = "Ouvrir les nouveaux onglets sur le dernier emplacement"; - -/* preferences */ -"Freelance Windows" = "Ouvrir dans une nouvelle fenêtre"; diff --git a/plugin/he.lproj/Tabs.strings b/plugin/he.lproj/Tabs.strings index 2c03a38..485ab78 100644 --- a/plugin/he.lproj/Tabs.strings +++ b/plugin/he.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - גירסה אינה רשומה"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - יום אחד נותר - רכוש כעת!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 ימים נותרו - רכוש כעת!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 ימים נותרו - רכוש כעת!!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 ימים נותרו - רכוש כעת!!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 ימים נותרו - רכוש כעת!!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d ימים נותרו - רכוש כעת!!"; "Close Tab" = "סגור לשונית Finder"; "Toggle Dual Mode" = "החלף מצב כפול"; "New Tab" = "לשונית חדשה"; "Use narrow Tabs Bar" = "השתמש בשורת לשוניות מצומצמת"; "Open new tabs with previous location" = "פתח לשוניות חדשות מהמיקום האחרון"; - -/* preferences */ -"Freelance Windows" = "חלונות חופשיים"; diff --git a/plugin/hi.lproj/Tabs.strings b/plugin/hi.lproj/Tabs.strings index f5a1054..ae353ab 100644 --- a/plugin/hi.lproj/Tabs.strings +++ b/plugin/hi.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "टोटलफ़ाइंडर - अपंजीकृत संस्करण"; "TotalFinder - 1 day left - buy now!" = "टोटलफ़ाइंडर - १ दिन बाकी - अभी खरीदें!"; "TotalFinder - 2 days left - buy now!" = "टोटलफ़ाइंडर - २ दिन बाकी - अभी खरीदें!"; "TotalFinder - 3 days left - buy now!" = "टोटलफ़ाइंडर - ३ दिन बाकी - अभी खरीदें!"; "TotalFinder - 4 days left - buy now!" = "टोटलफ़ाइंडर - ४ दिन बाकी - अभी खरीदें!"; "TotalFinder - 5 days left - buy now!" = "टोटलफ़ाइंडर - ५ दिन बाकी - अभी खरीदें!"; "TotalFinder - %d days left - buy now!" = "टोटलफ़ाइंडर - %d दिन बाकी - अभी खरीदें!"; "Close Tab" = "टैब बंद करें"; "Toggle Dual Mode" = "दोहरा अंदाज़ शुरू या बंद करें"; "New Tab" = "नया टैब"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "संकीर्ण टैब पट्टी का प्रयोग करें"; "Open new tabs with previous location" = "नया टैब पिछले स्थान के साथ खोलें"; - -/* preferences */ -"Freelance Windows" = "फ्रीलांस विंडोज"; diff --git a/plugin/hr.lproj/Tabs.strings b/plugin/hr.lproj/Tabs.strings index b7e250e..0b9bbdf 100644 --- a/plugin/hr.lproj/Tabs.strings +++ b/plugin/hr.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - neregistrirana verzija"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dan preostao - kupi sada!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dana preostalo - kupi sada!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dana preostalo - kupi sada!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dana preostalo - kupi sada!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dana preostalo - kupi sada!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dana preostalo - kupi sada!"; "Close Tab" = "Zatvori karticu"; "Toggle Dual Mode" = "Prebaci Dual môd"; "New Tab" = "Nova kartica"; "Use narrow Tabs Bar" = "Koristi usku traku kartica"; "Open new tabs with previous location" = "Otvori nove kartice prethodnih lokacija"; - -/* preferences */ -"Freelance Windows" = "Plutajući prozori"; diff --git a/plugin/hu.lproj/Tabs.strings b/plugin/hu.lproj/Tabs.strings index 3eeae4c..a9b92f8 100644 --- a/plugin/hu.lproj/Tabs.strings +++ b/plugin/hu.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - Nem regisztrált verzió"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 nap maradt - vásárlás most!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 nap maradt - vásárlás most!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 nap maradt - vásárlás most!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 nap maradt - vásárlás most!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 nap maradt - vásárlás most!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d nap maradt - vásárlás most!"; "Close Tab" = "Fül bezárása"; "Toggle Dual Mode" = "Váltás kettős módra"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Keskeny fülek használata"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Szabadúszó ablak"; diff --git a/plugin/id.lproj/Tabs.strings b/plugin/id.lproj/Tabs.strings index f6fe1bb..516c78a 100644 --- a/plugin/id.lproj/Tabs.strings +++ b/plugin/id.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versi belum teregistrasi"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 hari tersisa - beli sekarang!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 hari tersisa - beli sekarang!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 hari tersisa - beli sekarang!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 hari tersisa - beli sekarang!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 hari tersisa - beli sekarang!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d hari tersisa - beli sekarang!"; "Close Tab" = "Tutup Tab"; "Toggle Dual Mode" = "Aktifkan Mode Dual"; "New Tab" = "Tab Baru"; "Use narrow Tabs Bar" = "Gunakan Tabs Bar sempit"; "Open new tabs with previous location" = "Buka tab baru dari lokasi sebelumnya"; - -/* preferences */ -"Freelance Windows" = "Jendela Freelance"; diff --git a/plugin/it.lproj/Tabs.strings b/plugin/it.lproj/Tabs.strings index b7dc9d9..edd5b16 100644 --- a/plugin/it.lproj/Tabs.strings +++ b/plugin/it.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versione non registrata"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 giorno rimasto - acquista adesso!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 giorni rimasti - acquista adesso!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 giorni rimasti - acquista adesso!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 giorni rimasti - acquista adesso!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 giorni rimasti - acquista adesso!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d giorni rimasti - acquista adesso!"; "Close Tab" = "Chiudi scheda"; "Toggle Dual Mode" = "Vista a doppio pannello"; "New Tab" = "Nuova scheda"; "Use narrow Tabs Bar" = "Barra delle schede ridotta"; "Open new tabs with previous location" = "Apri le nuove schede nella posizione precedente"; - -/* preferences */ -"Freelance Windows" = "Finestre libere"; diff --git a/plugin/ja.lproj/Tabs.strings b/plugin/ja.lproj/Tabs.strings index d816a28..733c7e6 100644 --- a/plugin/ja.lproj/Tabs.strings +++ b/plugin/ja.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - 未登録"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 試用期限の残りはあと 1 日です - 購入してください!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 2 日です - 購入してください!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 3 日です - 購入してください!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 4 日です - 購入してください!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 試用期限の残りはあと 5 日です - 購入してください!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - 試用期限の残りはあと %d 日です - 購入してください!"; "Close Tab" = "タブを閉じる"; "Toggle Dual Mode" = "デュアルモードの切替"; "New Tab" = "新規タブ"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "タブバーを狭くする"; "Open new tabs with previous location" = "以前の場所を新規のタブで開く"; - -/* preferences */ -"Freelance Windows" = "タブの代わりに新しいウィンドウで開く"; diff --git a/plugin/ko.lproj/Tabs.strings b/plugin/ko.lproj/Tabs.strings index ee893a9..0e35995 100644 --- a/plugin/ko.lproj/Tabs.strings +++ b/plugin/ko.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - 체험판"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 체험 기간이 1일 남았습니다 - 지금 구매하세요!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 체험 기간이 2일 남았습니다 - 지금 구매하세요!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 체험 기간이 3일 남았습니다 - 지금 구매하세요!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 체험 기간이 4일 남았습니다 - 지금 구매하세요!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 체험 기간이 5일 남았습니다 - 지금 구매하세요!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - 체험 기간이 %d일 남았습니다 - 지금 구매하세요!"; "Close Tab" = "탭 닫기"; "Toggle Dual Mode" = "듀얼 모드 단축키"; "New Tab" = "새 탭"; "Use narrow Tabs Bar" = "탭 칸 세로폭 줄임"; "Open new tabs with previous location" = "이전 위치에서 새 탭 열기"; - -/* preferences */ -"Freelance Windows" = "프리랜스 윈도우"; diff --git a/plugin/lt.lproj/Tabs.strings b/plugin/lt.lproj/Tabs.strings index 76c2645..83b6efd 100644 --- a/plugin/lt.lproj/Tabs.strings +++ b/plugin/lt.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - Neregistruota versija"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - liko 1 diena - pirkite dabar!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - liko 2 dienos - pirkite dabar!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - liko 3 dienos - pirkite dabar!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - liko 4 dienos - pirkite dabar!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - liko 5 dienos - pirkite dabar!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - liko %d dienos - pirkite dabar!"; "Close Tab" = "Užverti kortelę"; "Toggle Dual Mode" = "Į(iš)jungti dvigubą režimą"; "New Tab" = "Nauja kortelė"; "Use narrow Tabs Bar" = "Naudoti siaurą kortelių juostą"; "Open new tabs with previous location" = "Atidaryti naujas korteles su ankstesnėmis vietomis"; - -/* preferences */ -"Freelance Windows" = "Išoriškai atidaromi langai nepaverčiami kortelėmis"; diff --git a/plugin/mk.lproj/Tabs.strings b/plugin/mk.lproj/Tabs.strings index ebdf55c..85b9da6 100644 --- a/plugin/mk.lproj/Tabs.strings +++ b/plugin/mk.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - нерегистрирана верзија"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - преостанат 1 ден - купете го сега!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - преостанати 2 дена - купете го сега!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - преостанати 3 дена - купете го сега!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - преостанати 4 дена - купете го сега!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - преостанати 5 дена - купете го сега!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - преостанати %d дена - купете го сега!"; "Close Tab" = "Затвори Јазиче"; "Toggle Dual Mode" = "Изменичен Двоен Мод"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Тенка Линија со Јазичиња"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Слободни прозорци"; diff --git a/plugin/mn.lproj/Tabs.strings b/plugin/mn.lproj/Tabs.strings index e1b39fc..e6ef759 100644 --- a/plugin/mn.lproj/Tabs.strings +++ b/plugin/mn.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - бүртгэлгүй хувилбар"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 хоног үлдлээ - худалдаж ав!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 хоног үлдлээ - худалдаж ав!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 хоног үлдлээ - худалдаж ав!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 хоног үлдлээ - худалдаж ав!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 хоног үлдлээ - худалдаж ав!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d хоног үлдлээ - худалдаж ав!"; "Close Tab" = "Tab хаах"; "Toggle Dual Mode" = "Дуал горим"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Нарийн таб бар"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Freelance цонхнууд"; diff --git a/plugin/ms.lproj/Tabs.strings b/plugin/ms.lproj/Tabs.strings index 64d6553..35282b7 100644 --- a/plugin/ms.lproj/Tabs.strings +++ b/plugin/ms.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versi tidak berdaftar"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - tinggal 1 hari - beli sekarang!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - tinggal 2 hari - beli sekarang!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - tinggal 3 hari - beli sekarang!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - tinggal 4 hari - beli sekarang!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - tinggal 5 hari - beli sekarang!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - tinggal %d hari - buy now!"; "Close Tab" = "Tutup Tab"; "Toggle Dual Mode" = "Togol Mod Dual"; "New Tab" = "Tab Baru"; /* the tooltip of the "plus button" in tabs bar */ "Use narrow Tabs Bar" = "Gunakan Bar Tab kecil"; "Open new tabs with previous location" = "Buka tab baru dengan lokasi terdahulu"; - -/* preferences */ -"Freelance Windows" = "Tetingkap Bebas"; diff --git a/plugin/nl.lproj/Tabs.strings b/plugin/nl.lproj/Tabs.strings index 303fedd..6fb758c 100644 --- a/plugin/nl.lproj/Tabs.strings +++ b/plugin/nl.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - ongeregistreerde versie"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - nog 1 dag - koop nu!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - nog 2 dagen - koop nu!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - nog 3 dagen - koop nu!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - nog 4 dagen - koop nu!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - nog 5 dagen - koop nu!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - nog %d dagen - koop nu!"; "Close Tab" = "Sluit tabblad"; "Toggle Dual Mode" = "Dubbele/enkele kolom"; "New Tab" = "Nieuw tabblad"; "Use narrow Tabs Bar" = "Gebruik smalle tabbalk"; "Open new tabs with previous location" = "Open nieuwe tabs met de vorige locatie"; - -/* preferences */ -"Freelance Windows" = "Freelance-schermen"; diff --git a/plugin/nn.lproj/Tabs.strings b/plugin/nn.lproj/Tabs.strings index b00a410..bbb082f 100644 --- a/plugin/nn.lproj/Tabs.strings +++ b/plugin/nn.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - uregistrert versjon"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dag igjen - kjøp nå!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dagar igjen - kjøp nå!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dagar igjen - kjøp nå!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dagar igjen - kjøp nå!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dagar igjen - kjøp nå!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dagar igjen - kjøp nå!"; "Close Tab" = "Lukk fane"; "Toggle Dual Mode" = "Skru av/på Dual Mode"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Bruk smale fanar"; "Open new tabs with previous location" = "Åpne nye fanar i forrige lokasjon"; - -/* preferences */ -"Freelance Windows" = "Freelance-vindaugar"; diff --git a/plugin/no.lproj/Tabs.strings b/plugin/no.lproj/Tabs.strings index 425c072..1bdea6a 100644 --- a/plugin/no.lproj/Tabs.strings +++ b/plugin/no.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - uregistrert versjon"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dag igjen - kjøp nå!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dager igjen - kjøp nå!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dager igjen - kjøp nå!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dager igjen - kjøp nå!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dager igjen - kjøp nå!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dager igjen - kjøp nå!"; "Close Tab" = "Lukk fane"; "Toggle Dual Mode" = "Skru av/på Dual Mode"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Bruk smale faner"; "Open new tabs with previous location" = "Åpne nye faner i forrige lokasjon"; - -/* preferences */ -"Freelance Windows" = "Freelance-vinduer"; diff --git a/plugin/pl.lproj/Tabs.strings b/plugin/pl.lproj/Tabs.strings index 1bfced8..c250fe1 100644 --- a/plugin/pl.lproj/Tabs.strings +++ b/plugin/pl.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - niezarejestrowana wersja"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - Pozostał jeden dzień - kup teraz!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - Pozostały dwa dni - kup teraz!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - Pozostały trzy dni - kup teraz!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - Pozostały cztery dni- kup teraz!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - Pozostało pięć - kup teraz!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - Pozostało %d dni - kup teraz!"; "Close Tab" = "Zamknij kartę"; "Toggle Dual Mode" = "Wł/wył tryb podwójny"; "New Tab" = "Nowa zakładka"; "Use narrow Tabs Bar" = "Użyj wąskiego paska zakładek"; "Open new tabs with previous location" = "Otwieraj nową kartę z aktualną ścieżką"; - -/* preferences */ -"Freelance Windows" = "Wolne okna"; diff --git a/plugin/pt.lproj/Tabs.strings b/plugin/pt.lproj/Tabs.strings index d926d3e..f9c6090 100644 --- a/plugin/pt.lproj/Tabs.strings +++ b/plugin/pt.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versão não registrada"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dia para testar - compre agora!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dias para testar - compre agora!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dias para testar - compre agora!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dias para testar - compre agora!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dias para testar - compre agora!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dias para testar - compre agora!"; "Close Tab" = "Fechar Aba"; "Toggle Dual Mode" = "Ativar Modo Duplo"; "New Tab" = "Nova Aba"; "Use narrow Tabs Bar" = "Utilizar barra com abas finas"; "Open new tabs with previous location" = "Abrir novas abas com o local anterior"; - -/* preferences */ -"Freelance Windows" = "Janelas Autônomas"; diff --git a/plugin/pt_BR.lproj/Tabs.strings b/plugin/pt_BR.lproj/Tabs.strings index d926d3e..f9c6090 100644 --- a/plugin/pt_BR.lproj/Tabs.strings +++ b/plugin/pt_BR.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versão não registrada"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dia para testar - compre agora!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dias para testar - compre agora!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dias para testar - compre agora!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dias para testar - compre agora!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dias para testar - compre agora!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dias para testar - compre agora!"; "Close Tab" = "Fechar Aba"; "Toggle Dual Mode" = "Ativar Modo Duplo"; "New Tab" = "Nova Aba"; "Use narrow Tabs Bar" = "Utilizar barra com abas finas"; "Open new tabs with previous location" = "Abrir novas abas com o local anterior"; - -/* preferences */ -"Freelance Windows" = "Janelas Autônomas"; diff --git a/plugin/pt_PT.lproj/Tabs.strings b/plugin/pt_PT.lproj/Tabs.strings index d926d3e..f9c6090 100644 --- a/plugin/pt_PT.lproj/Tabs.strings +++ b/plugin/pt_PT.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versão não registrada"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dia para testar - compre agora!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dias para testar - compre agora!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dias para testar - compre agora!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dias para testar - compre agora!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dias para testar - compre agora!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dias para testar - compre agora!"; "Close Tab" = "Fechar Aba"; "Toggle Dual Mode" = "Ativar Modo Duplo"; "New Tab" = "Nova Aba"; "Use narrow Tabs Bar" = "Utilizar barra com abas finas"; "Open new tabs with previous location" = "Abrir novas abas com o local anterior"; - -/* preferences */ -"Freelance Windows" = "Janelas Autônomas"; diff --git a/plugin/ro.lproj/Tabs.strings b/plugin/ro.lproj/Tabs.strings index a646565..7d31bd7 100644 --- a/plugin/ro.lproj/Tabs.strings +++ b/plugin/ro.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - versiune neînregistrată"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 zi rămasă - Cumpară acum!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 zile rămase - Cumpară acum!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 zile rămase - Cumpară acum!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 zile rămase - Cumpară acum!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 zile rămase - Cumpară acum!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d zile rămase - Cumpară acum!"; "Close Tab" = "Închide tab"; "Toggle Dual Mode" = "Comută în modul dual"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Tab-uri înguste"; "Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Ferestre Libere"; diff --git a/plugin/ru.lproj/Tabs.strings b/plugin/ru.lproj/Tabs.strings index d0a6126..9e8c8d8 100644 --- a/plugin/ru.lproj/Tabs.strings +++ b/plugin/ru.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - незарегистрированная версия"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - остался 1 день - купите сейчас!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - осталось 2 дня - купите сейчас!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - осталось 3 дня - купите сейчас!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - осталось 4 дня - купите сейчас!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - осталось 5 дней - купите сейчас!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - осталось %d дней - купите сейчас!"; "Close Tab" = "Закрыть вкладку"; "Toggle Dual Mode" = "Двухпанельный режим"; "New Tab" = "Новая вкладка"; "Use narrow Tabs Bar" = "Узкая панель вкладок"; "Open new tabs with previous location" = "Открывать новые вкладки с прежним местоположением"; - -/* preferences */ -"Freelance Windows" = "Независимые окна"; diff --git a/plugin/sk.lproj/Tabs.strings b/plugin/sk.lproj/Tabs.strings index 2094d30..81474ec 100644 --- a/plugin/sk.lproj/Tabs.strings +++ b/plugin/sk.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - neregistrovaná verzia"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - zostáva 1 deň - kúpiť teraz!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - zostávajú 2 dni - kúpiť teraz!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - zostávajú 3 dni - kúpiť teraz!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - zostávajú 4 dni - kúpiť teraz!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - zostáva 5 dní - kúpiť teraz!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - zostáva %d dní - kúpiť teraz!"; "Close Tab" = "Zatvoriť tab"; "Toggle Dual Mode" = "Prepnúť na dual panel"; "New Tab" = "Nový tab"; "Use narrow Tabs Bar" = "Úzke taby"; "Open new tabs with previous location" = "Otvárať nové taby v predchádzajúcom adresári"; - -/* preferences */ -"Freelance Windows" = "Nezávislé okná"; diff --git a/plugin/sl.lproj/Tabs.strings b/plugin/sl.lproj/Tabs.strings index fd396ff..3e98089 100644 --- a/plugin/sl.lproj/Tabs.strings +++ b/plugin/sl.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - neregistrirana različica"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - do poteka samo še 1 dan - kupite zdaj!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - do poteka samo še 2 dneva - kupite zdaj!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - do poteka samo še 3 dnevi - kupite zdaj!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - do poteka samo še 4 dnevi - kupite zdaj!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - do poteka samo še 5 dni - kupite zdaj!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - do poteka samo še %d dni - kupite zdaj!"; "Close Tab" = "Zapri zavihek"; "Toggle Dual Mode" = "Preklopi v dvojni način"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "Uporabi ozko vrstico"; -"Open new tabs with previous location" = "Open new tabs with previous location"; - -/* preferences */ -"Freelance Windows" = "Premična okna"; +"Open new tabs with previous location" = "Open new tabs with previous location"; \ No newline at end of file diff --git a/plugin/sv.lproj/Tabs.strings b/plugin/sv.lproj/Tabs.strings index cdc5644..426f9c3 100644 --- a/plugin/sv.lproj/Tabs.strings +++ b/plugin/sv.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - oregistrerad version"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 dag kvar - köp nu!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 dagar kvar - köp nu!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 dagar kvar - köp nu!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 dagar kvar - köp nu!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 dagar kvar - köp nu!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d dagar kvar - köp nu!"; "Close Tab" = "Stäng flik"; "Toggle Dual Mode" = "Av-/Aktivera Dual Mode"; "New Tab" = "Ny flik"; "Use narrow Tabs Bar" = "Använd smalare Flikar"; "Open new tabs with previous location" = "Öppna nya flikar med tidigare sökvägar"; - -/* preferences */ -"Freelance Windows" = "Frilans Fönster"; diff --git a/plugin/th.lproj/Tabs.strings b/plugin/th.lproj/Tabs.strings index 68e7583..0daed42 100644 --- a/plugin/th.lproj/Tabs.strings +++ b/plugin/th.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - ทดลองใช้งาน"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - เหลือเวลา 1 วัน - ซื้อเดี๋ยวนี้!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - เหลือเวลา 2 วัน - ซื้อเดี๋ยวนี้!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - เหลือเวลา 3 วัน - ซื้อเดี๋ยวนี้!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - เหลือเวลา 4 วัน - ซื้อเดี๋ยวนี้!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - เหลือเวลา 5 วัน - ซื้อเดี๋ยวนี้!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - เหลือเวลา %d วัน - ซื้อเดี๋ยวนี้!"; "Close Tab" = "ปิดแท็บ"; "Toggle Dual Mode" = "เรียกใช้หน้าต่างคู่"; "New Tab" = "เปิดแท็บใหม่"; "Use narrow Tabs Bar" = "ใช้แถบแท็บแบบเล็ก"; "Open new tabs with previous location" = "เปิดแท็บใหม่โดยที่อยู่ก่อนหน้านี้"; - -/* preferences */ -"Freelance Windows" = "หน้าต่างอิสระ"; diff --git a/plugin/tr.lproj/Tabs.strings b/plugin/tr.lproj/Tabs.strings index 361b16b..0141846 100644 --- a/plugin/tr.lproj/Tabs.strings +++ b/plugin/tr.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - Lisanssız sürüm"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 gün kaldı - şimdi satın al!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 gün kaldı - şimdi satın al!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 gün kaldı - şimdi satın al!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 gün kaldı - şimdi satın al!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 gün kaldı - şimdi satın al!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - %d gün kaldı - şimdi satın al!"; "Close Tab" = "Sekmeyi Kapat"; "Toggle Dual Mode" = "Çift Pencereyi Aç/Kapat"; "New Tab" = "Yeni Sekme"; "Use narrow Tabs Bar" = "Dar sekme çubuğu kullan"; "Open new tabs with previous location" = "Yeni sekmeleri bir önceki konumda aç"; - -/* preferences */ -"Freelance Windows" = "Bağımsız pencereler"; diff --git a/plugin/uk.lproj/Tabs.strings b/plugin/uk.lproj/Tabs.strings index 9c1631d..2a006ee 100644 --- a/plugin/uk.lproj/Tabs.strings +++ b/plugin/uk.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - не зареєстрована версія"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - залишився 1 день - придбати зараз!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - залишилось 2 дні - придбати зараз!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - залишилось 3 дні - придбати зараз!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - залишилось 4 дні - придбати зараз!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - залишилось 5 днів - придбати зараз!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - залишилось %d днів - придбати зараз!"; "Close Tab" = "Закрити вкладку"; "Toggle Dual Mode" = "Двопанельний режим"; "New Tab" = "Нова вкладка"; "Use narrow Tabs Bar" = "Вузька панель вкладок"; "Open new tabs with previous location" = "Відкривати нові вкладки на пепередніх позиціях"; - -/* preferences */ -"Freelance Windows" = "Незалежні вікна"; diff --git a/plugin/vi.lproj/Tabs.strings b/plugin/vi.lproj/Tabs.strings index bdf2259..06aa76b 100644 --- a/plugin/vi.lproj/Tabs.strings +++ b/plugin/vi.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - phiên bản chưa đăng ký"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - còn 1 ngày -mua ngay!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - còn 2 ngày - mua ngay!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - còn 3 ngày - ngay!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - còn 4 ngày - mua ngay!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - còn 5 ngày - nagy!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - còn %d ngày - mua ngay!"; "Close Tab" = "Đóng Tab"; "Toggle Dual Mode" = "Kích hoạt chế độ hai của sổ"; "New Tab" = "Tab mới"; "Use narrow Tabs Bar" = "Sử dụng tab hẹp"; "Open new tabs with previous location" = "Mở nhiều tab mới với cùng vị trí cũ"; - -/* preferences */ -"Freelance Windows" = "Của sổ Freelance"; diff --git a/plugin/zh_CN.lproj/Tabs.strings b/plugin/zh_CN.lproj/Tabs.strings index 2f682d3..8be47a4 100644 --- a/plugin/zh_CN.lproj/Tabs.strings +++ b/plugin/zh_CN.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - 未注册版本"; "TotalFinder - 1 day left - buy now!" = "TotalFinder 试用剩余 1 天 请购买支持!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder 试用剩余 2 天 请购买支持!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder 试用剩余 3 天 请购买支持!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder 试用剩余 4 天 请购买支持!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder 试用剩余 5 天 请购买支持!"; "TotalFinder - %d days left - buy now!" = "TotalFinder 试用剩余 %d 天 请购买支持!"; "Close Tab" = "关闭标签页"; "Toggle Dual Mode" = "切换单/双窗口模式"; "New Tab" = "新建标签页"; "Use narrow Tabs Bar" = "标签栏紧凑模式"; "Open new tabs with previous location" = "在以前的位置打开新标签"; - -/* preferences */ -"Freelance Windows" = "新窗口不于标签页打开"; diff --git a/plugin/zh_HK.lproj/Tabs.strings b/plugin/zh_HK.lproj/Tabs.strings index a7ef76c..1f48fe7 100644 --- a/plugin/zh_HK.lproj/Tabs.strings +++ b/plugin/zh_HK.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - 未註冊版本"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 剩餘 1 天 - 立即購買!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 剩餘 2 天 - 立即購買!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 剩餘 3 天 - 立即購買!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 剩餘 4 天 - 立即購買!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 剩餘 5 天 - 立即購買!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - 剩餘 %d 天 - 立即購買!"; "Close Tab" = "關閉分頁"; "Toggle Dual Mode" = "切換雙視窗模式"; "New Tab" = "新增分頁"; "Use narrow Tabs Bar" = "使用較窄分頁列"; "Open new tabs with previous location" = "於上一個位置開啟新分頁"; - -/* preferences */ -"Freelance Windows" = "於新視窗開啟新分頁"; diff --git a/plugin/zh_TW.lproj/Tabs.strings b/plugin/zh_TW.lproj/Tabs.strings index 00a3c2f..06964ba 100644 --- a/plugin/zh_TW.lproj/Tabs.strings +++ b/plugin/zh_TW.lproj/Tabs.strings @@ -1,16 +1,13 @@ "TotalFinder - unregistered version" = "TotalFinder - 未註冊版本"; "TotalFinder - 1 day left - buy now!" = "TotalFinder - 剩下 1 天 - 馬上購買!"; "TotalFinder - 2 days left - buy now!" = "TotalFinder - 剩下 2 天 - 馬上購買!"; "TotalFinder - 3 days left - buy now!" = "TotalFinder - 剩下 3 天 - 馬上購買!"; "TotalFinder - 4 days left - buy now!" = "TotalFinder - 剩下 4 天 - 馬上購買!"; "TotalFinder - 5 days left - buy now!" = "TotalFinder - 剩下 5 天 - 馬上購買!"; "TotalFinder - %d days left - buy now!" = "TotalFinder - 剩下 %d 天 - 馬上購買!"; "Close Tab" = "關閉分頁"; "Toggle Dual Mode" = "切換雙視窗模式"; "New Tab" = "New Tab"; "Use narrow Tabs Bar" = "使用較窄分頁列"; "Open new tabs with previous location" = "在新分頁開啟上一頁"; - -/* preferences */ -"Freelance Windows" = "於新視窗開啟新分頁";
binaryage/totalfinder-i18n
00830ec423c60a793dd38a3479bf6641d43de2b0
remove "Freelance Windows" check box from UI
diff --git a/plugin/TabsPreferences.xib b/plugin/TabsPreferences.xib index fe9da02..c340792 100644 --- a/plugin/TabsPreferences.xib +++ b/plugin/TabsPreferences.xib @@ -1,103 +1,91 @@ <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="TabsPluginPreferencesController"> <connections> <outlet property="$tabsPreferences" destination="1" id="70"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Tabs Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="139"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> - <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="11"> - <rect key="frame" x="18" y="66" width="159" height="18"/> + <button translatesAutoresizingMaskIntoConstraints="NO" id="11"> + <rect key="frame" x="18" y="67" width="153" height="18"/> <buttonCell key="cell" type="check" title="^Use narrow Tabs Bar" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="12"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderNarrowTabsBar" id="13"/> </connections> </button> - <textField verticalHuggingPriority="750" misplaced="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="19"> - <rect key="frame" x="18" y="102" width="124" height="17"/> + <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="19"> + <rect key="frame" x="18" y="103" width="120" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Toggle Dual Mode" id="20"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> - <customView misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="32" customClass="MASShortcutView"> - <rect key="frame" x="183" y="66" width="130" height="19"/> + <customView translatesAutoresizingMaskIntoConstraints="NO" id="32" customClass="MASShortcutView"> + <rect key="frame" x="177" y="67" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="73"/> <constraint firstAttribute="width" constant="130" id="126"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="NarrowTabsBar"/> </userDefinedRuntimeAttributes> </customView> - <customView misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="49" customClass="MASShortcutView"> - <rect key="frame" x="148" y="101" width="130" height="19"/> + <customView translatesAutoresizingMaskIntoConstraints="NO" id="49" customClass="MASShortcutView"> + <rect key="frame" x="144" y="102" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="74"/> <constraint firstAttribute="width" constant="130" id="124"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="DualMode"/> </userDefinedRuntimeAttributes> </customView> - <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="75"> - <rect key="frame" x="18" y="32" width="151" height="18"/> - <buttonCell key="cell" type="check" title="^Freelance Windows" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="76"> - <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> - <font key="font" metaFont="system"/> - </buttonCell> - <connections> - <binding destination="4" name="value" keyPath="values.TotalFinderDontMakeTabs" id="88"/> - </connections> - </button> - <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="102"> - <rect key="frame" x="18" y="-2" width="262" height="18"/> + <button translatesAutoresizingMaskIntoConstraints="NO" id="102"> + <rect key="frame" x="18" y="33" width="255" height="18"/> <buttonCell key="cell" type="check" title="^Open new tabs with previous location" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="103"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderNewTabsWithCurrentTarget" id="110"/> </connections> </button> </subviews> <constraints> <constraint firstItem="49" firstAttribute="leading" secondItem="19" secondAttribute="trailing" constant="8" symbolic="YES" id="136"/> <constraint firstItem="19" firstAttribute="top" secondItem="1" secondAttribute="top" constant="20" symbolic="YES" id="149"/> <constraint firstItem="49" firstAttribute="centerY" secondItem="19" secondAttribute="centerY" id="150"/> <constraint firstItem="11" firstAttribute="top" secondItem="19" secondAttribute="bottom" constant="20" id="153"/> <constraint firstItem="32" firstAttribute="centerY" secondItem="11" secondAttribute="centerY" id="156"/> <constraint firstItem="32" firstAttribute="leading" secondItem="11" secondAttribute="trailing" constant="8" symbolic="YES" id="157"/> <constraint firstItem="11" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="158"/> <constraint firstItem="19" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="159"/> - <constraint firstItem="75" firstAttribute="top" secondItem="11" secondAttribute="bottom" constant="20" id="160"/> <constraint firstItem="102" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="169"/> - <constraint firstItem="75" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="171"/> - <constraint firstItem="102" firstAttribute="top" secondItem="75" secondAttribute="bottom" constant="20" id="E1e-Ie-UVr"/> + <constraint firstItem="102" firstAttribute="top" secondItem="11" secondAttribute="bottom" constant="20" id="EyF-gb-0fw"/> </constraints> <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="Tabs Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="72"/> <outlet property="owner_" destination="-2" id="71"/> </connections> </customObject> <userDefaultsController id="4" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document>
binaryage/totalfinder-i18n
0b5aedeb90b530ac133e72bb04cef069436d3aaf
re-save xib files under Xcode 11.1
diff --git a/crashwatcher/CrashWatcher.xib b/crashwatcher/CrashWatcher.xib index b3fd664..45829db 100644 --- a/crashwatcher/CrashWatcher.xib +++ b/crashwatcher/CrashWatcher.xib @@ -1,157 +1,158 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14105" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14105"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="Reporter"> <connections> <outlet property="alertWindow_" destination="1" id="142"/> <outlet property="cancelButton_" destination="14" id="158"/> <outlet property="commentMessage_" destination="8" id="154"/> <outlet property="countdownLabel_" destination="189" id="208"/> <outlet property="dialogExplanation_" destination="225" id="227"/> <outlet property="dialogNote_" destination="222" id="224"/> <outlet property="dialogTitle_" destination="3" id="155"/> <outlet property="progressIndicator_" destination="228" id="229"/> <outlet property="sendButton_" destination="12" id="159"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> - <window allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" oneShot="NO" showsToolbarButton="NO" visibleAtLaunch="NO" animationBehavior="default" id="1" userLabel="Window"> + <window allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" visibleAtLaunch="NO" animationBehavior="default" id="1" userLabel="Window"> <windowStyleMask key="styleMask" titled="YES" resizable="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="72" y="251" width="490" height="190"/> <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1417"/> <value key="minSize" type="size" width="490" height="190"/> <view key="contentView" id="2"> - <rect key="frame" x="0.0" y="0.0" width="490" height="190"/> + <rect key="frame" x="0.0" y="0.0" width="490" height="189"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView translatesAutoresizingMaskIntoConstraints="NO" id="6"> - <rect key="frame" x="8" y="56" width="128" height="128"/> + <rect key="frame" x="8" y="55" width="128" height="128"/> <constraints> <constraint firstAttribute="height" constant="128" id="N4d-df-rsY"/> <constraint firstAttribute="width" constant="128" id="nRO-BI-KaR"/> </constraints> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="CrashWatcher" id="220"/> </imageView> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" preferredMaxLayoutWidth="308" translatesAutoresizingMaskIntoConstraints="NO" id="8"> <rect key="frame" x="160" y="116" width="312" height="28"/> <constraints> <constraint firstAttribute="width" constant="308" id="ep4-1j-s1A"/> </constraints> <textFieldCell key="cell" controlSize="small" sendsActionOnEndEditing="YES" title="We are sorry, but TotalXXX hit an unexpected problem and crashed XXX." id="217"> - <font key="font" metaFont="smallSystem"/> + <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" preferredMaxLayoutWidth="308" translatesAutoresizingMaskIntoConstraints="NO" id="222"> <rect key="frame" x="160" y="94" width="312" height="14"/> <textFieldCell key="cell" controlSize="small" sendsActionOnEndEditing="YES" title="Note: You have to launch TotalXXX.app again manually." id="223"> - <font key="font" metaFont="smallSystem"/> + <font key="font" metaFont="message" size="11"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" preferredMaxLayoutWidth="308" translatesAutoresizingMaskIntoConstraints="NO" id="225"> <rect key="frame" x="160" y="58" width="312" height="28"/> <textFieldCell key="cell" controlSize="small" sendsActionOnEndEditing="YES" title="The send button will upload the crash report to gist.github.com and launch Mail.app with email template." id="226"> - <font key="font" metaFont="smallSystem"/> + <font key="font" metaFont="message" size="11"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" preferredMaxLayoutWidth="308" translatesAutoresizingMaskIntoConstraints="NO" id="3"> - <rect key="frame" x="160" y="152" width="312" height="18"/> + <rect key="frame" x="160" y="152" width="312" height="17"/> <constraints> <constraint firstAttribute="width" constant="308" id="esB-1A-UKM"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="TotalXXX has quit unexpectedly!" id="219"> <font key="font" metaFont="systemBold" size="14"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="12"> <rect key="frame" x="331" y="5" width="145" height="32"/> <buttonCell key="cell" type="push" title="SendReportLabel" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="210"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> DQ </string> </buttonCell> <connections> <action selector="sendReport:" target="-2" id="45"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="14"> <rect key="frame" x="182" y="5" width="145" height="32"/> <constraints> <constraint firstAttribute="width" relation="lessThanOrEqual" constant="150" id="qL7-xf-iqK"/> </constraints> <buttonCell key="cell" type="push" title="CancelLabel" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="211"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> Gw </string> </buttonCell> <connections> <action selector="cancel:" target="-2" id="46"/> </connections> </button> <textField verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="189"> - <rect key="frame" x="19" y="15" width="67" height="14"/> + <rect key="frame" x="19" y="14" width="67" height="14"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="xx seconds." id="221"> - <font key="font" metaFont="smallSystem"/> + <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="-2" name="value" keyPath="countdownMessage" id="194"/> </connections> </textField> <progressIndicator hidden="YES" wantsLayer="YES" horizontalHuggingPriority="750" verticalHuggingPriority="750" maxValue="100" bezeled="NO" indeterminate="YES" controlSize="small" style="spinning" translatesAutoresizingMaskIntoConstraints="NO" id="228"> <rect key="frame" x="305" y="15" width="16" height="16"/> </progressIndicator> </subviews> <constraints> <constraint firstItem="8" firstAttribute="top" secondItem="3" secondAttribute="bottom" constant="8" id="2UK-wL-YGM"/> <constraint firstItem="14" firstAttribute="width" secondItem="12" secondAttribute="width" priority="500" id="2jq-EV-dzG"/> <constraint firstAttribute="bottom" secondItem="12" secondAttribute="bottom" constant="12" id="9me-5A-EE4"/> <constraint firstItem="14" firstAttribute="top" secondItem="12" secondAttribute="top" id="9wp-44-KPV"/> <constraint firstItem="3" firstAttribute="leading" secondItem="6" secondAttribute="trailing" constant="26" id="EyX-dV-gxp"/> <constraint firstItem="3" firstAttribute="leading" secondItem="225" secondAttribute="leading" id="Fod-2X-2kX"/> <constraint firstItem="225" firstAttribute="top" secondItem="222" secondAttribute="bottom" constant="8" id="HWY-n4-6hv"/> <constraint firstItem="6" firstAttribute="top" secondItem="2" secondAttribute="top" constant="6" id="SGI-1o-Nmk"/> <constraint firstItem="12" firstAttribute="leading" secondItem="228" secondAttribute="trailing" constant="16" id="SWD-Jv-Tl5"/> <constraint firstItem="8" firstAttribute="width" secondItem="222" secondAttribute="width" id="Tc0-mn-SmI"/> <constraint firstItem="12" firstAttribute="top" secondItem="228" secondAttribute="top" constant="-2" id="Vpk-NY-bfV"/> <constraint firstItem="189" firstAttribute="leading" secondItem="2" secondAttribute="leading" constant="21" id="YKk-mV-IEg"/> <constraint firstItem="3" firstAttribute="leading" secondItem="222" secondAttribute="leading" id="Yhh-7e-wa4"/> <constraint firstItem="3" firstAttribute="top" secondItem="2" secondAttribute="top" constant="20" id="ZHu-s7-JPA"/> <constraint firstItem="222" firstAttribute="top" secondItem="8" secondAttribute="bottom" constant="8" id="ezx-HF-o5U"/> <constraint firstItem="189" firstAttribute="top" secondItem="6" secondAttribute="bottom" constant="27" id="gwW-ww-fyK"/> <constraint firstItem="12" firstAttribute="top" secondItem="225" secondAttribute="bottom" constant="25" id="hAf-xJ-3rC"/> <constraint firstItem="8" firstAttribute="width" secondItem="225" secondAttribute="width" id="omK-LY-BsE"/> <constraint firstAttribute="trailing" secondItem="12" secondAttribute="trailing" constant="20" id="qG9-AM-Cdp"/> <constraint firstItem="12" firstAttribute="leading" secondItem="14" secondAttribute="trailing" constant="16" id="vEp-Dm-vtL"/> <constraint firstItem="6" firstAttribute="leading" secondItem="2" secondAttribute="leading" constant="8" id="vyY-Ma-CwT"/> <constraint firstItem="8" firstAttribute="leading" secondItem="3" secondAttribute="leading" id="xSE-ra-7uf"/> </constraints> </view> <connections> <outlet property="initialFirstResponder" destination="12" id="91"/> </connections> + <point key="canvasLocation" x="131" y="136"/> </window> <userDefaultsController id="191" userLabel="Shared User Defaults Controller"/> </objects> <resources> <image name="CrashWatcher" width="512" height="512"/> </resources> </document> diff --git a/crashwatcher/MainMenu.xib b/crashwatcher/MainMenu.xib index 702dbe8..a353341 100644 --- a/crashwatcher/MainMenu.xib +++ b/crashwatcher/MainMenu.xib @@ -1,24 +1,25 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14105" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14105"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="NSApplication"> <connections> <outlet property="delegate" destination="494" id="Utr-rv-hwG"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <menu title="AMainMenu" systemMenu="main" id="29"> <items> <menuItem title="TotalFinder Crash Watcher" id="56"> <menu key="submenu" title="TotalFinder Crash Watcher" systemMenu="apple" id="57"/> </menuItem> </items> + <point key="canvasLocation" x="139" y="154"/> </menu> <customObject id="494" customClass="AppDelegate"/> </objects> </document> diff --git a/plugin/ColorfulSidebarPreferences.xib b/plugin/ColorfulSidebarPreferences.xib index cb286cf..cc0bc7d 100644 --- a/plugin/ColorfulSidebarPreferences.xib +++ b/plugin/ColorfulSidebarPreferences.xib @@ -1,44 +1,45 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="ColorfulSidebarPluginPreferencesController"> <connections> <outlet property="$sidebarPreferences" destination="4" id="14"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="4" userLabel="Sidebar Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="7"> <rect key="frame" x="18" y="9" width="201" height="18"/> <buttonCell key="cell" type="check" title="^Show sidebar icons in color" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="8"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderColorfulSidebarEnabled" id="13"/> </connections> </button> </subviews> <constraints> <constraint firstItem="7" firstAttribute="leading" secondItem="4" secondAttribute="leading" constant="20" symbolic="YES" id="5"/> <constraint firstItem="7" firstAttribute="centerY" secondItem="4" secondAttribute="centerY" id="17"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="Sidebar Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="4" id="9"/> <outlet property="owner_" destination="-2" id="11"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/ColumnViewAutoWidthPreferences.xib b/plugin/ColumnViewAutoWidthPreferences.xib index e75ebb1..b89adf0 100644 --- a/plugin/ColumnViewAutoWidthPreferences.xib +++ b/plugin/ColumnViewAutoWidthPreferences.xib @@ -1,173 +1,174 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="ColumnViewAutoWidthPluginPreferencesController"> <connections> <outlet property="$preferences" destination="1" id="164"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="78"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="9"> <rect key="frame" x="18" y="52" width="299" height="18"/> <buttonCell key="cell" type="check" title="^Automatically adjust widths in Column View" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="10"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" id="18"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="110"> - <rect key="frame" x="35" y="30" width="22" height="18"/> + <rect key="frame" x="35" y="31" width="22" height="18"/> <buttonCell key="cell" type="check" bezelStyle="regularSquare" imagePosition="left" inset="2" id="115"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="enabled" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" id="163"/> <binding destination="3" name="value" keyPath="values.TotalFinderColumnViewAutoWidthMaxColumnWidthEnabled" id="117"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="qxp-dT-vMd"> - <rect key="frame" x="35" y="7" width="22" height="18"/> + <rect key="frame" x="35" y="9" width="22" height="18"/> <buttonCell key="cell" type="check" bezelStyle="regularSquare" imagePosition="left" inset="2" id="LeO-Xp-36k"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="enabled" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" id="Pdp-DV-InI"/> <binding destination="3" name="value" keyPath="values.TotalFinderColumnViewAutoWidthMinColumnWidthEnabled" id="LOq-ld-KfH"/> </connections> </button> <textField verticalHuggingPriority="750" misplaced="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="111"> <rect key="frame" x="271" y="28" width="96" height="22"/> <constraints> <constraint firstAttribute="width" constant="96" id="113"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="112"> <numberFormatter key="formatter" formatterBehavior="custom10_4" positiveFormat="#,##0.### px" negativeFormat="#,##0.### px" localizesFormat="NO" numberStyle="decimal" allowsFloats="NO" usesGroupingSeparator="NO" paddingCharacter="*" minimumIntegerDigits="1" maximumIntegerDigits="309" maximumFractionDigits="3" decimalSeparator="." groupingSeparator="," currencyDecimalSeparator="." plusSign="+" minusSign="-" notANumberSymbol="NaN" perMillSymbol="‰" percentSymbol="%" exponentSymbol="E" positivePrefix="" positiveSuffix=" px" negativePrefix="-" negativeSuffix=" px" id="114"> <integer key="minimum" value="100"/> <integer key="maximum" value="10000"/> </numberFormatter> <font key="font" metaFont="system"/> - <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> + <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="3" name="enabled2" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" previousBinding="116" id="159"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> <binding destination="3" name="value" keyPath="values.TotalFinderColumnViewAutoWidthMaxColumnWidth" previousBinding="anE-LM-NSw" id="Dgj-7X-FYU"/> <binding destination="3" name="enabled" keyPath="values.TotalFinderColumnViewAutoWidthMaxColumnWidthEnabled" id="116"/> <binding destination="3" name="minValue" keyPath="values.TotalFinderColumnViewAutoWidthMinColumnWidth" id="anE-LM-NSw"/> </connections> </textField> <textField verticalHuggingPriority="750" misplaced="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="142" customClass="PreferencesTextField"> <rect key="frame" x="56" y="31" width="209" height="17"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Limit maximum column width to" id="143"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="3" name="enabled2" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" previousBinding="157" id="161"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> <binding destination="3" name="enabled" keyPath="values.TotalFinderColumnViewAutoWidthMaxColumnWidthEnabled" id="157"/> </connections> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" misplaced="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="vWv-N1-uYS" customClass="PreferencesTextField"> <rect key="frame" x="56" y="8" width="206" height="17"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Limit minimum column width to" id="by2-Ga-min"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="3" name="enabled" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" id="hjv-eG-w2q"/> <binding destination="3" name="enabled2" keyPath="values.TotalFinderColumnViewAutoWidthMinColumnWidthEnabled" previousBinding="hjv-eG-w2q" id="v2v-ls-z41"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> </connections> </textField> <textField verticalHuggingPriority="750" misplaced="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="bqn-vg-Ryh"> <rect key="frame" x="268" y="5" width="96" height="22"/> <constraints> <constraint firstAttribute="height" constant="22" id="B7y-W9-uMi"/> <constraint firstAttribute="width" constant="96" id="iMS-AS-vRV"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="h6L-vP-Iuw"> <numberFormatter key="formatter" formatterBehavior="custom10_4" positiveFormat="#,##0.### px" negativeFormat="#,##0.### px" localizesFormat="NO" numberStyle="decimal" allowsFloats="NO" usesGroupingSeparator="NO" paddingCharacter="*" minimumIntegerDigits="1" maximumIntegerDigits="309" maximumFractionDigits="3" decimalSeparator="." groupingSeparator="," currencyDecimalSeparator="." plusSign="+" minusSign="-" notANumberSymbol="NaN" perMillSymbol="‰" percentSymbol="%" exponentSymbol="E" positivePrefix="" positiveSuffix=" px" negativePrefix="-" negativeSuffix=" px" id="CJ6-2J-MOt"> <integer key="minimum" value="100"/> <integer key="maximum" value="10000"/> </numberFormatter> <font key="font" metaFont="system"/> - <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> + <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="3" name="enabled" keyPath="values.TotalFinderColumnViewAutoWidthEnabled" id="a7q-Ur-1Rr"/> <binding destination="3" name="maxValue" keyPath="values.TotalFinderColumnViewAutoWidthMaxColumnWidth" id="Bxx-zc-mB4"/> <binding destination="3" name="value" keyPath="values.TotalFinderColumnViewAutoWidthMinColumnWidth" previousBinding="Bxx-zc-mB4" id="oHo-kd-Nnv"/> <binding destination="3" name="enabled2" keyPath="values.TotalFinderColumnViewAutoWidthMinColumnWidthEnabled" previousBinding="a7q-Ur-1Rr" id="Blw-BO-Uyb"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> </connections> </textField> </subviews> <constraints> <constraint firstItem="9" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="15"/> <constraint firstItem="9" firstAttribute="top" secondItem="1" secondAttribute="top" constant="10" id="109"/> <constraint firstItem="110" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="37" id="141"/> <constraint firstItem="142" firstAttribute="centerY" secondItem="111" secondAttribute="centerY" id="165"/> <constraint firstItem="142" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="58" id="168"/> <constraint firstItem="111" firstAttribute="leading" secondItem="142" secondAttribute="trailing" constant="8" symbolic="YES" id="172"/> <constraint firstItem="110" firstAttribute="baseline" secondItem="142" secondAttribute="baseline" id="175"/> <constraint firstItem="111" firstAttribute="top" secondItem="1" secondAttribute="top" constant="28" id="181"/> <constraint firstItem="qxp-dT-vMd" firstAttribute="leading" secondItem="110" secondAttribute="leading" id="CpW-7q-a2X"/> <constraint firstItem="bqn-vg-Ryh" firstAttribute="top" secondItem="111" secondAttribute="bottom" constant="1" id="Fqe-i6-BLH"/> <constraint firstItem="qxp-dT-vMd" firstAttribute="baseline" secondItem="vWv-N1-uYS" secondAttribute="baseline" id="PKi-yf-Ldd"/> <constraint firstItem="bqn-vg-Ryh" firstAttribute="leading" secondItem="vWv-N1-uYS" secondAttribute="trailing" constant="8" id="RVu-nO-1Ni"/> <constraint firstItem="vWv-N1-uYS" firstAttribute="top" secondItem="142" secondAttribute="bottom" constant="6" id="aLj-3i-Obj"/> <constraint firstItem="vWv-N1-uYS" firstAttribute="leading" secondItem="142" secondAttribute="leading" id="aVz-IZ-mz3"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="6"/> <outlet property="owner_" destination="-2" id="5"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/CopyPathMenu.xib b/plugin/CopyPathMenu.xib index 799b807..59c6ab6 100644 --- a/plugin/CopyPathMenu.xib +++ b/plugin/CopyPathMenu.xib @@ -1,62 +1,63 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="AHCopyPathMenuController"> <connections> <outlet property="$copyPathMenu" destination="55" id="93"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <menu title="^Copy Path" id="55" customClass="AHMenuForNode"> <items> <menuItem title="^POSIX Path" id="58" userLabel="Menu Item - ^POSIX Path"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="$cmdCopyPath:" target="-2" id="71"/> </connections> </menuItem> <menuItem title="^URL" tag="1" id="64"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="$cmdCopyPath:" target="-2" id="72"/> </connections> </menuItem> <menuItem title="^Windows Path" tag="2" id="63"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="$cmdCopyPath:" target="-2" id="73"/> </connections> </menuItem> <menuItem title="^UNC Path" tag="3" id="91"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="$cmdCopyPath:" target="-2" id="92"/> </connections> </menuItem> <menuItem title="^HFS Path" tag="4" id="59" userLabel="Menu Item - ^HFS Path"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="$cmdCopyPath:" target="-2" id="74"/> </connections> </menuItem> <menuItem title="^Terminal Path" tag="5" id="65" userLabel="Menu Item - ^Terminal Path"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="$cmdCopyPath:" target="-2" id="75"/> </connections> </menuItem> </items> + <point key="canvasLocation" x="139" y="152"/> </menu> <customObject id="86" userLabel="Localizer And Layout Tweaker" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="55" id="90"/> <outlet property="owner_" destination="-2" id="89"/> </connections> </customObject> </objects> </document> diff --git a/plugin/CopyPathMenuPreferences.xib b/plugin/CopyPathMenuPreferences.xib index 93b9d54..4b9a7af 100644 --- a/plugin/CopyPathMenuPreferences.xib +++ b/plugin/CopyPathMenuPreferences.xib @@ -1,44 +1,45 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="CopyPathMenuPluginPreferencesController"> <connections> <outlet property="$menusPreferences" destination="1" id="15"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Menus Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="4"> <rect key="frame" x="18" y="9" width="278" height="18"/> <buttonCell key="cell" type="check" title="^Allow path copying from Context Menus" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="5"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderCopyPathMenuEnabled" id="6"/> </connections> </button> </subviews> <constraints> <constraint firstItem="4" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="11"/> <constraint firstItem="4" firstAttribute="centerY" secondItem="1" secondAttribute="centerY" id="27"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="Menus Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="14"/> <outlet property="owner_" destination="-2" id="13"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/CutAndPastePreferences.xib b/plugin/CutAndPastePreferences.xib index 3bdbe6b..fe1d451 100644 --- a/plugin/CutAndPastePreferences.xib +++ b/plugin/CutAndPastePreferences.xib @@ -1,44 +1,45 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="CutAndPastePluginPreferencesController"> <connections> <outlet property="$menusPreferences" destination="1" id="18"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Menus Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="7"> <rect key="frame" x="18" y="9" width="289" height="18"/> <buttonCell key="cell" type="check" title="^Show CutPaste buttons in Context Menus" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="8"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderCutAndPasteShowContextMenuButtons" id="9"/> </connections> </button> </subviews> <constraints> <constraint firstItem="7" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="13"/> <constraint firstItem="7" firstAttribute="centerY" secondItem="1" secondAttribute="centerY" id="21"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="Menus Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="17"/> <outlet property="owner_" destination="-2" id="16"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/DockProgressBarPreferences.xib b/plugin/DockProgressBarPreferences.xib index 0527765..abffc9a 100644 --- a/plugin/DockProgressBarPreferences.xib +++ b/plugin/DockProgressBarPreferences.xib @@ -1,44 +1,45 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="DockProgressBarPluginPreferencesController"> <connections> <outlet property="$dockPreferences" destination="2" id="14"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="2" userLabel="Dock Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="5"> <rect key="frame" x="18" y="9" width="221" height="18"/> <buttonCell key="cell" type="check" title="^Show progress bar in the Dock" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="8"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderShowDockProgressBar" id="11"/> </connections> </button> </subviews> <constraints> <constraint firstItem="5" firstAttribute="leading" secondItem="2" secondAttribute="leading" constant="20" symbolic="YES" id="7"/> <constraint firstItem="5" firstAttribute="centerY" secondItem="2" secondAttribute="centerY" id="17"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="3" userLabel="Dock Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="2" id="9"/> <outlet property="owner_" destination="-2" id="12"/> </connections> </customObject> <userDefaultsController id="4" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/FoldersOnTopPreferences.xib b/plugin/FoldersOnTopPreferences.xib index 75c030c..46a3303 100644 --- a/plugin/FoldersOnTopPreferences.xib +++ b/plugin/FoldersOnTopPreferences.xib @@ -1,56 +1,57 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="FoldersOnTopPluginPreferencesController"> <connections> <outlet property="$fileBrowserPreferences" destination="1" id="30"/> </connections> </customObject> <customView id="1" userLabel="FileBrowser Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="8"> <rect key="frame" x="18" y="9" width="122" height="18"/> <buttonCell key="cell" type="check" title="^Folders on Top" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="9"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderFoldersOnTop" id="10"/> </connections> </button> <customView misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="16" customClass="MASShortcutView"> <rect key="frame" x="146" y="9" width="130" height="19"/> <constraints> <constraint firstAttribute="width" constant="130" id="31"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="FoldersOnTop"/> </userDefinedRuntimeAttributes> </customView> </subviews> <constraints> <constraint firstItem="16" firstAttribute="leading" secondItem="8" secondAttribute="trailing" constant="8" symbolic="YES" id="32"/> <constraint firstItem="8" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="33"/> <constraint firstItem="16" firstAttribute="centerY" secondItem="1" secondAttribute="centerY" id="66"/> <constraint firstItem="8" firstAttribute="centerY" secondItem="16" secondAttribute="centerY" id="74"/> <constraint firstItem="16" firstAttribute="top" secondItem="1" secondAttribute="top" constant="8" id="79"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customObject id="2" userLabel="FileBrowser Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="27"/> <outlet property="owner_" destination="-2" id="26"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/LabelsPreferences.xib b/plugin/LabelsPreferences.xib index 6d0e9e2..e9291c8 100644 --- a/plugin/LabelsPreferences.xib +++ b/plugin/LabelsPreferences.xib @@ -1,55 +1,56 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="LabelsPluginPreferencesController"> <connections> <outlet property="$labelsPreferences" destination="4" id="5Ya-xy-yHm"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="4" userLabel="FileBrowser Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="50"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="7"> <rect key="frame" x="18" y="24" width="119" height="18"/> <buttonCell key="cell" type="check" title="^Colored Labels" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="8"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="3" name="value" keyPath="values.TotalFinderLabelsEnabled" id="Ogk-Hw-hSN"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="mM7-kD-T4k"> <rect key="frame" x="35" y="8" width="259" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^The last applied tag determines item's background color." id="ms8-ix-10M"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="7" firstAttribute="leading" secondItem="4" secondAttribute="leading" constant="20" symbolic="YES" id="5"/> <constraint firstItem="7" firstAttribute="centerY" secondItem="4" secondAttribute="centerY" constant="-8" id="24"/> <constraint firstItem="mM7-kD-T4k" firstAttribute="top" secondItem="7" secondAttribute="bottom" constant="7" id="Rnx-kB-hlB"/> <constraint firstItem="mM7-kD-T4k" firstAttribute="leading" secondItem="4" secondAttribute="leading" constant="37" id="bpt-gz-6te"/> <constraint firstItem="7" firstAttribute="top" secondItem="4" secondAttribute="top" constant="10" id="fCP-Lj-hfS"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="FileBrowser Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="4" id="9"/> <outlet property="owner_" destination="-2" id="11"/> </connections> </customObject> <userDefaultsController id="3" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/Licensing.xib b/plugin/Licensing.xib index 4221564..f2581f7 100644 --- a/plugin/Licensing.xib +++ b/plugin/Licensing.xib @@ -1,362 +1,363 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> - <plugIn identifier="com.apple.WebKitIBPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> + <plugIn identifier="com.apple.WebKitIBPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="XMLicensingWindowController"> <connections> <outlet property="$currentView" destination="5" id="87"/> <outlet property="$licenseKey" destination="22" id="Zmd-9G-7hA"/> <outlet property="$licenseName" destination="20" id="X6N-3o-BmH"/> <outlet property="$licensingInfo" destination="115" id="118"/> <outlet property="$viewA" destination="5" id="107"/> <outlet property="$viewB" destination="24" id="105"/> <outlet property="$viewC" destination="54" id="106"/> <outlet property="window" destination="1" id="44"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customObject id="120" userLabel="Localizer -&gt; Window" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="wqR-T4-xos"/> <outlet property="owner_" destination="-2" id="pA3-Cu-pmQ"/> </connections> </customObject> <customObject id="127" userLabel="Localizer -&gt; RegistrationA" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="5" id="07e-6r-2Je"/> <outlet property="owner_" destination="-2" id="3Gn-E2-FUa"/> </connections> </customObject> <customObject id="130" userLabel="Localizer -&gt; RegistrationB" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="24" id="g7L-Qr-5XU"/> <outlet property="owner_" destination="-2" id="BIt-ac-LuS"/> </connections> </customObject> <customObject id="133" userLabel="Localizer -&gt; RegistrationC" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="54" id="lmA-1y-DCZ"/> <outlet property="owner_" destination="-2" id="YJ7-YF-9wV"/> </connections> </customObject> <userDefaultsController id="45" customClass="TotalUserDefaultsController"/> - <window title="^TotalFinder Registration" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" oneShot="NO" animationBehavior="default" id="1"> + <window title="^TotalFinder Registration" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" animationBehavior="default" id="1"> <windowStyleMask key="styleMask" titled="YES" closable="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="525" y="500" width="480" height="300"/> <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1417"/> <view key="contentView" id="2"> <rect key="frame" x="0.0" y="0.0" width="480" height="300"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <userGuides> <userLayoutGuide location="150" affinity="minX"/> <userLayoutGuide location="247" affinity="minY"/> </userGuides> <subviews> <imageView fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="97"> <rect key="frame" x="4" y="75" width="140" height="298"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" animates="YES" imageScaling="proportionallyDown" image="LicensingDialogIcon" id="98"/> </imageView> </subviews> </view> + <point key="canvasLocation" x="139" y="147"/> </window> <customView id="5" userLabel="RegistrationA" customClass="MSZLinkedView"> <rect key="frame" x="0.0" y="0.0" width="482" height="301"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="6"> <rect key="frame" x="374" y="13" width="96" height="32"/> <constraints> <constraint firstAttribute="width" constant="84" id="sXX-Sk-rgU"/> </constraints> <buttonCell key="cell" type="push" title="^Register" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="19"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$registerApp:" target="-2" id="67"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="158"> - <rect key="frame" x="202" y="13" width="172" height="32"/> + <rect key="frame" x="203" y="13" width="171" height="32"/> <buttonCell key="cell" type="push" title="^Buy TotalFinder Now" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="159"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$visitStore:" target="-2" id="160"/> </connections> </button> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="22"> <rect key="frame" x="170" y="61" width="294" height="98"/> <constraints> <constraint firstAttribute="width" constant="294" id="Wpu-8f-3Ro"/> <constraint firstAttribute="height" constant="98" id="h6r-OO-9HS"/> </constraints> <textFieldCell key="cell" controlSize="small" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" placeholderString="^License Key" drawsBackground="YES" id="23"> - <font key="font" metaFont="smallSystem"/> - <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> + <font key="font" metaFont="message" size="11"/> + <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="45" name="value" keyPath="values.TotalFinderLicenseKey" id="113"> <dictionary key="options"> <string key="NSNullPlaceholder">License Key</string> </dictionary> </binding> <outlet property="nextKeyView" destination="20" id="109"/> </connections> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="20"> <rect key="frame" x="170" y="172" width="294" height="19"/> <constraints> <constraint firstAttribute="width" constant="294" id="35y-SE-4dm"/> </constraints> <textFieldCell key="cell" controlSize="small" lineBreakMode="truncatingTail" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" placeholderString="^License Name" drawsBackground="YES" usesSingleLineMode="YES" id="21"> - <font key="font" metaFont="smallSystem"/> - <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> + <font key="font" metaFont="message" size="11"/> + <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="45" name="value" keyPath="values.TotalFinderLicenseName" id="112"> <dictionary key="options"> <string key="NSNullPlaceholder">License Name</string> </dictionary> </binding> <outlet property="nextKeyView" destination="22" id="108"/> </connections> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="8"> - <rect key="frame" x="168" y="218" width="296" height="34"/> + <rect key="frame" x="168" y="221" width="296" height="32"/> <constraints> <constraint firstAttribute="width" constant="292" id="ncC-34-f0l"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Please enter your license details from the email we have sent you:" id="17"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="7"> - <rect key="frame" x="154" y="260" width="113" height="21"/> + <rect key="frame" x="154" y="261" width="112" height="20"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Registration" id="18"> <font key="font" metaFont="systemBold" size="17"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="20" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="170" id="2Vq-Yk-et4"/> <constraint firstItem="6" firstAttribute="trailing" secondItem="22" secondAttribute="trailing" id="2ZB-6I-fQE"/> <constraint firstItem="8" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="170" id="5uc-9c-Zkz"/> <constraint firstItem="22" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="170" id="VKa-Rv-5IX"/> <constraint firstItem="6" firstAttribute="leading" secondItem="158" secondAttribute="trailing" constant="12" symbolic="YES" id="Ykb-iT-qIr"/> <constraint firstItem="20" firstAttribute="top" secondItem="5" secondAttribute="top" constant="110" id="a9F-7W-XME"/> <constraint firstItem="8" firstAttribute="top" secondItem="7" secondAttribute="bottom" constant="8" id="ask-F6-yc6"/> <constraint firstItem="7" firstAttribute="top" secondItem="5" secondAttribute="top" constant="20" id="hu4-Ul-vI7"/> <constraint firstAttribute="bottom" secondItem="158" secondAttribute="bottom" constant="20" id="kCP-tj-YL8"/> <constraint firstItem="7" firstAttribute="leading" secondItem="5" secondAttribute="leading" constant="156" id="to7-RV-17q"/> <constraint firstItem="6" firstAttribute="baseline" secondItem="158" secondAttribute="baseline" id="zdI-O0-mQ5"/> <constraint firstItem="22" firstAttribute="top" secondItem="20" secondAttribute="bottom" constant="13" id="zzm-1V-gER"/> </constraints> <connections> <outlet property="$nextView" destination="54" id="90"/> </connections> </customView> <customView id="24" userLabel="RegistrationB" customClass="MSZLinkedView"> <rect key="frame" x="0.0" y="0.0" width="482" height="301"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="26"> - <rect key="frame" x="168" y="210" width="36" height="17"/> + <rect key="frame" x="168" y="213" width="36" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" sendsActionOnEndEditing="YES" state="on" placeholderString="Name" id="37"> <font key="font" size="13" name="Monaco"/> <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" red="0.99989891050000002" green="1" blue="0.094879518070000002" alpha="1" colorSpace="calibratedRGB"/> </textFieldCell> <connections> <binding destination="45" name="value" keyPath="values.TotalFinderLicenseName" id="114"/> </connections> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="29"> - <rect key="frame" x="168" y="235" width="296" height="17"/> + <rect key="frame" x="168" y="237" width="296" height="16"/> <constraints> <constraint firstAttribute="width" constant="292" id="7Yx-2Q-2Gm"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^This TotalFinder copy is licensed to:" id="34"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="196" translatesAutoresizingMaskIntoConstraints="NO" id="30"> - <rect key="frame" x="154" y="260" width="200" height="21"/> + <rect key="frame" x="154" y="261" width="199" height="20"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Thanks for registering!" id="33"> <font key="font" metaFont="systemBold" size="17"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <webView maintainsBackForwardList="NO" translatesAutoresizingMaskIntoConstraints="NO" id="115"> <rect key="frame" x="20" y="50" width="442" height="117"/> <constraints> <constraint firstAttribute="height" constant="117" id="Sdb-qV-889"/> <constraint firstAttribute="width" constant="442" id="WaM-Bx-saG"/> </constraints> <webPreferences key="preferences" defaultFontSize="12" defaultFixedFontSize="12"> <nil key="identifier"/> </webPreferences> <connections> <outlet property="policyDelegate" destination="-2" id="119"/> </connections> </webView> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="27"> - <rect key="frame" x="228" y="13" width="144" height="32"/> + <rect key="frame" x="229" y="13" width="143" height="32"/> <buttonCell key="cell" type="push" title="^Change License" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="36"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent"></string> </buttonCell> <connections> <action selector="$previousView:" target="-2" id="52"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="31"> <rect key="frame" x="372" y="13" width="96" height="32"/> <constraints> <constraint firstAttribute="width" constant="84" id="PsE-ld-efg"/> </constraints> <buttonCell key="cell" type="push" title="^Close" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="32"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$close:" target="-2" id="93"/> </connections> </button> </subviews> <constraints> <constraint firstItem="31" firstAttribute="trailing" secondItem="115" secondAttribute="trailing" id="2Xb-NN-xyd"/> <constraint firstItem="29" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="170" id="9X5-RU-fob"/> <constraint firstItem="30" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="156" id="M7T-sa-Rbt"/> <constraint firstItem="26" firstAttribute="top" secondItem="29" secondAttribute="bottom" constant="8" id="S4e-bh-zej"/> <constraint firstItem="26" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="170" id="Yl3-jd-O7T"/> <constraint firstAttribute="bottom" secondItem="115" secondAttribute="bottom" constant="50" id="a5d-Iy-SDq"/> <constraint firstItem="30" firstAttribute="top" secondItem="24" secondAttribute="top" constant="20" id="bnr-N9-qgb"/> <constraint firstItem="31" firstAttribute="baseline" secondItem="27" secondAttribute="baseline" id="dnL-zQ-mAP"/> <constraint firstItem="31" firstAttribute="leading" secondItem="27" secondAttribute="trailing" constant="12" symbolic="YES" id="fmX-jq-gTh"/> <constraint firstItem="29" firstAttribute="top" secondItem="30" secondAttribute="bottom" constant="8" id="kiI-XE-3Ra"/> <constraint firstAttribute="bottom" secondItem="27" secondAttribute="bottom" constant="20" symbolic="YES" id="lMT-Ou-PIX"/> <constraint firstAttribute="centerX" secondItem="115" secondAttribute="centerX" id="oam-wT-RTR"/> </constraints> <connections> <outlet property="$previousView" destination="5" id="92"/> </connections> </customView> <customView id="54" userLabel="RegistrationC" customClass="MSZLinkedView"> <rect key="frame" x="0.0" y="0.0" width="482" height="301"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="74"> - <rect key="frame" x="168" y="121" width="296" height="34"/> + <rect key="frame" x="168" y="125" width="296" height="32"/> <constraints> <constraint firstAttribute="width" constant="292" id="Nme-bC-UQM"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^To purchase a license for TotalFinder, please visit BinaryAge web store." id="75"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="292" translatesAutoresizingMaskIntoConstraints="NO" id="56"> - <rect key="frame" x="168" y="235" width="296" height="17"/> + <rect key="frame" x="168" y="237" width="296" height="16"/> <constraints> <constraint firstAttribute="width" constant="292" id="NLN-e9-1KJ"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Please go back and try again." id="63"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="58"> - <rect key="frame" x="154" y="260" width="173" height="21"/> + <rect key="frame" x="154" y="261" width="172" height="20"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Invalid license code" id="61"> <font key="font" metaFont="systemBold" size="17"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="72"> - <rect key="frame" x="200" y="13" width="172" height="32"/> + <rect key="frame" x="201" y="13" width="171" height="32"/> <buttonCell key="cell" type="push" title="^Buy TotalFinder Now" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="73"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$visitStore:" target="-2" id="117"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="57"> <rect key="frame" x="372" y="13" width="96" height="32"/> <constraints> <constraint firstAttribute="width" constant="84" id="ydo-0n-EEI"/> </constraints> <buttonCell key="cell" type="push" title="^Back" bezelStyle="rounded" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="62"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> <string key="keyEquivalent" base64-UTF8="YES"> CQ </string> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </buttonCell> <connections> <action selector="$previousView:" target="-2" id="83"/> </connections> </button> </subviews> <constraints> <constraint firstItem="56" firstAttribute="top" secondItem="58" secondAttribute="bottom" constant="8" id="03G-Ol-XXa"/> <constraint firstItem="72" firstAttribute="baseline" secondItem="57" secondAttribute="baseline" id="41I-MV-t68"/> <constraint firstItem="58" firstAttribute="top" secondItem="54" secondAttribute="top" constant="20" id="FCW-1I-RUz"/> <constraint firstItem="57" firstAttribute="leading" secondItem="72" secondAttribute="trailing" constant="12" symbolic="YES" id="GyW-kP-C9Z"/> <constraint firstItem="58" firstAttribute="leading" secondItem="54" secondAttribute="leading" constant="156" id="LwA-nz-YkU"/> <constraint firstItem="56" firstAttribute="leading" secondItem="54" secondAttribute="leading" constant="170" id="QkL-qk-15h"/> <constraint firstItem="74" firstAttribute="top" secondItem="56" secondAttribute="bottom" constant="80" id="XJ3-I8-IZN"/> <constraint firstAttribute="trailing" secondItem="57" secondAttribute="trailing" constant="20" symbolic="YES" id="eMY-4J-C4J"/> <constraint firstItem="74" firstAttribute="leading" secondItem="54" secondAttribute="leading" constant="170" id="fRu-SJ-Pjt"/> <constraint firstAttribute="bottom" secondItem="72" secondAttribute="bottom" constant="20" symbolic="YES" id="zkX-d8-3q1"/> </constraints> <connections> <outlet property="$previousView" destination="5" id="95"/> </connections> </customView> </objects> <resources> <image name="LicensingDialogIcon" width="512" height="512"/> </resources> </document> diff --git a/plugin/Preferences.xib b/plugin/Preferences.xib index 497d6e2..354f775 100644 --- a/plugin/Preferences.xib +++ b/plugin/Preferences.xib @@ -1,215 +1,216 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14295.6" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14295.6"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="PreferencesController"> <connections> <outlet property="$featuresOutline" destination="3" id="382"/> <outlet property="$headerHelpButton" destination="83" id="383"/> <outlet property="$headerIcon" destination="55" id="384"/> <outlet property="$headerTitle" destination="72" id="385"/> <outlet property="$presentationView" destination="106" id="386"/> <outlet property="$rootView" destination="1" id="387"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="PreferencesPane"> <rect key="frame" x="0.0" y="0.0" width="660" height="510"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <customView translatesAutoresizingMaskIntoConstraints="NO" id="106" userLabel="Presentation" customClass="PreferencesPresentationView"> <rect key="frame" x="180" y="8" width="480" height="444"/> </customView> <box autoresizesSubviews="NO" boxType="custom" borderType="line" borderWidth="0.0" title="Box" titlePosition="noTitle" translatesAutoresizingMaskIntoConstraints="NO" id="24" userLabel="Header"> <rect key="frame" x="180" y="460" width="480" height="50"/> <view key="contentView" id="1LM-jw-DUG"> <rect key="frame" x="0.0" y="0.0" width="480" height="50"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView translatesAutoresizingMaskIntoConstraints="NO" id="55" userLabel="Icon"> <rect key="frame" x="7" y="8" width="36" height="36"/> <constraints> <constraint firstAttribute="width" constant="36" id="67"/> <constraint firstAttribute="height" constant="36" id="69"/> </constraints> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyUpOrDown" id="56"/> <connections> <binding destination="-2" name="value" keyPath="$selectedFeature.$icon" id="276"/> </connections> </imageView> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="72" userLabel="Title"> - <rect key="frame" x="49" y="11" width="378" height="29"/> + <rect key="frame" x="49" y="11" width="378" height="28"/> <constraints> <constraint firstAttribute="width" constant="374" id="241"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" state="on" title="Section Title" id="73"> <font key="font" metaFont="system" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="-2" name="value" keyPath="$selectedFeature.$title" id="272"/> </connections> </textField> <button horizontalHuggingPriority="750" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="83" userLabel="Help"> <rect key="frame" x="441" y="9" width="25" height="25"/> <buttonCell key="cell" type="help" bezelStyle="helpButton" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="84"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <action selector="$openHelp:" target="-2" id="278"/> </connections> </button> </subviews> </view> <constraints> <constraint firstAttribute="trailing" secondItem="83" secondAttribute="trailing" constant="16" id="AQ1-Xl-aJM"/> <constraint firstItem="83" firstAttribute="top" secondItem="24" secondAttribute="top" constant="16" id="F5v-Rq-5ND"/> <constraint firstItem="55" firstAttribute="leading" secondItem="24" secondAttribute="leading" constant="7" id="TuP-Np-gys"/> <constraint firstItem="72" firstAttribute="leading" secondItem="55" secondAttribute="trailing" constant="8" symbolic="YES" id="bq8-dc-V36"/> <constraint firstItem="72" firstAttribute="centerY" secondItem="24" secondAttribute="centerY" id="sLU-Om-7MQ"/> <constraint firstItem="55" firstAttribute="top" secondItem="24" secondAttribute="top" constant="6" id="ypH-GK-8i9"/> </constraints> </box> <scrollView horizontalLineScroll="22" horizontalPageScroll="10" verticalLineScroll="22" verticalPageScroll="10" hasHorizontalScroller="NO" hasVerticalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="2" userLabel="Features"> <rect key="frame" x="-2" y="-1" width="183" height="512"/> <clipView key="contentView" drawsBackground="NO" copiesOnScroll="NO" id="JoM-V7-h65"> <rect key="frame" x="1" y="1" width="181" height="510"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <outlineView verticalHuggingPriority="750" allowsExpansionToolTips="YES" columnAutoresizingStyle="lastColumnOnly" selectionHighlightStyle="sourceList" columnReordering="NO" columnResizing="NO" multipleSelection="NO" emptySelection="NO" autosaveColumns="NO" rowHeight="22" rowSizeStyle="small" viewBased="YES" indentationPerLevel="14" outlineTableColumn="7" id="3" userLabel="Outline"> <rect key="frame" x="0.0" y="0.0" width="181" height="510"/> - <autoresizingMask key="autoresizingMask"/> + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" name="_sourceListBackgroundColor" catalog="System" colorSpace="catalog"/> <color key="gridColor" name="gridColor" catalog="System" colorSpace="catalog"/> <tableColumns> <tableColumn identifier="features" editable="NO" width="178" minWidth="16" maxWidth="1000" id="7"> <tableHeaderCell key="headerCell" lineBreakMode="truncatingTail" borderStyle="border" alignment="left"> - <font key="font" metaFont="smallSystem"/> + <font key="font" metaFont="message" size="11"/> <color key="textColor" name="headerTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" white="0.33333298560000002" alpha="1" colorSpace="calibratedWhite"/> </tableHeaderCell> <textFieldCell key="dataCell" lineBreakMode="truncatingTail" selectable="YES" editable="YES" alignment="left" title="Text Cell" id="10"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <prototypeCellViews> <tableCellView identifier="category" id="170" userLabel="CategoryView"> <rect key="frame" x="0.0" y="0.0" width="178" height="20"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="171"> <rect key="frame" x="1" y="0.0" width="176" height="20"/> <constraints> <constraint firstAttribute="height" constant="20" id="293"/> </constraints> <textFieldCell key="cell" lineBreakMode="truncatingTail" sendsActionOnEndEditing="YES" title="Table View Cell" id="172"> <font key="font" metaFont="system"/> <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="170" name="value" keyPath="objectValue.$title" id="259"/> </connections> </textField> </subviews> <constraints> <constraint firstAttribute="trailing" secondItem="171" secondAttribute="trailing" constant="3" id="175"/> <constraint firstItem="171" firstAttribute="leading" secondItem="170" secondAttribute="leading" constant="3" id="176"/> <constraint firstItem="171" firstAttribute="top" secondItem="170" secondAttribute="top" id="296"/> </constraints> <connections> <outlet property="textField" destination="171" id="173"/> </connections> </tableCellView> <tableCellView identifier="item" id="177" userLabel="ItemView"> <rect key="frame" x="0.0" y="20" width="178" height="20"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView translatesAutoresizingMaskIntoConstraints="NO" id="178"> <rect key="frame" x="3" y="0.0" width="20" height="20"/> <constraints> <constraint firstAttribute="width" constant="20" id="2au-J9-Wpc"/> <constraint firstAttribute="height" constant="20" id="a1D-ng-UxX"/> </constraints> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="NSActionTemplate" id="181"/> <connections> <binding destination="177" name="value" keyPath="objectValue.$icon" id="257"/> </connections> </imageView> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="179"> - <rect key="frame" x="26" y="2" width="151" height="17"/> + <rect key="frame" x="26" y="2" width="151" height="16"/> <constraints> <constraint firstAttribute="width" constant="147" id="332"/> </constraints> <textFieldCell key="cell" lineBreakMode="truncatingTail" sendsActionOnEndEditing="YES" title="Table View Cell" usesSingleLineMode="YES" id="180"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="177" name="value" keyPath="objectValue.$title" id="255"/> </connections> </textField> </subviews> <constraints> <constraint firstItem="178" firstAttribute="leading" secondItem="177" secondAttribute="leading" constant="3" id="0L8-FV-mKl"/> <constraint firstItem="179" firstAttribute="leading" secondItem="178" secondAttribute="trailing" constant="5" id="nTa-YT-j8T"/> <constraint firstItem="179" firstAttribute="centerY" secondItem="177" secondAttribute="centerY" id="tJc-j2-y7r"/> <constraint firstItem="178" firstAttribute="centerY" secondItem="177" secondAttribute="centerY" id="u7h-hO-98H"/> </constraints> <connections> <outlet property="imageView" destination="178" id="182"/> <outlet property="textField" destination="179" id="183"/> </connections> </tableCellView> </prototypeCellViews> </tableColumn> </tableColumns> <connections> <outlet property="dataSource" destination="120" id="121"/> <outlet property="delegate" destination="-2" id="204"/> </connections> </outlineView> </subviews> <nil key="backgroundColor"/> </clipView> <scroller key="horizontalScroller" hidden="YES" verticalHuggingPriority="750" horizontal="YES" id="4"> <rect key="frame" x="-100" y="-100" width="180" height="15"/> <autoresizingMask key="autoresizingMask"/> </scroller> <scroller key="verticalScroller" hidden="YES" verticalHuggingPriority="750" horizontal="NO" id="6"> <rect key="frame" x="-100" y="-100" width="15" height="102"/> <autoresizingMask key="autoresizingMask"/> </scroller> </scrollView> </subviews> <constraints> <constraint firstAttribute="bottom" secondItem="24" secondAttribute="bottom" constant="460" id="98"/> <constraint firstItem="24" firstAttribute="top" secondItem="1" secondAttribute="top" id="99"/> <constraint firstItem="24" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="180" id="101"/> <constraint firstItem="24" firstAttribute="trailing" secondItem="1" secondAttribute="trailing" id="252"/> <constraint firstItem="2" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="-2" id="366"/> <constraint firstAttribute="trailing" secondItem="2" secondAttribute="trailing" constant="479" id="367"/> <constraint firstItem="2" firstAttribute="centerY" secondItem="1" secondAttribute="centerY" id="381"/> <constraint firstItem="2" firstAttribute="top" secondItem="1" secondAttribute="top" constant="-1" id="391"/> <constraint firstItem="106" firstAttribute="trailing" secondItem="1" secondAttribute="trailing" id="422"/> <constraint firstItem="106" firstAttribute="leading" secondItem="24" secondAttribute="leading" id="423"/> <constraint firstAttribute="bottom" secondItem="106" secondAttribute="bottom" constant="8" id="439"/> <constraint firstItem="106" firstAttribute="top" secondItem="1" secondAttribute="top" constant="58" id="447"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="120" customClass="PreferencesFeaturesDataSource"/> <userDefaultsController id="262" customClass="TotalUserDefaultsController"/> </objects> <resources> <image name="NSActionTemplate" width="14" height="14"/> </resources> </document> diff --git a/plugin/ShellPreferences.xib b/plugin/ShellPreferences.xib index dcb8284..97aa7cf 100644 --- a/plugin/ShellPreferences.xib +++ b/plugin/ShellPreferences.xib @@ -1,319 +1,320 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14269.12" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14269.12"/> - <plugIn identifier="com.apple.WebKitIBPlugin" version="14269.12"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> + <plugIn identifier="com.apple.WebKitIBPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="TFShellPreferencesController"> <connections> <outlet property="$aboutContent" destination="133" id="228"/> <outlet property="$aboutPreferences" destination="1" id="229"/> <outlet property="$dockPreferences" destination="333" id="365"/> <outlet property="$menusPreferences" destination="316" id="366"/> <outlet property="$registerButton" destination="96" id="233"/> <outlet property="$registeredTo" destination="95" id="232"/> <outlet property="$registrationPreferences" destination="7" id="230"/> <outlet property="$tabsPreferences" destination="8uq-4v-kht" id="iLo-k4-P2D"/> <outlet property="$titleInAbout" destination="293" id="303"/> <outlet property="$titleInRegistration" destination="97" id="304"/> <outlet property="$titleInUpdates" destination="258" id="305"/> <outlet property="$updatesPreferences" destination="87" id="231"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="7" userLabel="Registration Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="101"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="440" translatesAutoresizingMaskIntoConstraints="NO" id="97"> - <rect key="frame" x="18" y="52" width="444" height="29"/> + <rect key="frame" x="18" y="53" width="444" height="28"/> <constraints> <constraint firstAttribute="width" constant="440" id="hTq-0b-4ws"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="98"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="96"> - <rect key="frame" x="20" y="0.0" width="61" height="19"/> + <rect key="frame" x="20" y="2" width="61" height="19"/> <buttonCell key="cell" type="roundRect" title="Register" bezelStyle="roundedRect" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="99"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="cellTitle"/> </buttonCell> <connections> <action selector="$showLicensingWindow:" target="-2" id="306"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="95"> - <rect key="frame" x="18" y="27" width="146" height="17"/> + <rect key="frame" x="18" y="29" width="146" height="16"/> <textFieldCell key="cell" lineBreakMode="truncatingTail" sendsActionOnEndEditing="YES" title="Registered to John Doe" usesSingleLineMode="YES" id="100"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="97" firstAttribute="top" secondItem="7" secondAttribute="top" constant="20" symbolic="YES" id="120"/> <constraint firstItem="97" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="121"/> <constraint firstItem="95" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="128"/> <constraint firstItem="96" firstAttribute="leading" secondItem="7" secondAttribute="leading" constant="20" symbolic="YES" id="130"/> <constraint firstItem="95" firstAttribute="top" secondItem="97" secondAttribute="bottom" constant="8" symbolic="YES" id="246"/> <constraint firstItem="96" firstAttribute="top" secondItem="95" secondAttribute="bottom" constant="8" symbolic="YES" id="247"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="215" userLabel="Registration Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="7" id="217"/> <outlet property="owner_" destination="-2" id="216"/> </connections> </customObject> <customView id="87" userLabel="Updates Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="140"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="152"> <rect key="frame" x="38" y="42" width="203" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Automatically check the website for updates" id="162"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="154"> <rect key="frame" x="38" y="5" width="152" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Participate in TotalFinder testing" id="161"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button translatesAutoresizingMaskIntoConstraints="NO" id="155" userLabel="Check Box"> <rect key="frame" x="18" y="18" width="152" height="18"/> <buttonCell key="cell" type="check" title="^Include pre-releases" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="160"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderUsePreReleases" id="211"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="156"> <rect key="frame" x="18" y="55" width="142" height="18"/> <buttonCell key="cell" type="check" title="^Check for Updates" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="159"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderCheckForUpdates" id="Mgr-b0-keU"/> </connections> </button> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="157"> <rect key="frame" x="165" y="56" width="78" height="16"/> <buttonCell key="cell" type="push" title="^Check Now" bezelStyle="rounded" alignment="center" controlSize="mini" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="158"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="miniSystem"/> </buttonCell> <connections> <action selector="$checkForUpdates:" target="-2" id="235"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="258"> - <rect key="frame" x="18" y="91" width="194" height="29"/> + <rect key="frame" x="18" y="92" width="194" height="28"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="259"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="156" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="196"/> <constraint firstItem="157" firstAttribute="leading" secondItem="156" secondAttribute="trailing" constant="8" symbolic="YES" id="197"/> <constraint firstItem="155" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="204"/> <constraint firstItem="154" firstAttribute="leading" secondItem="152" secondAttribute="leading" id="205"/> <constraint firstItem="155" firstAttribute="top" secondItem="152" secondAttribute="bottom" constant="8" symbolic="YES" id="248"/> <constraint firstItem="258" firstAttribute="top" secondItem="87" secondAttribute="top" constant="20" symbolic="YES" id="262"/> <constraint firstItem="157" firstAttribute="bottom" secondItem="156" secondAttribute="bottom" id="267"/> <constraint firstItem="258" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="20" symbolic="YES" id="268"/> <constraint firstItem="157" firstAttribute="top" secondItem="87" secondAttribute="top" constant="68" id="269"/> <constraint firstItem="154" firstAttribute="leading" secondItem="87" secondAttribute="leading" constant="40" id="277"/> <constraint firstAttribute="bottom" secondItem="155" secondAttribute="bottom" constant="20" symbolic="YES" id="278"/> <constraint firstAttribute="bottom" secondItem="154" secondAttribute="bottom" constant="5" id="283"/> <constraint firstItem="154" firstAttribute="top" secondItem="155" secondAttribute="bottom" constant="4" id="284"/> <constraint firstItem="152" firstAttribute="top" secondItem="156" secondAttribute="bottom" constant="4" id="285"/> </constraints> </customView> <customObject id="218" userLabel="Updates Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="87" id="224"/> <outlet property="owner_" destination="-2" id="219"/> </connections> </customObject> <customView id="1" userLabel="About Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="227"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <webView translatesAutoresizingMaskIntoConstraints="NO" id="133"> - <rect key="frame" x="20" y="26" width="440" height="119"/> + <rect key="frame" x="20" y="28" width="440" height="119"/> <constraints> <constraint firstAttribute="height" constant="119" id="307"/> </constraints> <webPreferences key="preferences" defaultFontSize="12" defaultFixedFontSize="12"> <nil key="identifier"/> </webPreferences> <connections> <outlet property="policyDelegate" destination="-2" id="236"/> </connections> </webView> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="440" translatesAutoresizingMaskIntoConstraints="NO" id="134"> - <rect key="frame" x="18" y="153" width="444" height="17"/> + <rect key="frame" x="18" y="155" width="444" height="16"/> <textFieldCell key="cell" sendsActionOnEndEditing="YES" title="^Thank you for using TotalFinder!" usesSingleLineMode="YES" id="135"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="293"> - <rect key="frame" x="18" y="178" width="444" height="29"/> + <rect key="frame" x="18" y="179" width="444" height="28"/> <constraints> <constraint firstAttribute="width" constant="440" id="25p-5M-1IT"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="TotalFinder X.Y.Z" usesSingleLineMode="YES" id="294"> <font key="font" metaFont="systemBold" size="24"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="308"> <rect key="frame" x="20" y="-1" width="182" height="19"/> <buttonCell key="cell" type="roundRect" title="^Reset TotalFinder to defaults" bezelStyle="roundedRect" alignment="center" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="309"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="cellTitle"/> </buttonCell> <connections> <action selector="$resetToDefaults:" target="-2" id="315"/> </connections> </button> </subviews> <constraints> <constraint firstItem="133" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="148"/> <constraint firstAttribute="trailing" secondItem="133" secondAttribute="trailing" constant="20" symbolic="YES" id="150"/> <constraint firstItem="293" firstAttribute="top" secondItem="1" secondAttribute="top" constant="20" symbolic="YES" id="297"/> <constraint firstItem="293" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="298"/> <constraint firstItem="308" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="312"/> <constraint firstItem="308" firstAttribute="bottom" secondItem="1" secondAttribute="bottom" id="314"/> <constraint firstItem="134" firstAttribute="leading" secondItem="293" secondAttribute="leading" id="Cxh-45-C83"/> <constraint firstItem="134" firstAttribute="top" secondItem="293" secondAttribute="bottom" constant="8" symbolic="YES" id="Omi-6z-SoP"/> <constraint firstItem="134" firstAttribute="trailing" secondItem="133" secondAttribute="trailing" id="iWI-4i-aCd"/> <constraint firstItem="133" firstAttribute="top" secondItem="134" secondAttribute="bottom" constant="8" symbolic="YES" id="lyt-Gf-2Gt"/> </constraints> </customView> <customObject id="221" userLabel="About Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="225"/> <outlet property="owner_" destination="-2" id="222"/> </connections> </customObject> <customView id="333" userLabel="Dock Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="34"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="348"> <rect key="frame" x="18" y="8" width="171" height="18"/> <buttonCell key="cell" type="check" title="^Keep original Dock icon" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="349"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderDontCustomizeDockIcon" id="369"/> </connections> </button> </subviews> <constraints> <constraint firstItem="348" firstAttribute="leading" secondItem="333" secondAttribute="leading" constant="20" symbolic="YES" id="356"/> <constraint firstItem="348" firstAttribute="centerY" secondItem="333" secondAttribute="centerY" id="370"/> </constraints> </customView> <customView id="8uq-4v-kht" userLabel="Tabs Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="64"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="J6d-M3-FOb"> <rect key="frame" x="18" y="37" width="173" height="18"/> <buttonCell key="cell" type="check" title="^Disable tabs completely" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="eeg-k4-55d"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <action selector="$disableTabsCompletely:" target="-2" id="OeT-jd-1nq"/> <binding destination="94" name="value" keyPath="values.TotalFinderTabsDisabled" id="xA9-mr-Dgn"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="wo8-mU-gzk"> <rect key="frame" x="39" y="20" width="357" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^This will effectively disable tabs, dual mode and visor. Finder restart is needed." id="2MQ-dx-5TV"> <font key="font" metaFont="miniSystem"/> <color key="textColor" name="disabledControlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="J6d-M3-FOb" firstAttribute="leading" secondItem="8uq-4v-kht" secondAttribute="leading" constant="20" symbolic="YES" id="J6s-HG-TwS"/> <constraint firstItem="J6d-M3-FOb" firstAttribute="top" secondItem="8uq-4v-kht" secondAttribute="top" constant="11" id="LbD-yg-Erj"/> <constraint firstItem="wo8-mU-gzk" firstAttribute="leading" secondItem="J6d-M3-FOb" secondAttribute="leading" constant="21" id="lfA-yT-amC"/> <constraint firstItem="wo8-mU-gzk" firstAttribute="top" secondItem="J6d-M3-FOb" secondAttribute="bottom" constant="8" id="pO7-UY-2E2"/> </constraints> </customView> <customObject id="345" userLabel="Dock Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="333" id="358"/> <outlet property="owner_" destination="-2" id="347"/> </connections> </customObject> <customObject id="mbL-Rz-ge5" userLabel="Tabs Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="8uq-4v-kht" id="ahm-Fv-KC7"/> <outlet property="owner_" destination="-2" id="4OD-Ed-CB4"/> </connections> </customObject> <customView id="316" userLabel="Menus Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="34"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button translatesAutoresizingMaskIntoConstraints="NO" id="317"> <rect key="frame" x="18" y="8" width="161" height="18"/> <buttonCell key="cell" type="check" title="^Hide icon in Menu Bar" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="318"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="94" name="value" keyPath="values.TotalFinderShowStatusItem" id="367"> <dictionary key="options"> <string key="NSValueTransformerName">NSNegateBoolean</string> </dictionary> </binding> </connections> </button> </subviews> <constraints> <constraint firstItem="317" firstAttribute="leading" secondItem="316" secondAttribute="leading" constant="20" symbolic="YES" id="322"/> <constraint firstItem="317" firstAttribute="centerY" secondItem="316" secondAttribute="centerY" id="371"/> </constraints> </customView> <customObject id="342" userLabel="Menus Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="316" id="357"/> <outlet property="owner_" destination="-2" id="344"/> </connections> </customObject> <userDefaultsController id="94" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/SystemFilesPreferences.xib b/plugin/SystemFilesPreferences.xib index b6182a1..bcffef2 100644 --- a/plugin/SystemFilesPreferences.xib +++ b/plugin/SystemFilesPreferences.xib @@ -1,57 +1,58 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="SystemFilesPluginPreferencesController"> <connections> <outlet property="$fileBrowserPreferences" destination="1" id="30"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="FileBrowser Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="36"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="11"> <rect key="frame" x="18" y="9" width="147" height="18"/> <buttonCell key="cell" type="check" title="^Show System Files" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="12"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="6" name="value" keyPath="values.AppleShowAllFiles" id="13"/> </connections> </button> <customView misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="19" customClass="MASShortcutView"> <rect key="frame" x="171" y="9" width="130" height="19"/> <constraints> <constraint firstAttribute="width" constant="130" id="31"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="ShowSystemFiles"/> </userDefinedRuntimeAttributes> </customView> </subviews> <constraints> <constraint firstItem="11" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="32"/> <constraint firstItem="19" firstAttribute="leading" secondItem="11" secondAttribute="trailing" constant="8" symbolic="YES" id="33"/> <constraint firstItem="19" firstAttribute="centerY" secondItem="11" secondAttribute="centerY" id="61"/> <constraint firstItem="19" firstAttribute="top" secondItem="1" secondAttribute="top" constant="8" id="62"/> <constraint firstItem="19" firstAttribute="centerY" secondItem="1" secondAttribute="centerY" id="63"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="FileBrowser Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="5"/> <outlet property="owner_" destination="-2" id="4"/> </connections> </customObject> <userDefaultsController id="6" userLabel="Shared Defaults"/> <userDefaultsController id="GH9-Co-tDG" userLabel="TotalFinder Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/TabsPreferences.xib b/plugin/TabsPreferences.xib index d410f0b..fe9da02 100644 --- a/plugin/TabsPreferences.xib +++ b/plugin/TabsPreferences.xib @@ -1,102 +1,103 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="TabsPluginPreferencesController"> <connections> <outlet property="$tabsPreferences" destination="1" id="70"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Tabs Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="139"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="11"> <rect key="frame" x="18" y="66" width="159" height="18"/> <buttonCell key="cell" type="check" title="^Use narrow Tabs Bar" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="12"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderNarrowTabsBar" id="13"/> </connections> </button> <textField verticalHuggingPriority="750" misplaced="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="19"> <rect key="frame" x="18" y="102" width="124" height="17"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Toggle Dual Mode" id="20"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <customView misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="32" customClass="MASShortcutView"> <rect key="frame" x="183" y="66" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="73"/> <constraint firstAttribute="width" constant="130" id="126"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="NarrowTabsBar"/> </userDefinedRuntimeAttributes> </customView> <customView misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="49" customClass="MASShortcutView"> <rect key="frame" x="148" y="101" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="74"/> <constraint firstAttribute="width" constant="130" id="124"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="DualMode"/> </userDefinedRuntimeAttributes> </customView> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="75"> <rect key="frame" x="18" y="32" width="151" height="18"/> <buttonCell key="cell" type="check" title="^Freelance Windows" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="76"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderDontMakeTabs" id="88"/> </connections> </button> <button misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="102"> <rect key="frame" x="18" y="-2" width="262" height="18"/> <buttonCell key="cell" type="check" title="^Open new tabs with previous location" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="103"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="4" name="value" keyPath="values.TotalFinderNewTabsWithCurrentTarget" id="110"/> </connections> </button> </subviews> <constraints> <constraint firstItem="49" firstAttribute="leading" secondItem="19" secondAttribute="trailing" constant="8" symbolic="YES" id="136"/> <constraint firstItem="19" firstAttribute="top" secondItem="1" secondAttribute="top" constant="20" symbolic="YES" id="149"/> <constraint firstItem="49" firstAttribute="centerY" secondItem="19" secondAttribute="centerY" id="150"/> <constraint firstItem="11" firstAttribute="top" secondItem="19" secondAttribute="bottom" constant="20" id="153"/> <constraint firstItem="32" firstAttribute="centerY" secondItem="11" secondAttribute="centerY" id="156"/> <constraint firstItem="32" firstAttribute="leading" secondItem="11" secondAttribute="trailing" constant="8" symbolic="YES" id="157"/> <constraint firstItem="11" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="158"/> <constraint firstItem="19" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="159"/> <constraint firstItem="75" firstAttribute="top" secondItem="11" secondAttribute="bottom" constant="20" id="160"/> <constraint firstItem="102" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="169"/> <constraint firstItem="75" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="171"/> <constraint firstItem="102" firstAttribute="top" secondItem="75" secondAttribute="bottom" constant="20" id="E1e-Ie-UVr"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="2" userLabel="Tabs Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="72"/> <outlet property="owner_" destination="-2" id="71"/> </connections> </customObject> <userDefaultsController id="4" userLabel="Shared Defaults" customClass="TotalUserDefaultsController"/> </objects> </document> diff --git a/plugin/VisorPreferences.xib b/plugin/VisorPreferences.xib index 3b8ed0f..94e0935 100644 --- a/plugin/VisorPreferences.xib +++ b/plugin/VisorPreferences.xib @@ -1,437 +1,437 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> - <capability name="box content view" minToolsVersion="7.0"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="VisorPluginPreferencesController"> <connections> <outlet property="$modifierIcon1" destination="479" id="1432"/> <outlet property="$modifierIcon2" destination="477" id="1433"/> <outlet property="$visorPreferences" destination="1" id="1431"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView id="1" userLabel="Visor Preferences"> <rect key="frame" x="0.0" y="0.0" width="480" height="428"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <subviews> <box autoresizesSubviews="NO" borderType="bezel" titlePosition="noTitle" translatesAutoresizingMaskIntoConstraints="NO" id="460"> <rect key="frame" x="17" y="16" width="446" height="368"/> <view key="contentView" id="7Jc-52-NrS"> <rect key="frame" x="3" y="3" width="440" height="362"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="110" translatesAutoresizingMaskIntoConstraints="NO" id="469" customClass="PreferencesTextField"> - <rect key="frame" x="14" y="330" width="114" height="17"/> + <rect key="frame" x="14" y="331" width="114" height="16"/> <constraints> <constraint firstAttribute="width" constant="110" id="1494"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="^Activation:" id="503"> <font key="font" metaFont="systemBold"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="508"/> </connections> </textField> <button translatesAutoresizingMaskIntoConstraints="NO" id="483"> - <rect key="frame" x="137" y="53" width="146" height="18"/> + <rect key="frame" x="137" y="53" width="145" height="18"/> <buttonCell key="cell" type="check" title="^Show on all Spaces" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="486"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderOnEverySpace" id="517"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="518"/> </connections> </button> <box title="Title" titlePosition="noTitle" translatesAutoresizingMaskIntoConstraints="NO" id="482"> - <rect key="frame" x="136" y="116" width="181" height="43"/> + <rect key="frame" x="136" y="117" width="181" height="43"/> <view key="contentView" id="d65-Fj-ZcM"> - <rect key="frame" x="2" y="2" width="177" height="39"/> + <rect key="frame" x="3" y="3" width="175" height="37"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <slider verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="487"> - <rect key="frame" x="12" y="8" width="80" height="24"/> + <rect key="frame" x="11" y="7" width="80" height="24"/> <constraints> <constraint firstAttribute="width" constant="76" id="635"/> </constraints> <sliderCell key="cell" continuous="YES" alignment="left" maxValue="1" doubleValue="0.44444444444444442" tickMarkPosition="below" numberOfTickMarks="10" allowsTickMarkValuesOnly="YES" sliderType="linear" id="491"> - <font key="font" size="12" name="Helvetica"/> + <font key="font" metaFont="user"/> </sliderCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderAnimationSpeed" id="529"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="530"/> </connections> </slider> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="488"> - <rect key="frame" x="100" y="8" width="66" height="22"/> + <rect key="frame" x="99" y="8" width="66" height="21"/> <constraints> <constraint firstAttribute="width" constant="66" id="546"/> </constraints> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" alignment="center" title="3 0 sec" drawsBackground="YES" id="489"> <numberFormatter key="formatter" formatterBehavior="10_0" positiveFormat="#,##0.0 sec" negativeFormat="-#,##0.0 sec" thousandSeparator="," id="490"> <attributedString key="attributedStringForZero"> <fragment content="0"/> </attributedString> <decimal key="minimum" value="NaN"/> <decimal key="maximum" value="NaN"/> </numberFormatter> <font key="font" metaFont="system"/> - <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> + <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderAnimationSpeed" id="531"/> </connections> </textFieldCell> <connections> <binding destination="457" name="editable" keyPath="values.TotalFinderVisorEnabled" id="527"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" previousBinding="527" id="528"/> </connections> </textField> </subviews> </view> <constraints> <constraint firstAttribute="height" constant="37" id="1442"/> <constraint firstItem="487" firstAttribute="top" secondItem="482" secondAttribute="top" constant="9" id="Abb-Tt-Rsc"/> <constraint firstItem="487" firstAttribute="leading" secondItem="482" secondAttribute="leading" constant="13" id="M2L-0v-MW8"/> <constraint firstAttribute="trailing" secondItem="488" secondAttribute="trailing" constant="10" id="hQ3-FZ-wcL"/> <constraint firstItem="488" firstAttribute="top" secondItem="487" secondAttribute="top" id="lxg-Mi-ube"/> </constraints> </box> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="110" translatesAutoresizingMaskIntoConstraints="NO" id="471" customClass="PreferencesTextField"> - <rect key="frame" x="14" y="184" width="114" height="17"/> + <rect key="frame" x="14" y="185" width="114" height="16"/> <constraints> <constraint firstAttribute="width" constant="110" id="1498"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="^Animation:" id="501"> <font key="font" metaFont="systemBold"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="521"/> </connections> </textField> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="110" translatesAutoresizingMaskIntoConstraints="NO" id="470" customClass="PreferencesTextField"> - <rect key="frame" x="14" y="245" width="114" height="17"/> + <rect key="frame" x="14" y="246" width="114" height="16"/> <constraints> <constraint firstAttribute="width" constant="110" id="1500"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="^Control:" id="502"> <font key="font" metaFont="systemBold"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="536"/> </connections> </textField> <comboBox verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="481"> - <rect key="frame" x="139" y="73" width="222" height="26"/> + <rect key="frame" x="139" y="73" width="222" height="25"/> <constraints> <constraint firstAttribute="width" constant="219" id="551"/> </constraints> <comboBoxCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" borderStyle="bezel" title="Screen 0" drawsBackground="YES" completes="NO" usesDataSource="YES" numberOfVisibleItems="5" id="492"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </comboBoxCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderScreen" id="1429"> <dictionary key="options"> <string key="NSValueTransformerName">PreferencesScreenTransformer</string> </dictionary> </binding> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="520"/> <outlet property="dataSource" destination="-2" id="1435"/> </connections> </comboBox> <button translatesAutoresizingMaskIntoConstraints="NO" id="480"> <rect key="frame" x="137" y="294" width="22" height="18"/> <constraints> <constraint firstAttribute="height" constant="14" id="1268"/> </constraints> <buttonCell key="cell" type="check" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="493"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderHotKey2Enabled" id="515"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="516"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="478"> - <rect key="frame" x="137" y="163" width="110" height="18"/> + <rect key="frame" x="137" y="164" width="110" height="18"/> <buttonCell key="cell" type="check" title="^Slide Window" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="495"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderUseSlide" id="525"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="526"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="476"> - <rect key="frame" x="137" y="183" width="110" height="18"/> + <rect key="frame" x="137" y="184" width="110" height="18"/> <buttonCell key="cell" type="check" title="^Fade Window" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="497"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderUseFade" id="523"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="524"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="475"> <rect key="frame" x="137" y="33" width="178" height="18"/> <buttonCell key="cell" type="check" title="^Show on top of the Dock" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="498"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="533"/> <binding destination="457" name="value" keyPath="values.TotalFinderVisorOnDockLevel" id="532"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="474"> <rect key="frame" x="137" y="13" width="142" height="18"/> <constraints> <constraint firstAttribute="height" constant="14" id="1443"/> </constraints> <buttonCell key="cell" type="check" title="^Free Form Window" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="499"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="538"/> <binding destination="457" name="value" keyPath="values.TotalFinderVisorFreeForm" id="537"/> </connections> </button> <button translatesAutoresizingMaskIntoConstraints="NO" id="473"> - <rect key="frame" x="137" y="244" width="104" height="18"/> + <rect key="frame" x="137" y="245" width="104" height="18"/> <buttonCell key="cell" type="check" title="^Hide on ESC" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="500"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderHideOnEscape" id="534"/> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="535"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" preferredMaxLayoutWidth="110" translatesAutoresizingMaskIntoConstraints="NO" id="468" customClass="PreferencesTextField"> - <rect key="frame" x="14" y="77" width="114" height="17"/> + <rect key="frame" x="14" y="79" width="114" height="16"/> <constraints> <constraint firstAttribute="width" constant="110" id="1497"/> </constraints> <textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="^Screen:" id="504"> <font key="font" metaFont="systemBold"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="522"/> </connections> </textField> <customView translatesAutoresizingMaskIntoConstraints="NO" id="464" customClass="MASShortcutView"> <rect key="frame" x="226" y="220" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="1437"/> <constraint firstAttribute="width" constant="130" id="1461"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="PinVisor"/> </userDefinedRuntimeAttributes> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="541"/> </connections> </customView> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="465" customClass="PreferencesTextField"> - <rect key="frame" x="156" y="222" width="64" height="17"/> + <rect key="frame" x="156" y="223" width="64" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="^Pin Visor" id="505"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="542"/> </connections> </textField> <box autoresizesSubviews="NO" borderType="none" title="Box" titlePosition="noTitle" translatesAutoresizingMaskIntoConstraints="NO" id="1229"> - <rect key="frame" x="155" y="266" width="177" height="71"/> + <rect key="frame" x="155" y="267" width="177" height="70"/> <view key="contentView" id="oYG-9X-EdO"> - <rect key="frame" x="0.0" y="0.0" width="177" height="71"/> + <rect key="frame" x="0.0" y="0.0" width="177" height="70"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView translatesAutoresizingMaskIntoConstraints="NO" id="477" customClass="PreferencesModifierButtonImageView"> - <rect key="frame" x="101" y="15" width="57" height="43"/> + <rect key="frame" x="101" y="15" width="57" height="42"/> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="ModifiersOption" id="496"/> <connections> <binding destination="457" name="enabled2" keyPath="values.TotalFinderHotKey2Enabled" previousBinding="513" id="514"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="513"/> </connections> </imageView> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="484" customClass="PreferencesTextField"> - <rect key="frame" x="82" y="28" width="13" height="17"/> + <rect key="frame" x="82" y="28" width="13" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="+" id="485"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <binding destination="457" name="enabled2" keyPath="values.TotalFinderHotKey2Enabled" previousBinding="509" id="510"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="509"/> </connections> </textField> <imageView translatesAutoresizingMaskIntoConstraints="NO" id="479" customClass="PreferencesModifierButtonImageView"> - <rect key="frame" x="19" y="15" width="57" height="43"/> + <rect key="frame" x="19" y="15" width="57" height="42"/> <constraints> <constraint firstAttribute="width" constant="57" id="1416"/> </constraints> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" animates="YES" imageScaling="proportionallyDown" image="ModifiersOption" id="494"/> <connections> <binding destination="457" name="enabled2" keyPath="values.TotalFinderHotKey2Enabled" previousBinding="511" id="512"> <dictionary key="options"> <integer key="NSMultipleValuesPlaceholder" value="-1"/> <integer key="NSNoSelectionPlaceholder" value="-1"/> <integer key="NSNotApplicablePlaceholder" value="-1"/> <integer key="NSNullPlaceholder" value="-1"/> </dictionary> </binding> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="511"/> </connections> </imageView> </subviews> </view> <constraints> <constraint firstAttribute="trailing" secondItem="477" secondAttribute="trailing" constant="16" id="9FI-O4-uo1"/> <constraint firstItem="479" firstAttribute="leading" secondItem="1229" secondAttribute="leading" constant="16" id="9SP-aE-1In"/> <constraint firstItem="479" firstAttribute="top" secondItem="1229" secondAttribute="top" constant="11" id="Dd4-Tj-6wI"/> <constraint firstItem="484" firstAttribute="leading" secondItem="479" secondAttribute="trailing" constant="8" symbolic="YES" id="HLz-Rc-ZQy"/> <constraint firstItem="477" firstAttribute="top" secondItem="1229" secondAttribute="top" constant="11" id="Rdt-wA-vt4"/> <constraint firstAttribute="bottom" secondItem="477" secondAttribute="bottom" constant="11" id="Vbv-fl-4SB"/> <constraint firstAttribute="bottom" secondItem="479" secondAttribute="bottom" constant="11" id="f58-AW-BYQ"/> <constraint firstItem="484" firstAttribute="centerY" secondItem="479" secondAttribute="centerY" id="sRQ-x5-GPf"/> <constraint firstItem="477" firstAttribute="leading" secondItem="484" secondAttribute="trailing" constant="8" symbolic="YES" id="tu0-P7-jBO"/> <constraint firstItem="484" firstAttribute="centerX" secondItem="1229" secondAttribute="centerX" id="zLI-xb-lfL"/> </constraints> </box> <customView translatesAutoresizingMaskIntoConstraints="NO" id="463" customClass="MASShortcutView"> <rect key="frame" x="139" y="328" width="130" height="19"/> <constraints> <constraint firstAttribute="height" constant="19" id="1438"/> <constraint firstAttribute="width" constant="130" id="1462"/> </constraints> <userDefinedRuntimeAttributes> <userDefinedRuntimeAttribute type="string" keyPath="$shortcutName" value="ToggleVisor"/> </userDefinedRuntimeAttributes> <connections> <binding destination="457" name="enabled" keyPath="values.TotalFinderVisorEnabled" id="540"/> </connections> </customView> </subviews> </view> <constraints> <constraint firstAttribute="height" constant="362" id="1456"/> <constraint firstItem="1229" firstAttribute="leading" secondItem="460" secondAttribute="leading" constant="158" id="2Jl-fh-8GF"/> <constraint firstItem="482" firstAttribute="top" secondItem="478" secondAttribute="bottom" constant="8" symbolic="YES" id="2uF-T0-9g4"/> <constraint firstAttribute="bottom" secondItem="474" secondAttribute="bottom" constant="14" id="36V-sz-ySc"/> <constraint firstItem="483" firstAttribute="height" secondItem="474" secondAttribute="height" id="4bk-bO-wBO"/> <constraint firstItem="471" firstAttribute="leading" secondItem="460" secondAttribute="leading" constant="16" id="5GE-KI-0Xz"/> <constraint firstItem="463" firstAttribute="leading" secondItem="476" secondAttribute="leading" id="APS-Er-Jkz"/> <constraint firstItem="1229" firstAttribute="top" secondItem="460" secondAttribute="top" constant="28" id="B56-Xc-Ann"/> <constraint firstItem="474" firstAttribute="top" secondItem="475" secondAttribute="bottom" constant="6" symbolic="YES" id="BA3-6a-pz1"/> <constraint firstItem="469" firstAttribute="leading" secondItem="460" secondAttribute="leading" constant="16" id="D05-WY-rYb"/> <constraint firstItem="471" firstAttribute="top" secondItem="460" secondAttribute="top" constant="162" id="Efh-Iq-MLe"/> <constraint firstItem="475" firstAttribute="top" secondItem="483" secondAttribute="bottom" constant="6" symbolic="YES" id="Fze-Nu-BSg"/> <constraint firstItem="1229" firstAttribute="leading" secondItem="465" secondAttribute="leading" id="HSv-s7-Amf"/> <constraint firstItem="470" firstAttribute="top" secondItem="460" secondAttribute="top" constant="101" id="I05-uh-zil"/> <constraint firstItem="463" firstAttribute="leading" secondItem="481" secondAttribute="leading" id="J9T-3R-tia"/> <constraint firstItem="468" firstAttribute="leading" secondItem="460" secondAttribute="leading" constant="16" id="LSG-J3-r3J"/> <constraint firstItem="463" firstAttribute="leading" secondItem="483" secondAttribute="leading" id="Nxg-Ip-QPL"/> <constraint firstItem="469" firstAttribute="top" secondItem="460" secondAttribute="top" constant="16" id="QkC-m4-YfL"/> <constraint firstItem="470" firstAttribute="leading" secondItem="460" secondAttribute="leading" constant="16" id="QqV-dT-gBc"/> <constraint firstItem="463" firstAttribute="leading" secondItem="460" secondAttribute="leading" constant="139" id="R1C-ls-Y9L"/> <constraint firstItem="463" firstAttribute="leading" secondItem="482" secondAttribute="leading" id="Ub3-XL-sCT"/> <constraint firstItem="464" firstAttribute="leading" secondItem="465" secondAttribute="trailing" constant="8" symbolic="YES" id="WGm-fJ-Qsh"/> <constraint firstItem="463" firstAttribute="leading" secondItem="478" secondAttribute="leading" id="WNx-mM-xcY"/> <constraint firstItem="463" firstAttribute="leading" secondItem="480" secondAttribute="leading" id="Xlo-za-sRV"/> <constraint firstItem="463" firstAttribute="leading" secondItem="475" secondAttribute="leading" id="aiP-IN-oMf"/> <constraint firstItem="463" firstAttribute="leading" secondItem="474" secondAttribute="leading" id="ao3-U9-6AK"/> <constraint firstItem="483" firstAttribute="top" secondItem="481" secondAttribute="bottom" constant="8" symbolic="YES" id="b6B-os-aBr"/> <constraint firstItem="480" firstAttribute="top" secondItem="460" secondAttribute="top" constant="53" id="c7a-zR-w0h"/> <constraint firstItem="482" firstAttribute="trailing" secondItem="481" secondAttribute="trailing" constant="-44" id="g9v-Gq-qlD"/> <constraint firstItem="476" firstAttribute="baseline" secondItem="471" secondAttribute="baseline" id="guk-sE-ghC"/> <constraint firstItem="463" firstAttribute="leading" secondItem="480" secondAttribute="leading" priority="1" id="i2S-kN-5yu"/> <constraint firstItem="478" firstAttribute="top" secondItem="476" secondAttribute="bottom" constant="6" symbolic="YES" id="idn-27-Hqk"/> <constraint firstItem="465" firstAttribute="top" secondItem="464" secondAttribute="top" id="jnC-rX-t0V"/> <constraint firstItem="465" firstAttribute="top" secondItem="460" secondAttribute="top" constant="124" id="kxD-wg-Fnp"/> <constraint firstItem="481" firstAttribute="baseline" secondItem="468" secondAttribute="baseline" id="mdJ-lK-kSe"/> <constraint firstItem="463" firstAttribute="leading" secondItem="473" secondAttribute="leading" id="nk8-bR-CEO"/> <constraint firstItem="483" firstAttribute="height" secondItem="475" secondAttribute="height" id="rmu-uX-nEE"/> <constraint firstItem="1229" firstAttribute="centerY" secondItem="480" secondAttribute="centerY" id="w1K-G9-hke"/> <constraint firstItem="463" firstAttribute="top" secondItem="469" secondAttribute="top" id="x04-J2-wpc"/> <constraint firstItem="470" firstAttribute="baseline" secondItem="473" secondAttribute="baseline" id="xiA-Br-zi5"/> </constraints> </box> <button translatesAutoresizingMaskIntoConstraints="NO" id="721"> - <rect key="frame" x="18" y="400" width="116" height="18"/> + <rect key="frame" x="18" y="400" width="115" height="18"/> <buttonCell key="cell" type="check" title="^Visor Feature" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="726"> <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/> <font key="font" metaFont="systemBold"/> </buttonCell> <connections> <binding destination="457" name="value" keyPath="values.TotalFinderVisorEnabled" id="727"/> </connections> </button> <textField verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="722"> <rect key="frame" x="38" y="390" width="272" height="11"/> <textFieldCell key="cell" controlSize="mini" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="^a system-wide window sliding from the bottom on a hot-key" id="724"> <font key="font" metaFont="miniSystem"/> <color key="textColor" red="0.41304347829999999" green="0.41304347829999999" blue="0.41304347829999999" alpha="1" colorSpace="calibratedRGB"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="721" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="732"/> <constraint firstItem="460" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="735"/> <constraint firstAttribute="trailing" secondItem="460" secondAttribute="trailing" constant="20" symbolic="YES" id="743"/> <constraint firstItem="722" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="40" id="1428"/> <constraint firstItem="721" firstAttribute="top" secondItem="1" secondAttribute="top" constant="12" id="1514"/> <constraint firstItem="460" firstAttribute="top" secondItem="722" secondAttribute="bottom" constant="8" symbolic="YES" id="1533"/> <constraint firstAttribute="bottom" secondItem="460" secondAttribute="bottom" constant="20" symbolic="YES" id="1534"/> </constraints> + <point key="canvasLocation" x="139" y="154"/> </customView> <customObject id="810" userLabel="Visor Localizer" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="1" id="817"/> <outlet property="owner_" destination="-2" id="816"/> </connections> </customObject> <userDefaultsController id="457" userLabel="Tweaks" customClass="TotalUserDefaultsController"/> </objects> <resources> <image name="ModifiersOption" width="330" height="230"/> </resources> </document>
binaryage/totalfinder-i18n
599ce9cdf77da04c4cc527cf295f471a2ee80f3a
review constraints for cut and paste menu buttons
diff --git a/plugin/CutAndPaste.xib b/plugin/CutAndPaste.xib index 8b65aa0..e896a2c 100644 --- a/plugin/CutAndPaste.xib +++ b/plugin/CutAndPaste.xib @@ -1,87 +1,80 @@ <?xml version="1.0" encoding="UTF-8"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="13189.4" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15400" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="13189.4"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15400"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="AHEditMenuController"> <connections> <outlet property="$copyButton" destination="32" id="89"/> <outlet property="$cutButton" destination="33" id="88"/> <outlet property="$editMenuItemView" destination="26" id="86"/> <outlet property="$pasteButton" destination="31" id="87"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <customView autoresizesSubviews="NO" horizontalCompressionResistancePriority="1000" placeholderIntrinsicWidth="400" placeholderIntrinsicHeight="19" id="26" userLabel="EditMenuItemView" customClass="MenuTrackedRootView"> - <rect key="frame" x="0.0" y="0.0" width="218" height="18"/> + <rect key="frame" x="0.0" y="0.0" width="218" height="34"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> - <customView translatesAutoresizingMaskIntoConstraints="NO" id="W6i-FP-HUk" userLabel="Container"> - <rect key="frame" x="0.0" y="0.0" width="161" height="18"/> - <subviews> - <button verticalHuggingPriority="750" tag="36000" translatesAutoresizingMaskIntoConstraints="NO" id="33" userLabel="Cut Button" customClass="MenuTrackedButton"> - <rect key="frame" x="20" y="-1" width="41" height="20"/> - <buttonCell key="cell" type="smallSquare" title="^Cut" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="34" customClass="WrenchMenuButtonCell"> - <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> - <font key="font" metaFont="smallSystem"/> - </buttonCell> - <connections> - <action selector="$commandsDispatcher:" target="-2" id="48"/> - </connections> - </button> - <button verticalHuggingPriority="750" tag="36001" translatesAutoresizingMaskIntoConstraints="NO" id="32" userLabel="Copy Button" customClass="MenuTrackedButton"> - <rect key="frame" x="60" y="-1" width="41" height="20"/> - <buttonCell key="cell" type="smallSquare" title="^Copy" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="35" customClass="WrenchMenuButtonCell"> - <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> - <font key="font" metaFont="smallSystem"/> - </buttonCell> - <connections> - <action selector="$commandsDispatcher:" target="-2" id="49"/> - </connections> - </button> - <button verticalHuggingPriority="750" tag="36003" translatesAutoresizingMaskIntoConstraints="NO" id="31" userLabel="Paste Button" customClass="MenuTrackedButton"> - <rect key="frame" x="100" y="-1" width="41" height="20"/> - <buttonCell key="cell" type="smallSquare" title="^Paste" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="36" customClass="WrenchMenuButtonCell"> - <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> - <font key="font" metaFont="smallSystem"/> - </buttonCell> - <connections> - <action selector="$commandsDispatcher:" target="-2" id="50"/> - </connections> - </button> - </subviews> + <button verticalHuggingPriority="750" tag="36000" translatesAutoresizingMaskIntoConstraints="NO" id="33" userLabel="Cut Button" customClass="MenuTrackedButton"> + <rect key="frame" x="20" y="7" width="40" height="20"/> <constraints> - <constraint firstItem="32" firstAttribute="width" secondItem="31" secondAttribute="width" id="Ai6-Ku-9d7"/> - <constraint firstAttribute="trailing" secondItem="31" secondAttribute="trailing" constant="20" id="Eck-YR-etY"/> - <constraint firstItem="31" firstAttribute="leading" secondItem="32" secondAttribute="trailing" constant="-1" id="JHM-kz-XmU"/> - <constraint firstAttribute="bottom" secondItem="33" secondAttribute="bottom" id="XIP-Vn-1sy"/> - <constraint firstAttribute="bottom" secondItem="31" secondAttribute="bottom" id="YXj-ln-8uZ"/> - <constraint firstItem="32" firstAttribute="top" secondItem="W6i-FP-HUk" secondAttribute="top" id="bLq-wL-Xjb"/> - <constraint firstItem="31" firstAttribute="top" secondItem="W6i-FP-HUk" secondAttribute="top" id="gU1-B0-Wq4"/> - <constraint firstItem="32" firstAttribute="leading" secondItem="33" secondAttribute="trailing" constant="-1" id="i6c-6U-4OB"/> - <constraint firstItem="33" firstAttribute="top" secondItem="W6i-FP-HUk" secondAttribute="top" id="maS-Om-Epu"/> - <constraint firstItem="32" firstAttribute="width" secondItem="33" secondAttribute="width" id="nd2-hr-HK5"/> - <constraint firstItem="33" firstAttribute="leading" secondItem="W6i-FP-HUk" secondAttribute="leading" constant="20" id="pJi-1L-HTR"/> - <constraint firstAttribute="bottom" secondItem="32" secondAttribute="bottom" id="qf1-1F-QN0"/> + <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="40" id="FzI-0D-1ou"/> </constraints> - </customView> + <buttonCell key="cell" type="smallSquare" title="^Cut" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="34" customClass="WrenchMenuButtonCell"> + <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> + <font key="font" metaFont="menu" size="11"/> + </buttonCell> + <connections> + <action selector="$commandsDispatcher:" target="-2" id="48"/> + </connections> + </button> + <button verticalHuggingPriority="750" tag="36001" translatesAutoresizingMaskIntoConstraints="NO" id="32" userLabel="Copy Button" customClass="MenuTrackedButton"> + <rect key="frame" x="62" y="7" width="40" height="20"/> + <constraints> + <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="40" id="d4f-XI-OAS"/> + </constraints> + <buttonCell key="cell" type="smallSquare" title="^Copy" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="35" customClass="WrenchMenuButtonCell"> + <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> + <font key="font" metaFont="menu" size="11"/> + </buttonCell> + <connections> + <action selector="$commandsDispatcher:" target="-2" id="49"/> + </connections> + </button> + <button verticalHuggingPriority="750" tag="36003" translatesAutoresizingMaskIntoConstraints="NO" id="31" userLabel="Paste Button" customClass="MenuTrackedButton"> + <rect key="frame" x="104" y="7" width="41" height="20"/> + <constraints> + <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="40" id="pac-Hw-Vb6"/> + </constraints> + <buttonCell key="cell" type="smallSquare" title="^Paste" bezelStyle="smallSquare" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="36" customClass="WrenchMenuButtonCell"> + <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> + <font key="font" metaFont="menu" size="11"/> + </buttonCell> + <connections> + <action selector="$commandsDispatcher:" target="-2" id="50"/> + </connections> + </button> </subviews> <constraints> - <constraint firstItem="W6i-FP-HUk" firstAttribute="leading" secondItem="26" secondAttribute="leading" id="QKW-b4-aaa"/> - <constraint firstAttribute="bottom" secondItem="W6i-FP-HUk" secondAttribute="bottom" id="hni-Oe-Spz"/> - <constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="W6i-FP-HUk" secondAttribute="trailing" id="ne6-dC-eWJ"/> - <constraint firstItem="W6i-FP-HUk" firstAttribute="top" secondItem="26" secondAttribute="top" id="nyD-to-tsz"/> + <constraint firstItem="31" firstAttribute="top" secondItem="26" secondAttribute="top" constant="8" id="E61-8i-P6f"/> + <constraint firstItem="33" firstAttribute="leading" secondItem="26" secondAttribute="leading" constant="20" id="EUC-Cr-oI9"/> + <constraint firstItem="32" firstAttribute="leading" secondItem="33" secondAttribute="trailing" constant="2" id="EwJ-Ao-4Tl"/> + <constraint firstItem="33" firstAttribute="top" secondItem="26" secondAttribute="top" constant="8" id="UH3-Rg-fM6"/> + <constraint firstItem="31" firstAttribute="leading" secondItem="32" secondAttribute="trailing" constant="2" id="b9r-11-MRS"/> + <constraint firstItem="32" firstAttribute="top" secondItem="26" secondAttribute="top" constant="8" id="pLU-J8-D33"/> </constraints> + <point key="canvasLocation" x="139" y="179"/> </customView> <customObject id="40" customClass="GTMUILocalizer"> <connections> <outlet property="otherObjectToLocalize_" destination="26" id="V6l-BM-FdS"/> <outlet property="owner_" destination="-2" id="qpW-gu-vRm"/> </connections> </customObject> </objects> </document>
binaryage/totalfinder-i18n
d4bbeff2034b2b41c0acd4c25e60f7b05f1686e7
crashwatcher: force external encoding to UTF-8
diff --git a/crashwatcher/ruby/upload-gist.rb b/crashwatcher/ruby/upload-gist.rb index fcfbdad..27f348a 100755 --- a/crashwatcher/ruby/upload-gist.rb +++ b/crashwatcher/ruby/upload-gist.rb @@ -1,32 +1,37 @@ #!/usr/bin/env ruby # frozen_string_literal: true # https://github.com/defunkt/gist/blob/master/lib/gist.rb +# this is to override encoding problems, users might have different locales set +# even US-ASCII could throw Encoding::InvalidByteSequenceError +# see https://makandracards.com/makandra/41250-ruby-s-default-encodings-can-be-unexpected +Encoding.default_external = 'UTF-8' + begin # noinspection RubyResolve require File.join File.dirname(__FILE__), 'gist.rb' rescue LoadError # noinspection RubyResolve begin require File.join File.dirname(__FILE__), 'vendor', 'gist.rb' rescue LoadError raise 'Failed to require gist.rb' end end # for now, I just support one file to upload file = ARGV[0].to_s token = ARGV[1].to_s raise 'no file path specified' if file.empty? raise 'no github access token specified' if token.empty? file_content = File.read(file) options = { filename: 'TotalFinder.crash', access_token: token, output: :html_url } puts Gist.gist(file_content, options)
binaryage/totalfinder-i18n
8858ed549060a225708db6e5676bdf56c89c4d7a
crashwatcher: make rubocop happy again
diff --git a/crashwatcher/ruby/.rubocop.yml b/crashwatcher/ruby/.rubocop.yml index ca9744e..5257a13 100644 --- a/crashwatcher/ruby/.rubocop.yml +++ b/crashwatcher/ruby/.rubocop.yml @@ -1,63 +1,64 @@ AllCops: - TargetRubyVersion: 2.3 + TargetRubyVersion: 2.6 Include: + - '**/*.rb' - '**/Gemfile' - '**/Rakefile' - '**/rakefile' Exclude: - '_node/**/*' - 'vendor/**/*' Metrics/LineLength: Max: 126 Layout/SpaceAroundEqualsInParameterDefault: EnforcedStyle: no_space Metrics/MethodLength: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false Metrics/BlockNesting: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/ClassLength: Enabled: false Style/Documentation: Enabled: false -Layout/IndentArray: +Layout/IndentFirstArrayElement: Enabled: false Style/GuardClause: Enabled: false Metrics/PerceivedComplexity: Enabled: false Style/TernaryParentheses: Enabled: false Style/RegexpLiteral: Enabled: false Style/RescueStandardError: Enabled: false Style/SafeNavigation: Enabled: false Lint/HandleExceptions: Enabled: false Style/SpecialGlobalVars: Enabled: false diff --git a/crashwatcher/ruby/extract-crash-info.rb b/crashwatcher/ruby/extract-crash-info.rb index 52adf14..f9923ca 100755 --- a/crashwatcher/ruby/extract-crash-info.rb +++ b/crashwatcher/ruby/extract-crash-info.rb @@ -1,112 +1,115 @@ #!/usr/bin/env ruby # frozen_string_literal: true def parse_module_version(content) m = content.match(/\+\s*com.binaryage.totalfinder\s*\((.*?)\)/m) return nil if m.nil? + # m[1] == 1.5.18 - 1.5.18 m[1].split('-')[0].strip end def parse_special_info(content) # "recent swizzled method" can appear in TotalFinder crash logs since v1.4.18 m = content.match(/recent swizzled method:(.*?)\n/m) return nil if m.nil? + m[1].strip end def parse_plugin_identifier(content) m = content.match(/PlugIn Identifier:(.*?)\n/m) return nil if m.nil? + m[1] end def find_first_ba_module(content) addresses = [] ranges = [] content.lines.each do |line| # extract addresses from callstacks on all threads - # 8 com.apple.AppKit 0x00007fff88a0d68f -[NSApplication run] + 395 + # 8 com.apple.AppKit 0x00007fff88a0d68f -[NSApplication run] + 395 addresses << Regexp.last_match(1).to_i(16) if line =~ /^\s*\d+\s+.*?0x([0-9a-f]+)\s/ # extract loaded module ranges, filter out only com.binaryage related # 0x1181c2000 - 0x1181c3ff7 +com.binaryage.totalfinder.nodesktopdots ##VERSION## (##VERSION##) <...> /some/path if line =~ /^\s*0x([0-9a-f]+)\s+-\s+0x([0-9a-f]+)\s+.*?(com\.binaryage.*?)\s/ ranges << [Regexp.last_match(1).to_i(16), Regexp.last_match(2).to_i(16), Regexp.last_match(3)] end end # test if any address is present inside our ranges addresses.each do |address| ranges.each do |range| hit = address >= range[0] && address <= range[1] return range[2] if hit end end nil end file = File.absolute_path(ARGV[0]) # this is just a special sanity check to include related-crash-report.rb errors in case related-crash-report.rb throws related_script_path = File.join(File.dirname(File.absolute_path(__FILE__)), 'related-crash-report.rb') system(related_script_path, file, err: :out) result = $?.exitstatus throw "The crash report '#{file}' is not related to TotalFinder" if result != 3 content = File.read(file) res = 'TotalFinder ' begin module_version = parse_module_version(content) res += "#{module_version} " if module_version plugin = parse_special_info(content) plugin ||= parse_plugin_identifier(content) plugin ||= find_first_ba_module(content) plugin.strip! if plugin res += 'crashed in ' + plugin.gsub('com.binaryage.totalfinder.', '') + ' ' if plugin rescue # ignored end details = [] begin version = content.match(/Version:(.*?)\n/m)[1].split(' ')[0] details << 'v' + version.strip rescue # ignored end begin version = content.match(/OS Version:.*?\((.*?)\)\n/m)[1] details << 'OS ' + version.strip rescue # ignored end begin type = content.match(/Exception Type:(.*?)\n/m)[1] x = type.match(/(.*?)\(.*\)/) type = x[1] if x # remove braced part if present type.downcase! type.sub!('exc_', '') type.sub!('_', ' ') details << type.strip rescue # ignored end begin thread = content.match(/Crashed Thread:(.*?)\n/m)[1].split(' ')[0] details << 'thread ' + thread.strip rescue # ignored end res += "| #{details.join(', ')}" puts res diff --git a/crashwatcher/ruby/related-crash-report.rb b/crashwatcher/ruby/related-crash-report.rb index cb15659..d55648a 100755 --- a/crashwatcher/ruby/related-crash-report.rb +++ b/crashwatcher/ruby/related-crash-report.rb @@ -1,37 +1,37 @@ #!/usr/bin/env ruby # frozen_string_literal: true file = ARGV[0] report = File.read(file) # OSX stack traces look like sample.crash # we want to test for presence of com.binaryage.* anywhere on the stack # we extract all com.binaryage.* ranges from "Binary Images" section # and also all addresses on all callstacks # then test if any of addresses hit some of our ranges addresses = [] ranges = [] report.lines.each do |line| # extract addresses from callstacks on all threads - # 8 com.apple.AppKit 0x00007fff88a0d68f -[NSApplication run] + 395 + # 8 com.apple.AppKit 0x00007fff88a0d68f -[NSApplication run] + 395 addresses << Regexp.last_match(1).to_i(16) if line =~ /^\s*\d+\s+.*?0x([0-9a-f]+)\s/ # extract loaded module ranges, filter out only com.binaryage related # 0x1181c2000 - 0x1181c3ff7 +com.binaryage.totalfinder.nodesktopdots ##VERSION## (##VERSION##) <...> /some/path if line =~ /^\s*0x([0-9a-f]+)\s+-\s+0x([0-9a-f]+)\s+.*?com\.binaryage/ ranges << [Regexp.last_match(1).to_i(16), Regexp.last_match(2).to_i(16)] end end # test if any address is present inside our ranges addresses.each do |address| ranges.each do |range| hit = address >= range[0] && address <= range[1] # puts "#{address} ? #{range[0]} - #{range[1]} => #{hit}" exit 3 if hit # yes, present! end end exit 0 # not present
binaryage/totalfinder-i18n
20583670ad65e2d862a90f193029d2270751459c
uninstaller: use PRODUCT_BUNDLE_IDENTIFIER in Info.plist
diff --git a/uninstaller/Info.plist b/uninstaller/Info.plist index 666982d..05a2749 100644 --- a/uninstaller/Info.plist +++ b/uninstaller/Info.plist @@ -1,32 +1,32 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIconFile</key> <string>UninstallerIcon</string> <key>CFBundleIdentifier</key> - <string>com.binaryage.totalfinder.uninstaller</string> + <string>${PRODUCT_BUNDLE_IDENTIFIER}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>##VERSION##</string> <key>CFBundleSignature</key> <string>BAGE</string> <key>CFBundleVersion</key> <string>##VERSION##</string> <key>LSMinimumSystemVersion</key> <string>${MACOSX_DEPLOYMENT_TARGET}</string> <key>NSMainNibFile</key> <string>MainMenu.nib</string> <key>NSPrincipalClass</key> <string>NSApplication</string> </dict> </plist>
binaryage/totalfinder-i18n
0240417c1851554ed4690f51a355fa54d8fba950
added Latvian language translation
diff --git a/crashwatcher/lv.lproj/Localizable.strings b/crashwatcher/lv.lproj/Localizable.strings new file mode 100644 index 0000000..aee8691 --- /dev/null +++ b/crashwatcher/lv.lproj/Localizable.strings @@ -0,0 +1,20 @@ +"crashDialogHeader" = "TotalFinder negaidīti pārtrauca darboties"; +"crashDialogMsg" = "Mēs atvainojamies, bet TotalFinder saskārās ar neparadzētu problēmu un pārstāja darbināt Finder programmu."; +"crashDialogNote" = "Piezīme: Finder programma tika automātiski pārstartēta, bet Jums no jauna jāstartē TotalFinder.app programma."; +"crashDialogExplanation" = "Nospiežot pogu sūtīt tiks augšupielādēta programmas kļūdu atskaite vietnē gist.github.com un palaista Mail.app programma ar e-pasta sagatvi."; + +"failDialogHeader" = "Nav iespējams augšupielādēt programmas kļūdu atskaiti vietnē gist.github.com"; +"failDialogMsg1" = "Ļoti slikti. Es nevarēju atrast programmas kļūdu atskaiti Jūsu ~/Logs/CrashReporter mapē."; +"failDialogMsg2" = "Es spēju atrast programmas kļūdu atskaiti, bet augšupielāde vietnē gist.github.com bija neveiksmīga.\n\nSteidzamos gadījumos Jūs varat sūtīt programmas kļūdu atskaiti uz:\n%@"; +"failDialogOK" = "Labi"; + +"sendReportButton" = "Sagatavot e-pasta ziņojumu"; +"cancelButton" = "Atcelt"; + +"emailTemplate" = "Antonin,\n\nMy %@ just crashed!\n\nThe crash report is available here:\n%@\n\n>\n> You may help me fix the problem by describing what happened before the crash.\n> I appreciate your help and I read these crash reports, but don't expect my direct answer.\n> For further discussion please open a topic at\n> https://discuss.binaryage.com.\n>\n> Thank you, Antonin"; + +"countdownMsgSecondsPlural" = "Atlikušas %d sekundes."; +"countdownMsgSecondSingular" = "Atlikusi %d sekunde."; + +"countdownMsgMinutesPlural" = "Atlikušas %d minūtes."; +"countdownMsgMinuteSingular" = "Atlikusi %d minūte."; diff --git a/plugin/lv.lproj/ColorfulSidebar.strings b/plugin/lv.lproj/ColorfulSidebar.strings new file mode 100644 index 0000000..e671653 --- /dev/null +++ b/plugin/lv.lproj/ColorfulSidebar.strings @@ -0,0 +1 @@ +"Show sidebar icons in color" = "Parādīt krāsainas sānjoslas ikonas"; diff --git a/plugin/lv.lproj/ColumnViewAutoWidth.strings b/plugin/lv.lproj/ColumnViewAutoWidth.strings new file mode 100644 index 0000000..a887971 --- /dev/null +++ b/plugin/lv.lproj/ColumnViewAutoWidth.strings @@ -0,0 +1,3 @@ +"Automatically adjust widths in Column View" = "Automātiski pielāgot platumu Kolonnu skatā"; +"Limit maximum column width to" = "Limitēt maksimālo kolonnu platumu uz"; +"Limit minimum column width to" = "Limitēt minimālo kolonny platumu uz"; diff --git a/plugin/lv.lproj/CopyPathMenu.strings b/plugin/lv.lproj/CopyPathMenu.strings new file mode 100644 index 0000000..0041a2f --- /dev/null +++ b/plugin/lv.lproj/CopyPathMenu.strings @@ -0,0 +1,9 @@ +"Copy Path" = "Kopēt ceļu"; +"POSIX Path" = "POSIX ceļš"; +"URL" = "URL"; +"Windows Path" = "Windows ceļš"; +"HFS Path" = "HFS ceļš"; +"Terminal Path" = "Termināļa ceļš"; +"UNC Path" = "UNC ceļš"; + +"Allow path copying from Context Menus" = "Atļaut ceļa kopēšanu no Konteksta izvēlness"; diff --git a/plugin/lv.lproj/CutAndPaste.strings b/plugin/lv.lproj/CutAndPaste.strings new file mode 100644 index 0000000..eb12f75 --- /dev/null +++ b/plugin/lv.lproj/CutAndPaste.strings @@ -0,0 +1,13 @@ +/* please note these items should be translated by exactly the same conventions */ +/* as Main Menu > Edit > Copy item works in your localized Finder */ +/* do not translate it directly from English but look how your menu looks in your language */ +/* sample screenshot of English version: http://dl.dropbox.com/u/559047/Screenshots/qigu.png */ +"Edit" = "Edit"; +"Cut" = "Cut"; +"Cut “%@”" = "Cut “%@”"; +"Cut %u Items" = "Cut %u Items"; +"Paste" = "Paste"; +"Paste %u Items" = "Paste %u Items"; +"Copy" = "Copy"; + +"Show CutPaste buttons in Context Menus" = "Parādīt Cutpaste buttons iekš Konteksta izvēlnes"; diff --git a/plugin/lv.lproj/DockProgressBar.strings b/plugin/lv.lproj/DockProgressBar.strings new file mode 100644 index 0000000..48cd5b0 --- /dev/null +++ b/plugin/lv.lproj/DockProgressBar.strings @@ -0,0 +1 @@ +"Show progress bar in the Dock" = "Parādīt progresa indikatoru dokā"; diff --git a/plugin/lv.lproj/FoldersOnTop.strings b/plugin/lv.lproj/FoldersOnTop.strings new file mode 100644 index 0000000..f36e093 --- /dev/null +++ b/plugin/lv.lproj/FoldersOnTop.strings @@ -0,0 +1 @@ +"Folders on Top" = "Izlases mapes augšpusē"; diff --git a/plugin/lv.lproj/InfoLine.html b/plugin/lv.lproj/InfoLine.html new file mode 100644 index 0000000..8eba1c9 --- /dev/null +++ b/plugin/lv.lproj/InfoLine.html @@ -0,0 +1,7 @@ +<style> + html {font-family: 'Lucida Grande', arial; font-size: 10px; cursor: default; color: #999;} + html,body {overflow: hidden;} + a, a:visited { color: #66f; } + a:hover {color: #22f} +</style> +<center><b>TotalFinder ##VERSION##</b> by <a href="https://www.binaryage.com">binaryage.com</a></center> \ No newline at end of file diff --git a/plugin/lv.lproj/Labels.strings b/plugin/lv.lproj/Labels.strings new file mode 100644 index 0000000..2298fac --- /dev/null +++ b/plugin/lv.lproj/Labels.strings @@ -0,0 +1,2 @@ +"Colored Labels" = "Krāsainas kolonnu etiķetes"; +"The last applied tag determines item's background color." = "Pēdējā apstiprinātā etiķete nosaka vienuma fona krāsu."; diff --git a/plugin/lv.lproj/LicensingInfo.html b/plugin/lv.lproj/LicensingInfo.html new file mode 100644 index 0000000..d0b7d85 --- /dev/null +++ b/plugin/lv.lproj/LicensingInfo.html @@ -0,0 +1,19 @@ +<style> + html{font-family:'Lucida Grande',arial;font-size:10px;cursor:default;color:#666;} + html,body {overflow: hidden;} + a,a:visited{color:#66f;} + a:hover{color:#22f} + h1{white-space:nowrap;} + ul{margin:0;padding:0;padding-left:16px;} + p{margin-bottom: 10px} + .choice{margin-top: 6px;} + .example{margin-left: 14px;margin-top: 2px; font-size: 9px;} + .note {font-size: 9px;} +</style> + +<p>Jūs varat izmantot šo licenci divos iespējamos veidos:</p> +<div class="choice">1. <strong>viens lietotājs iekš vairākiem datoriem</strong> <span class="note">(kamēr esat vienīgais lietotājs kas izmanto TotalFinder)</span></div> +<div class="example">Piemērs: galda dators un personīgais dators kuri abi ir Jūsu īpašumā</div> +<div class="choice">2. <strong>vairāki lietotāji iekš viena datora</strong></div> +<div class="example">Piemērs: mājas dators ko izmanto citi ģimenes locekļi</div> +<p class="note">Lai uzzinātu vairāk par licencēšanu apmeklējiet vietni <a href="https://totalfinder.binaryage.com/licensing">https://totalfinder.binaryage.com/licensing</a></p> diff --git a/plugin/lv.lproj/MenuItems.strings b/plugin/lv.lproj/MenuItems.strings new file mode 100644 index 0000000..e484e20 --- /dev/null +++ b/plugin/lv.lproj/MenuItems.strings @@ -0,0 +1,38 @@ +/* + +menu items are special - their keys are always prefixed with 'MenuItem:' (prefix) + +The goal is to distinguish them from normal string keys and +allow menu item localization to be independent from other strings. + +Without this (in English) some keys would be shared for menu items and preferences, +and this would make it uneasy to localize them in other languages properly +=> this will prevent it. + +*/ + +"MenuItem:Pin Visor" = "Pin Visor"; +"MenuItem:Close Tab" = "Close Tab"; +"MenuItem:New Native Tab" = "New Native Tab"; +"MenuItem:Close Native Tab" = "Close Native Tab"; +"MenuItem:Show Previous Native Tab" = "Show Previous Native Tab"; +"MenuItem:Show Next Native Tab" = "Show Next Native Tab"; +"MenuItem:New Tab" = "New Tab"; +"MenuItem:Reopen Closed Tab" = "Reopen Closed Tab"; +"MenuItem:Close Window" = "Close Window"; +"MenuItem:Toggle Dual Mode" = "Toggle Dual Mode"; +"MenuItem:Narrow Tabs Bar" = "Narrow Tabs Bar"; +"MenuItem:Select Previous Tab" = "Select Previous Tab"; +"MenuItem:Select Next Tab" = "Select Next Tab"; +"MenuItem:Switch Active Panel" = "Switch Active Panel"; +"MenuItem:Folders on Top" = "Folders on Top"; +"MenuItem:Show System Files" = "Show System Files"; +"MenuItem:Column View Auto Width" = "Column View Auto Width"; +"MenuItem:Dock Progress Bar" = "Dock Progress Bar"; +"MenuItem:Template" = "Template"; /* this is just for development - don't translate */ + +/* +note: These menu item localizations are taken from Finder's localization table: +Enter Full Screen +Exit Full Screen +*/ diff --git a/plugin/lv.lproj/NoDesktopDots.strings b/plugin/lv.lproj/NoDesktopDots.strings new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/plugin/lv.lproj/NoDesktopDots.strings @@ -0,0 +1 @@ + diff --git a/plugin/lv.lproj/PurchaseScreen.html b/plugin/lv.lproj/PurchaseScreen.html new file mode 100644 index 0000000..3d3d9ab --- /dev/null +++ b/plugin/lv.lproj/PurchaseScreen.html @@ -0,0 +1,17 @@ +<style> + html{font-family:'Lucida Grande',arial;font-size:12px;cursor:default;color:#666;} + html,body {overflow: hidden;} + a,a:visited{color:#66f;} + a:hover{color:#22f} + h1{white-space:nowrap;} + ul{margin:0;padding:0;padding-left:16px;} + p{margin-bottom: 20px} +</style> + +<p> +Papildus inforācija:<br/> +Mājaslapa: <a href="https://totalfinder.binaryage.com">https://totalfinder.binaryage.com</a><br/> +Dokumentācija: <a href="https://totalfinder.binaryage.com/about">https://totalfinder.binaryage.com/about</a><br/> +Autori: <a href="https://totalfinder.binaryage.com/credits">https://totalfinder.binaryage.com/credits</a><br/> +Atbalsts: <a href="https://discuss.binaryage.com">https://discuss.binaryage.com</a><br/> +</p> diff --git a/plugin/lv.lproj/SystemFiles.strings b/plugin/lv.lproj/SystemFiles.strings new file mode 100644 index 0000000..3e6494d --- /dev/null +++ b/plugin/lv.lproj/SystemFiles.strings @@ -0,0 +1 @@ +"Show System Files" = "Show System Files"; diff --git a/plugin/lv.lproj/Tabs.strings b/plugin/lv.lproj/Tabs.strings new file mode 100644 index 0000000..5b0df93 --- /dev/null +++ b/plugin/lv.lproj/Tabs.strings @@ -0,0 +1,16 @@ +"TotalFinder - unregistered version" = "TotalFinder - unregistered version"; +"TotalFinder - 1 day left - buy now!" = "TotalFinder - 1 day left - buy now!"; +"TotalFinder - 2 days left - buy now!" = "TotalFinder - 2 days left - buy now!"; +"TotalFinder - 3 days left - buy now!" = "TotalFinder - 3 days left - buy now!"; +"TotalFinder - 4 days left - buy now!" = "TotalFinder - 4 days left - buy now!"; +"TotalFinder - 5 days left - buy now!" = "TotalFinder - 5 days left - buy now!"; +"TotalFinder - %d days left - buy now!" = "TotalFinder - %d days left - buy now!"; +"Close Tab" = "Close Tab"; +"Toggle Dual Mode" = "Toggle Dual Mode"; + +"New Tab" = "New Tab"; /* the tooltip of the "plus button" in tabs bar */ +"Use narrow Tabs Bar" = "Use narrow Tabs Bar"; +"Open new tabs with previous location" = "Open new tabs with previous location"; + +/* preferences */ +"Freelance Windows" = "Freelance Windows"; diff --git a/plugin/lv.lproj/Template.strings b/plugin/lv.lproj/Template.strings new file mode 100644 index 0000000..d071801 --- /dev/null +++ b/plugin/lv.lproj/Template.strings @@ -0,0 +1,4 @@ +"Template" = "Template"; +"SAMPLE" = "SAMPLE"; +"Experimental" = "Experimental"; +"Enable Template" = "Enable Template"; diff --git a/plugin/lv.lproj/TotalFinder.strings b/plugin/lv.lproj/TotalFinder.strings new file mode 100644 index 0000000..0bac649 --- /dev/null +++ b/plugin/lv.lproj/TotalFinder.strings @@ -0,0 +1,87 @@ +/* preferences */ +"BASIC" = "BASIC"; +"SYSTEM" = "SYSTEM"; +"Menus" = "Menus"; +"Updates" = "Updates"; +"File Browser" = "File Browser"; +"Dock" = "Dock"; +"Sidebar" = "Sidebar"; + +/* TotalFinder Status Menu Item */ +"Check for Updates" = "Pārbaudīt programmas atjauninājumus"; +"Uninstall TotalFinder" = "Attinstalēt TotalFinder"; +"About TotalFinder" = "Part TotalFinder"; +"Restart Finder" = "Pārstartēt Finder"; +"Status Menu" = "Statusa Izvēlne"; + +/* Reset to Defaults Alert Box */ +"Reset" = "Reset"; +"Cancel" = "Atcelt"; +"Do you really want reset to defaults?" = "Vai Jūs patiešām vēlaties attiestatīt uz noklusētajām vērtībām?"; +"This will restore initial TotalFinder settings." = "Šī darbība atjaunos orģinālos TotalFinder iestatījumus."; + +/* MainMenu items */ +"TotalFinder" = "TotalFinder"; +"TotalFinder Preferences…" = "TotalFinder Iestatījumi…"; +"Visit Homepage…" = "Atvērt mājaslapu…"; + +/* registration */ +"Licensed to %@" = "Licencēts uz %@"; +"Change License" = "Mainīte licenci"; +"Unregistered version in trial mode" = "Bezmaksas programmas izmēģinājuma versija"; +"Register" = "Reģistrēt"; + +/* navigation bar */ +"About" = "Par"; + +/* tweaks page */ +"Reset TotalFinder to defaults" = "Attiestatīt TotalFinder uz noklusētajām vērtībām"; + +"Hide icon in Menu Bar" = "Paslēpt ikonu Izvēlnes škirtnē"; +"Keep original Dock icon" = "Paturēt orģinālo doka ikonun"; + +/* about page */ +"Check Now" = "Pārbaudīt"; +"Automatically check the website for updates" = "Automātiski pārbaudīt programmas atjauninājumos no mājaslapas"; +"Include pre-releases" = "Iekļaut programmas relīzes"; +"Participate in TotalFinder testing" = "Piedalīties TotalFinder testēšanā"; + +/* registration */ +"TotalFinder Registration" = "TotalFinder Reģistrācija"; +"Registration" = "Reģistrācija"; +"Please enter your license details from the email we have sent you:" = "Lūdzu ievadiet licences detaļas, kuras mēs Jums nosūtījām uz e-pastu:"; +"Buy TotalFinder Now" = "Iegādāties TotalFinder"; +"Thanks for registering!" = "Paldies par reģistrēšanos!"; +"This TotalFinder copy is licensed to:" = "Šī TotalFinder kopija ir licencēta uz:"; +"Close" = "Aizvērt"; +"Back" = "Atpakaļ"; +"Invalid license code" = "Nederīgs licences kods"; +"Please go back and try again." = "Lūdzu dodieties atpakaļ un mēģinēt vēlreiz."; +"To purchase a license for TotalFinder, please visit BinaryAge web store." = "Lūdzu apmeklējiet BinaryAge e-veikalu lai iegādātos TotalFinder licenci."; +"Thank you for using TotalFinder!" = "Paldies, ka izmantojāt TotalFinder!"; +"License Name" = "Licences vārds"; +"License Key" = "Licences atslēga"; + + +/* shortcuts subsystem */ +"Click to record new shortcut" = "Spiediet šeit, lai ierakstītu jaunu saīsni."; +"Delete shortcut" = "Dzēst saīsni"; +"OK" = "Labi"; +"Record Shortcut" = "Ierakstīt saīsni"; +"Space" = "Atstarpe"; +"The key combination %@ cannot be used" = "Šī %@ klaviatūras kombinācija nevar tikt izmantota"; +"This combination cannot be used because it is already used by a system-wide keyboard shortcut.\nIf you really want to use this key combination, most shortcuts can be changed in the Keyboard & Mouse panel in System Preferences." = "Šī klaviatūras saīsnes kombinācija nevar tikt izmantota, jo tā jau ir izmantota sistēmas klaviatūras saīsnē.\nJa Jūs tiešām vēlaties izmantot šo klaviatūras kombināciju tad vairumu saīsnes iespējams rediģēt Klaviatūras & Peles iestatījumu panelī zem Sistēmas iestatījumiem."; +"This shortcut cannot be used because it is already used by the menu item ‘%@’." = "Šīs saīsne nevar tikt izmantota, jo tā jau ir izmantota izvēlnes vienumām ‘%@’."; +"Type New Shortcut" = "Ievadīt jauno saīsni"; +"Type Shortcut" = "Ievadīt saīsni"; +"Use Old Shortcut" = "Izmantot veco saīsni"; +"Set it anyway" = "Iestatīt to vienalga"; + +/* tabs section */ +"Disable tabs completely" = "Pilnībā atspējot cilnes"; +"Do you really want to disable tabs?" = "Vai Jūs patiešām vēlaties atspējot cilnes?"; +"Do you really want to enable tabs?" = "Vai Jūs patiešām vēlaties ieslēgt cilnes?"; +"Tabs" = "Cilnes"; +"This option will effectively disable the tabs module in TotalFinder. In effect the dual mode and visor functionality will be disabled as well. This may be desired under Mavericks - use native Finder tabs exclusively while keeping benefits of other TotalFinder features.\n\nFor this operation Finder has to be restarted!\nNote: Prior restarting please finish all Finder tasks in progress (like copying or moving files)." = "Ši papildizvēle atspējos cilnes moduli TotalFinder programmā. Pilnīgam efektam paralēlāis režīms un visor režīms tiks atslēgts. Šī funkcionalitāte ir vēlame Mavericks operētājsistēmas versijā - izmantot noklusētās Finder programmas cilnes un saglabāt ieguvumus no pārējām TotalFinder iespējām.\n\nLai pabeigtu šo darbību Finder programma ir jāpārstartē!\nPiezīme: Pirms Finder programmas pārstartēšanas lūdzu pabeidziet visas uzsāktās operācijas (failu kopēšanas vai pārvietošanas darbības)."; +"This option will effectively enable the tabs module in TotalFinder.\n\nFor this operation Finder has to be restarted.\nNote: Prior restarting please finish all Finder tasks in progress (like copying or moving files)." = "Ši papildizvēle ieslēgs cilnes moduli TotalFinder programmā.\n\nLai pabeigtu šo darbību Finder programma ir jāparstartē.\nPiezīme: Pirms Finder programmas pārstartēšanas lūdzu pabeidziet visas uzsāktās operācijas (failu kopēšanas vai pārvietošanas darbības)."; +"This will effectively disable tabs, dual mode and visor. Finder restart is needed." = "Šī darbīiba atspējos cilnes, paralēlo režīmu un visor efektu. Finder pārstartēšana ir nepieciešama."; diff --git a/plugin/lv.lproj/Visor.strings b/plugin/lv.lproj/Visor.strings new file mode 100644 index 0000000..e16d40e --- /dev/null +++ b/plugin/lv.lproj/Visor.strings @@ -0,0 +1,19 @@ +"Pin Visor" = "Pin Visor"; +"Show Visor" = "Show Visor"; +"Hide Visor" = "Hide Visor"; + +"Visor" = "Visor"; +"a system-wide window sliding from the bottom on a hot-key" = "a system-wide window sliding from the bottom on a hot-key"; +"Visor Feature" = "Visor Feature"; +"Activation:" = "Activation:"; +"Show on all Spaces" = "Show on all Spaces"; +"Animation:" = "Animation:"; +"Control:" = "Control:"; +"Slide Window" = "Slide Window"; +"Fade Window" = "Fade Window"; +"Show on top of the Dock" = "Show on top of the Dock"; +"Free Form Window" = "Free Form Window"; +"Hide on ESC" = "Hide on ESC"; +"Screen:" = "Screen:"; +"Screen" = "Screen"; +"Screen with Mouse Cursor" = "Screen with Mouse Cursor"; diff --git a/uninstaller/lv.lproj/Localizable.strings b/uninstaller/lv.lproj/Localizable.strings new file mode 100644 index 0000000..28692ea --- /dev/null +++ b/uninstaller/lv.lproj/Localizable.strings @@ -0,0 +1,23 @@ +/* buttons */ +"Quit" = "Beigt"; +"Cancel" = "Atcelt"; +"Uninstall" = "Atinstalēt"; +"Details" = "Detaļas"; + +/* tooltips */ +"Show detailed transcript" = "Parādīt detalizētu norakstu"; + +/* main texts */ +"You are about uninstall *APP*" = "Jūs tūlīt atinstalēsiet programmu TotalFinder"; +"This program will uninstall all *APP* components from this computer." = "Šī programma atinstalēs visus TotalFinder programmas komponentus."; +"*APP* has been uninstalled" = "TotalFinder tika atinstalēts"; +"Thank you for trying *APP*." = "Paldies, ka pamēģinājāt TotalFinder."; +"*APP* uninstallation failed" = "Neizdevās atinstalēt TotalFinder"; +"The uninstall script encountered problems. Please see the details. Please report bugs to support@binaryage.com." = "Atinstalēšanas programmā radās kļūda. Lūdzu skatieties detaļas par kļūdu. Lūdzu ziņojiet par kļūdām uz e-pastu support@binaryage.com."; + +/* possible script messages in details section */ +"Uninstaller needs admin privileges to remove *APP* from your system." = "Atinstalēšanas programmai nepieciešamas administratīvā lietotāja tiesības, lai attinstalētu TotalFinder no Jūsu sistēmas."; +"Running uninstall script:\n" = "Atinstalēšanas programma darbojas:\n"; +"Uninstall script finished successfully.\n" = "Atinstalēšanas programma veiksmīgi beidza savu darbību.\n"; +"Uninstall script needs admin rights.\n" = "Attinstalēšanas programmai nepieciešamas administratīvā lietotāja tiesības.\n"; +"Uninstall script failed with error [%d].\n" = "Attinstalēšanas programma saskarās ar kļūdu [%d].\n";
binaryage/totalfinder-i18n
c650e4aab94f7090f94079b1d67bfd9922a154ee
convert pin button tiff images to png
diff --git a/plugin/PinIconOffActive.png b/plugin/PinIconOffActive.png new file mode 100644 index 0000000..f22dacb Binary files /dev/null and b/plugin/PinIconOffActive.png differ diff --git a/plugin/PinIconOffActive.tif b/plugin/PinIconOffActive.tif deleted file mode 100644 index 2a5cf70..0000000 Binary files a/plugin/PinIconOffActive.tif and /dev/null differ diff --git a/plugin/PinIconOffActive2.png b/plugin/PinIconOffActive2.png new file mode 100644 index 0000000..3554450 Binary files /dev/null and b/plugin/PinIconOffActive2.png differ diff --git a/plugin/PinIconOffActive2.tif b/plugin/PinIconOffActive2.tif deleted file mode 100644 index c4dfd0c..0000000 Binary files a/plugin/PinIconOffActive2.tif and /dev/null differ diff --git a/plugin/PinIconOffActive2@2x.png b/plugin/PinIconOffActive2@2x.png new file mode 100644 index 0000000..a899297 Binary files /dev/null and b/plugin/PinIconOffActive2@2x.png differ diff --git a/plugin/PinIconOffActive2@2x.tif b/plugin/PinIconOffActive2@2x.tif deleted file mode 100644 index c4dfd0c..0000000 Binary files a/plugin/PinIconOffActive2@2x.tif and /dev/null differ diff --git a/plugin/PinIconOffActive@2x.png b/plugin/PinIconOffActive@2x.png new file mode 100644 index 0000000..8356be2 Binary files /dev/null and b/plugin/PinIconOffActive@2x.png differ diff --git a/plugin/PinIconOffActive@2x.tif b/plugin/PinIconOffActive@2x.tif deleted file mode 100644 index 8bee26a..0000000 Binary files a/plugin/PinIconOffActive@2x.tif and /dev/null differ diff --git a/plugin/PinIconOffInactive.png b/plugin/PinIconOffInactive.png new file mode 100644 index 0000000..796f8a3 Binary files /dev/null and b/plugin/PinIconOffInactive.png differ diff --git a/plugin/PinIconOffInactive.tif b/plugin/PinIconOffInactive.tif deleted file mode 100644 index 9e64fc8..0000000 Binary files a/plugin/PinIconOffInactive.tif and /dev/null differ diff --git a/plugin/PinIconOffInactive2.png b/plugin/PinIconOffInactive2.png new file mode 100644 index 0000000..bc759c6 Binary files /dev/null and b/plugin/PinIconOffInactive2.png differ diff --git a/plugin/PinIconOffInactive2.tif b/plugin/PinIconOffInactive2.tif deleted file mode 100644 index 425e444..0000000 Binary files a/plugin/PinIconOffInactive2.tif and /dev/null differ diff --git a/plugin/PinIconOffInactive2@2x.png b/plugin/PinIconOffInactive2@2x.png new file mode 100644 index 0000000..83bc028 Binary files /dev/null and b/plugin/PinIconOffInactive2@2x.png differ diff --git a/plugin/PinIconOffInactive2@2x.tif b/plugin/PinIconOffInactive2@2x.tif deleted file mode 100644 index 0112f4a..0000000 Binary files a/plugin/PinIconOffInactive2@2x.tif and /dev/null differ diff --git a/plugin/PinIconOffInactive@2x.png b/plugin/PinIconOffInactive@2x.png new file mode 100644 index 0000000..6c72ece Binary files /dev/null and b/plugin/PinIconOffInactive@2x.png differ diff --git a/plugin/PinIconOffInactive@2x.tif b/plugin/PinIconOffInactive@2x.tif deleted file mode 100644 index 66dd3e3..0000000 Binary files a/plugin/PinIconOffInactive@2x.tif and /dev/null differ diff --git a/plugin/PinIconOnActive.png b/plugin/PinIconOnActive.png new file mode 100644 index 0000000..eced468 Binary files /dev/null and b/plugin/PinIconOnActive.png differ diff --git a/plugin/PinIconOnActive.tif b/plugin/PinIconOnActive.tif deleted file mode 100644 index 70c7add..0000000 Binary files a/plugin/PinIconOnActive.tif and /dev/null differ diff --git a/plugin/PinIconOnActive2.png b/plugin/PinIconOnActive2.png new file mode 100644 index 0000000..b3e9c25 Binary files /dev/null and b/plugin/PinIconOnActive2.png differ diff --git a/plugin/PinIconOnActive2.tif b/plugin/PinIconOnActive2.tif deleted file mode 100644 index 9462609..0000000 Binary files a/plugin/PinIconOnActive2.tif and /dev/null differ diff --git a/plugin/PinIconOnActive2@2x.png b/plugin/PinIconOnActive2@2x.png new file mode 100644 index 0000000..0ec8507 Binary files /dev/null and b/plugin/PinIconOnActive2@2x.png differ diff --git a/plugin/PinIconOnActive2@2x.tif b/plugin/PinIconOnActive2@2x.tif deleted file mode 100644 index 9462609..0000000 Binary files a/plugin/PinIconOnActive2@2x.tif and /dev/null differ diff --git a/plugin/PinIconOnActive@2x.png b/plugin/PinIconOnActive@2x.png new file mode 100644 index 0000000..ed6d3a6 Binary files /dev/null and b/plugin/PinIconOnActive@2x.png differ diff --git a/plugin/PinIconOnActive@2x.tif b/plugin/PinIconOnActive@2x.tif deleted file mode 100644 index 5f8137d..0000000 Binary files a/plugin/PinIconOnActive@2x.tif and /dev/null differ diff --git a/plugin/PinIconOnInactive.png b/plugin/PinIconOnInactive.png new file mode 100644 index 0000000..0d6683a Binary files /dev/null and b/plugin/PinIconOnInactive.png differ diff --git a/plugin/PinIconOnInactive.tif b/plugin/PinIconOnInactive.tif deleted file mode 100644 index 3cd5148..0000000 Binary files a/plugin/PinIconOnInactive.tif and /dev/null differ diff --git a/plugin/PinIconOnInactive2.png b/plugin/PinIconOnInactive2.png new file mode 100644 index 0000000..90d5a09 Binary files /dev/null and b/plugin/PinIconOnInactive2.png differ diff --git a/plugin/PinIconOnInactive2.tif b/plugin/PinIconOnInactive2.tif deleted file mode 100644 index 6128d65..0000000 Binary files a/plugin/PinIconOnInactive2.tif and /dev/null differ diff --git a/plugin/PinIconOnInactive2@2x.png b/plugin/PinIconOnInactive2@2x.png new file mode 100644 index 0000000..93e57d6 Binary files /dev/null and b/plugin/PinIconOnInactive2@2x.png differ diff --git a/plugin/PinIconOnInactive2@2x.tif b/plugin/PinIconOnInactive2@2x.tif deleted file mode 100644 index ab1346d..0000000 Binary files a/plugin/PinIconOnInactive2@2x.tif and /dev/null differ diff --git a/plugin/PinIconOnInactive@2x.png b/plugin/PinIconOnInactive@2x.png new file mode 100644 index 0000000..8d58488 Binary files /dev/null and b/plugin/PinIconOnInactive@2x.png differ diff --git a/plugin/PinIconOnInactive@2x.tif b/plugin/PinIconOnInactive@2x.tif deleted file mode 100644 index 9a7ad06..0000000 Binary files a/plugin/PinIconOnInactive@2x.tif and /dev/null differ
binaryage/totalfinder-i18n
a6abf3cd3f0955b4514bb39dbbe2505e9a001b63
Revert "uninstaller: remove TotalFinderFileProvider if possible"
diff --git a/uninstaller/uninstall.applescript b/uninstaller/uninstall.applescript index 0c9a3a0..625978c 100644 --- a/uninstaller/uninstall.applescript +++ b/uninstaller/uninstall.applescript @@ -1,159 +1,148 @@ on run set newline to ASCII character 10 set stdout to "" set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher was not running" & newline end try set stdout to stdout & " shutdown TotalFinder agent ..." & newline try do shell script "killall TotalFinder" with administrator privileges on error set stdout to stdout & " TotalFinder agent was not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" -- we created unnamed login item up to version 1.4.18 (TotalFinder.app is filename) if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if -- since 1.4.19 we are creating named login item "TotalFinder" if login item "TotalFinder" exists then delete login item "TotalFinder" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinder.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinder.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/system-osax" & newline set stdout to stdout & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinderSIP.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try - - try - do shell script "[ ! -e \"/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle\" ]" - on error - set stdout to stdout & newline - set stdout to stdout & "/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle was left behind." & newline - set stdout to stdout & "This location is protected by System Integrity Protection." & newline - set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline - set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline - set stdout to stdout & newline - end try set stdout to stdout & "TotalFinder uninstallation done." -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
binaryage/totalfinder-i18n
c15f27dff38934d05b2ccde2544813f44e55b45f
Revert "actually remove TotalFinderFileProvider.bundle in uninstallation script"
diff --git a/uninstaller/uninstall.applescript b/uninstaller/uninstall.applescript index 5a76915..0c9a3a0 100644 --- a/uninstaller/uninstall.applescript +++ b/uninstaller/uninstall.applescript @@ -1,163 +1,159 @@ on run set newline to ASCII character 10 set stdout to "" set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher was not running" & newline end try set stdout to stdout & " shutdown TotalFinder agent ..." & newline try do shell script "killall TotalFinder" with administrator privileges on error set stdout to stdout & " TotalFinder agent was not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" -- we created unnamed login item up to version 1.4.18 (TotalFinder.app is filename) if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if -- since 1.4.19 we are creating named login item "TotalFinder" if login item "TotalFinder" exists then delete login item "TotalFinder" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinder.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinder.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/system-osax" & newline set stdout to stdout & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinderSIP.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try - try - do shell script "sudo rm -rf \"/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle\"" with administrator privileges - end try - try do shell script "[ ! -e \"/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try set stdout to stdout & "TotalFinder uninstallation done." -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
binaryage/totalfinder-i18n
52d6247c71a9e6da6ae25083e20aab013ed1dfe3
actually remove TotalFinderFileProvider.bundle in uninstallation script
diff --git a/uninstaller/uninstall.applescript b/uninstaller/uninstall.applescript index 0c9a3a0..5a76915 100644 --- a/uninstaller/uninstall.applescript +++ b/uninstaller/uninstall.applescript @@ -1,159 +1,163 @@ on run set newline to ASCII character 10 set stdout to "" set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher was not running" & newline end try set stdout to stdout & " shutdown TotalFinder agent ..." & newline try do shell script "killall TotalFinder" with administrator privileges on error set stdout to stdout & " TotalFinder agent was not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" -- we created unnamed login item up to version 1.4.18 (TotalFinder.app is filename) if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if -- since 1.4.19 we are creating named login item "TotalFinder" if login item "TotalFinder" exists then delete login item "TotalFinder" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinder.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinder.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/system-osax" & newline set stdout to stdout & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinderSIP.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try + try + do shell script "sudo rm -rf \"/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle\"" with administrator privileges + end try + try do shell script "[ ! -e \"/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try set stdout to stdout & "TotalFinder uninstallation done." -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
binaryage/totalfinder-i18n
2904a72b52044c1eaa6ea7d673a914936a356cd3
uninstaller: remove TotalFinderFileProvider if possible
diff --git a/uninstaller/uninstall.applescript b/uninstaller/uninstall.applescript index 625978c..0c9a3a0 100644 --- a/uninstaller/uninstall.applescript +++ b/uninstaller/uninstall.applescript @@ -1,148 +1,159 @@ on run set newline to ASCII character 10 set stdout to "" set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher was not running" & newline end try set stdout to stdout & " shutdown TotalFinder agent ..." & newline try do shell script "killall TotalFinder" with administrator privileges on error set stdout to stdout & " TotalFinder agent was not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" -- we created unnamed login item up to version 1.4.18 (TotalFinder.app is filename) if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if -- since 1.4.19 we are creating named login item "TotalFinder" if login item "TotalFinder" exists then delete login item "TotalFinder" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinder.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinder.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/system-osax" & newline set stdout to stdout & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\"" with administrator privileges end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinderSIP.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try + + try + do shell script "[ ! -e \"/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle\" ]" + on error + set stdout to stdout & newline + set stdout to stdout & "/System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/TotalFinderFileProvider.bundle was left behind." & newline + set stdout to stdout & "This location is protected by System Integrity Protection." & newline + set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline + set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline + set stdout to stdout & newline + end try set stdout to stdout & "TotalFinder uninstallation done." -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
binaryage/totalfinder-i18n
02a4079cdead2a162df02f7d8d3a550441efca49
fix whitespace in uninstaller script
diff --git a/uninstaller/uninstall.applescript b/uninstaller/uninstall.applescript index 100493e..625978c 100644 --- a/uninstaller/uninstall.applescript +++ b/uninstaller/uninstall.applescript @@ -1,148 +1,148 @@ on run set newline to ASCII character 10 set stdout to "" set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher was not running" & newline end try set stdout to stdout & " shutdown TotalFinder agent ..." & newline try do shell script "killall TotalFinder" with administrator privileges on error set stdout to stdout & " TotalFinder agent was not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" -- we created unnamed login item up to version 1.4.18 (TotalFinder.app is filename) if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if -- since 1.4.19 we are creating named login item "TotalFinder" if login item "TotalFinder" exists then delete login item "TotalFinder" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges - end try + end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinder.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinder.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/system-osax" & newline set stdout to stdout & newline end try try do shell script "sudo rm -rf \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\"" with administrator privileges - end try + end try try do shell script "[ ! -e \"/System/Library/ScriptingAdditions/TotalFinderSIP.osax\" ]" on error set stdout to stdout & newline set stdout to stdout & "/System/Library/ScriptingAdditions/TotalFinderSIP.osax was left behind." & newline set stdout to stdout & "This location is protected by System Integrity Protection." & newline set stdout to stdout & "This folder is harmless. But you might want to boot into Recovery OS and remove it manually." & newline set stdout to stdout & "More details: https://totalfinder.binaryage.com/sip" & newline set stdout to stdout & newline end try set stdout to stdout & "TotalFinder uninstallation done." -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
binaryage/totalfinder-i18n
200a08c74531db34f0aeee983f2fb6a8551b41b9
add dark mode versions of tab icons
diff --git a/plugin/newtab_hover_dark.png b/plugin/newtab_hover_dark.png new file mode 100644 index 0000000..4504847 Binary files /dev/null and b/plugin/newtab_hover_dark.png differ diff --git a/plugin/newtab_hover_dark@2x.png b/plugin/newtab_hover_dark@2x.png new file mode 100644 index 0000000..939a8e1 Binary files /dev/null and b/plugin/newtab_hover_dark@2x.png differ diff --git a/plugin/newtab_normal_dark.png b/plugin/newtab_normal_dark.png new file mode 100644 index 0000000..0b46046 Binary files /dev/null and b/plugin/newtab_normal_dark.png differ diff --git a/plugin/newtab_normal_dark@2x.png b/plugin/newtab_normal_dark@2x.png new file mode 100644 index 0000000..4c89689 Binary files /dev/null and b/plugin/newtab_normal_dark@2x.png differ diff --git a/plugin/newtab_pressed_dark.png b/plugin/newtab_pressed_dark.png new file mode 100644 index 0000000..bfb8725 Binary files /dev/null and b/plugin/newtab_pressed_dark.png differ diff --git a/plugin/newtab_pressed_dark@2x.png b/plugin/newtab_pressed_dark@2x.png new file mode 100644 index 0000000..036c37b Binary files /dev/null and b/plugin/newtab_pressed_dark@2x.png differ diff --git a/plugin/tab_close_hover_dark.png b/plugin/tab_close_hover_dark.png new file mode 100644 index 0000000..3b79874 Binary files /dev/null and b/plugin/tab_close_hover_dark.png differ diff --git a/plugin/tab_close_hover_dark@2x.png b/plugin/tab_close_hover_dark@2x.png new file mode 100644 index 0000000..761f0e6 Binary files /dev/null and b/plugin/tab_close_hover_dark@2x.png differ diff --git a/plugin/tab_close_normal_dark.png b/plugin/tab_close_normal_dark.png new file mode 100644 index 0000000..ccf2e28 Binary files /dev/null and b/plugin/tab_close_normal_dark.png differ diff --git a/plugin/tab_close_normal_dark@2x.png b/plugin/tab_close_normal_dark@2x.png new file mode 100644 index 0000000..0138987 Binary files /dev/null and b/plugin/tab_close_normal_dark@2x.png differ diff --git a/plugin/tab_close_pressed_dark.png b/plugin/tab_close_pressed_dark.png new file mode 100644 index 0000000..2a931e7 Binary files /dev/null and b/plugin/tab_close_pressed_dark.png differ diff --git a/plugin/tab_close_pressed_dark@2x.png b/plugin/tab_close_pressed_dark@2x.png new file mode 100644 index 0000000..46693dc Binary files /dev/null and b/plugin/tab_close_pressed_dark@2x.png differ
binaryage/totalfinder-i18n
c5a025149f0c8ad61d38d0ccaa32ddba0d8a2b9b
refer to https://totalfinder.binaryage.com/sip
diff --git a/installer/en.lproj/welcome.rtf b/installer/en.lproj/welcome.rtf index ca0a1d7..f348aa9 100644 --- a/installer/en.lproj/welcome.rtf +++ b/installer/en.lproj/welcome.rtf @@ -1,34 +1,34 @@ {\rtf1\ansi\ansicpg1252\cocoartf1561\cocoasubrtf600 \cocoascreenfonts1{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;} {\colortbl;\red255\green255\blue255;\red255\green0\blue0;\red158\green0\blue6;} {\*\expandedcolortbl;;\csgenericrgb\c100000\c0\c0;\csgenericrgb\c61961\c0\c2353;} \paperw11900\paperh16840\margl1440\margr1440\vieww16580\viewh16600\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \f0\fs24 \cf0 This installer will install {\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com"}}{\fldrslt \b TotalFinder}} on your computer.\ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 {\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/about"}}{\fldrslt \cf0 https://totalfinder.binaryage.com/about}}\ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \cf2 \ Please finish all background jobs like copying or moving files.\cf3 \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \cf0 Finder will be restarted during the installation.\ \ Prior to buying you have 14 days to evaluate the product. \ For more info on licensing please visit:\ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 {\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/licensing"}}{\fldrslt \cf0 https://totalfinder.binaryage.com/licensing}}\ \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \b\fs28 \cf0 A note about System Integrity Protection (SIP) \b0\fs24 \ \ SIP is a security subsystem introduced in macOS 10.11 (El Capitan).\ Unfortunately it prevents TotalFinder from altering Finder.\ \ The only known workaround is to disable SIP.\ \ Please read more about TotalFinder and SIP:\ -{\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/system-integrity-protection"}}{\fldrslt https://totalfinder.binaryage.com/sip-mojave}}} \ No newline at end of file +{\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/sip"}}{\fldrslt https://totalfinder.binaryage.com/sip}}} \ No newline at end of file diff --git a/installer/readme.html b/installer/readme.html index 478e8f1..8712951 100644 --- a/installer/readme.html +++ b/installer/readme.html @@ -1,351 +1,351 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>TotalFinder from BinaryAge</title> <style type="text/css"> /* ----------------------------------------------------------------------- Blueprint CSS Framework 0.9 http://blueprintcss.org * Copyright (c) 2007-Present. See LICENSE for more info. * See README for instructions on how to use Blueprint. * For credits and origins, see AUTHORS. * This is a compressed file. See the sources in the 'src' directory. ----------------------------------------------------------------------- */ /* reset.css */ html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, dialog, figure, footer, header, hgroup, nav, section {margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;} article, aside, dialog, figure, footer, header, hgroup, nav, section {display:block;} body {line-height:1.5;} table {border-collapse:separate;border-spacing:0;} caption, th, td {text-align:left;font-weight:normal;} table, td, th {vertical-align:middle;} blockquote:before, blockquote:after, q:before, q:after {content:"";} blockquote, q {quotes:"" "";} a img {border:none;} /* typography.css */ html {font-size:100.01%;} h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111;} h1 {font-size:3em;line-height:1;margin-bottom:0.5em;} h2 {font-size:2em;margin-bottom:0.75em;} h3 {font-size:1.5em;line-height:1;margin-bottom:1em;} h4 {font-size:1.2em;line-height:1.25;margin-bottom:1.25em;} h5 {font-size:1em;font-weight:bold;margin-bottom:1.5em;} h6 {font-size:1em;font-weight:bold;} h1 img, h2 img, h3 img, h4 img, h5 img, h6 img {margin:0;} p {margin:0 0 1.5em;} p img.left {float:left;margin:1.5em 1.5em 1.5em 0;padding:0;} p img.right {float:right;margin:1.5em 0 1.5em 1.5em;} a:focus, a:hover {color:#000;} a {color:#009;text-decoration:underline;} blockquote {margin:1.5em;color:#666;font-style:italic;} strong {font-weight:bold;} em, dfn {font-style:italic;} dfn {font-weight:bold;} sup, sub {line-height:0;} abbr, acronym {border-bottom:1px dotted #666;} address {margin:0 0 1.5em;font-style:italic;} del {color:#666;} pre {margin:1.5em 0;white-space:pre;} pre, code, tt {font:1em 'andale mono', 'lucida console', monospace;line-height:1.5;} li ul, li ol {margin:0;} ul, ol {margin:0 1.5em 1.5em 0;padding-left:3.333em;} ul {list-style-type:disc;} ol {list-style-type:decimal;} dl {margin:0 0 1.5em 0;} dl dt {font-weight:bold;} dd {margin-left:1.5em;} table {margin-bottom:1.4em;width:100%;} th {font-weight:bold;} thead th {background:#c3d9ff;} th, td, caption {padding:4px 10px 4px 5px;} tr.even td {background:#e5ecf9;} tfoot {font-style:italic;} caption {background:#eee;} .small {font-size:.8em;margin-bottom:1.875em;line-height:1.875em;} .large {font-size:1.2em;line-height:2.5em;margin-bottom:1.25em;} .hide {display:none;} .quiet {color:#666;} .loud {color:#000;} .highlight {background:#ff0;} .added {background:#060;color:#fff;} .removed {background:#900;color:#fff;} .first {margin-left:0;padding-left:0;} .last {margin-right:0;padding-right:0;} .top {margin-top:0;padding-top:0;} .bottom {margin-bottom:0;padding-bottom:0;} /* forms.css */ label {font-weight:bold;} fieldset {padding:1.4em;margin:0 0 1.5em 0;border:1px solid #ccc;} legend {font-weight:bold;font-size:1.2em;} input[type=text], input[type=password], input.text, input.title, textarea, select {background-color:#fff;border:1px solid #bbb;} input[type=text]:focus, input[type=password]:focus, input.text:focus, input.title:focus, textarea:focus, select:focus {border-color:#666;} input[type=text], input[type=password], input.text, input.title, textarea, select {margin:0.5em 0;} input.text, input.title {width:300px;padding:5px;} input.title {font-size:1.5em;} textarea {width:390px;height:250px;padding:5px;} input[type=checkbox], input[type=radio], input.checkbox, input.radio {position:relative;top:.25em;} form.inline {line-height:3;} form.inline p {margin-bottom:0;} .error, .notice, .success {padding:.8em;margin-bottom:1em;border:2px solid #ddd;} .error {background:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;} .notice {background:#FFF6BF;color:#514721;border-color:#FFD324;} .success {background:#E6EFC2;color:#264409;border-color:#C6D880;} .error a {color:#8a1f11;} .notice a {color:#514721;} .success a {color:#264409;} /* grid.css */ .container {width:950px;margin:0 auto;} .showgrid {background:url(/shared/img/grid.png);} .column, .span-1, .span-2, .span-3, .span-4, .span-5, .span-6, .span-7, .span-8, .span-9, .span-10, .span-11, .span-12, .span-13, .span-14, .span-15, .span-16, .span-17, .span-18, .span-19, .span-20, .span-21, .span-22, .span-23, .span-24 {float:left;margin-right:10px;} .last {margin-right:0;} .span-1 {width:30px;} .span-2 {width:70px;} .span-3 {width:110px;} .span-4 {width:150px;} .span-5 {width:190px;} .span-6 {width:230px;} .span-7 {width:270px;} .span-8 {width:310px;} .span-9 {width:350px;} .span-10 {width:390px;} .span-11 {width:430px;} .span-12 {width:470px;} .span-13 {width:510px;} .span-14 {width:550px;} .span-15 {width:590px;} .span-16 {width:630px;} .span-17 {width:670px;} .span-18 {width:710px;} .span-19 {width:750px;} .span-20 {width:790px;} .span-21 {width:830px;} .span-22 {width:870px;} .span-23 {width:910px;} .span-24 {width:950px;margin-right:0;} input.span-1, textarea.span-1, input.span-2, textarea.span-2, input.span-3, textarea.span-3, input.span-4, textarea.span-4, input.span-5, textarea.span-5, input.span-6, textarea.span-6, input.span-7, textarea.span-7, input.span-8, textarea.span-8, input.span-9, textarea.span-9, input.span-10, textarea.span-10, input.span-11, textarea.span-11, input.span-12, textarea.span-12, input.span-13, textarea.span-13, input.span-14, textarea.span-14, input.span-15, textarea.span-15, input.span-16, textarea.span-16, input.span-17, textarea.span-17, input.span-18, textarea.span-18, input.span-19, textarea.span-19, input.span-20, textarea.span-20, input.span-21, textarea.span-21, input.span-22, textarea.span-22, input.span-23, textarea.span-23, input.span-24, textarea.span-24 {border-left-width:1px!important;border-right-width:1px!important;padding-left:5px!important;padding-right:5px!important;} input.span-1, textarea.span-1 {width:18px!important;} input.span-2, textarea.span-2 {width:58px!important;} input.span-3, textarea.span-3 {width:98px!important;} input.span-4, textarea.span-4 {width:138px!important;} input.span-5, textarea.span-5 {width:178px!important;} input.span-6, textarea.span-6 {width:218px!important;} input.span-7, textarea.span-7 {width:258px!important;} input.span-8, textarea.span-8 {width:298px!important;} input.span-9, textarea.span-9 {width:338px!important;} input.span-10, textarea.span-10 {width:378px!important;} input.span-11, textarea.span-11 {width:418px!important;} input.span-12, textarea.span-12 {width:458px!important;} input.span-13, textarea.span-13 {width:498px!important;} input.span-14, textarea.span-14 {width:538px!important;} input.span-15, textarea.span-15 {width:578px!important;} input.span-16, textarea.span-16 {width:618px!important;} input.span-17, textarea.span-17 {width:658px!important;} input.span-18, textarea.span-18 {width:698px!important;} input.span-19, textarea.span-19 {width:738px!important;} input.span-20, textarea.span-20 {width:778px!important;} input.span-21, textarea.span-21 {width:818px!important;} input.span-22, textarea.span-22 {width:858px!important;} input.span-23, textarea.span-23 {width:898px!important;} input.span-24, textarea.span-24 {width:938px!important;} .append-1 {padding-right:40px;} .append-2 {padding-right:80px;} .append-3 {padding-right:120px;} .append-4 {padding-right:160px;} .append-5 {padding-right:200px;} .append-6 {padding-right:240px;} .append-7 {padding-right:280px;} .append-8 {padding-right:320px;} .append-9 {padding-right:360px;} .append-10 {padding-right:400px;} .append-11 {padding-right:440px;} .append-12 {padding-right:480px;} .append-13 {padding-right:520px;} .append-14 {padding-right:560px;} .append-15 {padding-right:600px;} .append-16 {padding-right:640px;} .append-17 {padding-right:680px;} .append-18 {padding-right:720px;} .append-19 {padding-right:760px;} .append-20 {padding-right:800px;} .append-21 {padding-right:840px;} .append-22 {padding-right:880px;} .append-23 {padding-right:920px;} .prepend-1 {padding-left:40px;} .prepend-2 {padding-left:80px;} .prepend-3 {padding-left:120px;} .prepend-4 {padding-left:160px;} .prepend-5 {padding-left:200px;} .prepend-6 {padding-left:240px;} .prepend-7 {padding-left:280px;} .prepend-8 {padding-left:320px;} .prepend-9 {padding-left:360px;} .prepend-10 {padding-left:400px;} .prepend-11 {padding-left:440px;} .prepend-12 {padding-left:480px;} .prepend-13 {padding-left:520px;} .prepend-14 {padding-left:560px;} .prepend-15 {padding-left:600px;} .prepend-16 {padding-left:640px;} .prepend-17 {padding-left:680px;} .prepend-18 {padding-left:720px;} .prepend-19 {padding-left:760px;} .prepend-20 {padding-left:800px;} .prepend-21 {padding-left:840px;} .prepend-22 {padding-left:880px;} .prepend-23 {padding-left:920px;} .border {padding-right:4px;margin-right:5px;border-right:1px solid #eee;} .colborder {padding-right:24px;margin-right:25px;border-right:1px solid #eee;} .pull-1 {margin-left:-40px;} .pull-2 {margin-left:-80px;} .pull-3 {margin-left:-120px;} .pull-4 {margin-left:-160px;} .pull-5 {margin-left:-200px;} .pull-6 {margin-left:-240px;} .pull-7 {margin-left:-280px;} .pull-8 {margin-left:-320px;} .pull-9 {margin-left:-360px;} .pull-10 {margin-left:-400px;} .pull-11 {margin-left:-440px;} .pull-12 {margin-left:-480px;} .pull-13 {margin-left:-520px;} .pull-14 {margin-left:-560px;} .pull-15 {margin-left:-600px;} .pull-16 {margin-left:-640px;} .pull-17 {margin-left:-680px;} .pull-18 {margin-left:-720px;} .pull-19 {margin-left:-760px;} .pull-20 {margin-left:-800px;} .pull-21 {margin-left:-840px;} .pull-22 {margin-left:-880px;} .pull-23 {margin-left:-920px;} .pull-24 {margin-left:-960px;} .pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float:left;position:relative;} .push-1 {margin:0 -40px 1.5em 40px;} .push-2 {margin:0 -80px 1.5em 80px;} .push-3 {margin:0 -120px 1.5em 120px;} .push-4 {margin:0 -160px 1.5em 160px;} .push-5 {margin:0 -200px 1.5em 200px;} .push-6 {margin:0 -240px 1.5em 240px;} .push-7 {margin:0 -280px 1.5em 280px;} .push-8 {margin:0 -320px 1.5em 320px;} .push-9 {margin:0 -360px 1.5em 360px;} .push-10 {margin:0 -400px 1.5em 400px;} .push-11 {margin:0 -440px 1.5em 440px;} .push-12 {margin:0 -480px 1.5em 480px;} .push-13 {margin:0 -520px 1.5em 520px;} .push-14 {margin:0 -560px 1.5em 560px;} .push-15 {margin:0 -600px 1.5em 600px;} .push-16 {margin:0 -640px 1.5em 640px;} .push-17 {margin:0 -680px 1.5em 680px;} .push-18 {margin:0 -720px 1.5em 720px;} .push-19 {margin:0 -760px 1.5em 760px;} .push-20 {margin:0 -800px 1.5em 800px;} .push-21 {margin:0 -840px 1.5em 840px;} .push-22 {margin:0 -880px 1.5em 880px;} .push-23 {margin:0 -920px 1.5em 920px;} .push-24 {margin:0 -960px 1.5em 960px;} .push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float:right;position:relative;} .prepend-top {margin-top:1.5em;} .append-bottom {margin-bottom:1.5em;} .box {padding:1.5em;margin-bottom:1.5em;background:#E5ECF9;} hr {background:#ddd;color:#ddd;clear:both;float:none;width:100%;height:.1em;margin:0 0 1.45em;border:none;} hr.space {background:#fff;color:#fff;visibility:hidden;} .clearfix:after, .container:after {content:"\0020";display:block;height:0;clear:both;visibility:hidden;overflow:hidden;} .clearfix, .container {display:block;} .clear {clear:both;} /* -----------------------------------------------------------------------*/ html { font: 11pt "Play", "Lucida Grande","Lucida Sans Unicode","Lucida Sans",Verdana,sans-serif; } .wrapper { width: 824px; margin: auto; margin-top: 60px; } h1 { font-size: 14px; font-weight: bold; margin:0; } h1 a { font-size: 50px; font-weight: bold; } h3 { font-size: 20px; font-weight: bold; } #sub { font-size: 20px; margin: 0; } a { color: #3A6394; font-weight: bold; text-decoration: none; } a:hover { color: #1C75DB; } .center { text-align: center; } .small { font-size: 14pt !important; weight: normal; } img { margin-top: 30px; margin-bottom: 40px; -webkit-box-shadow:0 0 20px #666; box-shadow:0 0 20px #666; -webkit-border-radius:4px; border-radius:4px; width: 80%; } .warn { color: red; } .warn a { color: red; } </style> <link href='http://fonts.googleapis.com/css?family=Play:400,700&v2' rel='stylesheet' type='text/css'> </head> <body> <div class="wrapper"> <div class="center"><h1><a href="https://totalfinder.binaryage.com">TotalFinder</a></h1></div> <br/> <div class="center"><p>TotalFinder is a plugin for Finder.app which adds dual panel, keyboard shortcuts, colored labels and other useful features.</p></div> <div class="center"><img src="intro.png" alt="TotalFinder"></div> <div class="center"> <p>Compatible with macOS 10.11 (El Capitan) - 10.14 (Mojave).</p> - <p class="warn">Since macOS 10.11 (El Capitan) requires <a href="https://totalfinder.binaryage.com/sip-mojave">a system tweak</a>.</p> + <p class="warn">Since macOS 10.11 (El Capitan) requires <a href="https://totalfinder.binaryage.com/sip">a system tweak</a>.</p> <br> <p>The documentation is located at<br><a href="https://totalfinder.binaryage.com/about">https://totalfinder.binaryage.com/about</a></p> <p>For support please visit<br><a href="https://discuss.binaryage.com">https://discuss.binaryage.com</a></p> </div> </div> </body> </html> \ No newline at end of file diff --git a/installer/readme.pdf b/installer/readme.pdf index 70b3f1f..879be89 100644 Binary files a/installer/readme.pdf and b/installer/readme.pdf differ