code
stringlengths
4
1.01M
language
stringclasses
2 values
/* * 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 * * https://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.avro; /** Thrown for errors building schemas. */ public class SchemaBuilderException extends AvroRuntimeException { public SchemaBuilderException(Throwable cause) { super(cause); } public SchemaBuilderException(String message) { super(message); } }
Java
/* * 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.beam.fn.harness.state; import static org.junit.Assert.assertArrayEquals; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.protobuf.ByteString; import java.io.IOException; import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link MultimapSideInput}. */ @RunWith(JUnit4.class) public class MultimapSideInputTest { @Test public void testGet() throws Exception { FakeBeamFnStateClient fakeBeamFnStateClient = new FakeBeamFnStateClient(ImmutableMap.of( key("A"), encode("A1", "A2", "A3"), key("B"), encode("B1", "B2"))); MultimapSideInput<String, String> multimapSideInput = new MultimapSideInput<>( fakeBeamFnStateClient, "instructionId", "ptransformId", "sideInputId", ByteString.copyFromUtf8("encodedWindow"), StringUtf8Coder.of(), StringUtf8Coder.of()); assertArrayEquals(new String[]{ "A1", "A2", "A3" }, Iterables.toArray(multimapSideInput.get("A"), String.class)); assertArrayEquals(new String[]{ "B1", "B2" }, Iterables.toArray(multimapSideInput.get("B"), String.class)); assertArrayEquals(new String[]{ }, Iterables.toArray(multimapSideInput.get("unknown"), String.class)); } private StateKey key(String id) throws IOException { return StateKey.newBuilder().setMultimapSideInput( StateKey.MultimapSideInput.newBuilder() .setPtransformId("ptransformId") .setSideInputId("sideInputId") .setWindow(ByteString.copyFromUtf8("encodedWindow")) .setKey(encode(id))).build(); } private ByteString encode(String ... values) throws IOException { ByteString.Output out = ByteString.newOutput(); for (String value : values) { StringUtf8Coder.of().encode(value, out); } return out.toByteString(); } }
Java
"use strict"; describe("Brisket server", function() { var Brisket = require("../../lib/brisket"); var MockBrisketApp = require("../mock/MockBrisketApp"); var nock = require("nock"); var supertest = require("supertest"); var brisketServer; beforeEach(function() { MockBrisketApp.initialize(); nock("http://api.example.com") .get("/fetch200") .reply(200, { ok: true }) .get("/fetch404") .reply(404, { ok: false }) .get("/fetch500") .reply(500, { ok: false }) .get("/fetch410") .reply(410, { ok: false }); brisketServer = Brisket.createServer({ apis: { "api": { host: "http://api.example.com", proxy: null } } }); }); afterEach(function() { MockBrisketApp.cleanup(); nock.cleanAll(); }); it("returns 200 when route is working", function(done) { supertest(brisketServer) .get("/working") .expect(200, mocha(done)); }); it("returns 500 when route is failing", function(done) { supertest(brisketServer) .get("/failing") .expect(500, mocha(done)); }); it("returns 302 when route is redirecting", function(done) { supertest(brisketServer) .get("/redirecting") .expect(302, mocha(done)); }); it("returns status from route when route sets status", function(done) { supertest(brisketServer) .get("/setsStatus") .expect(206, mocha(done)); }); it("returns 200 when data fetch is 200 AND route code doesn't error", function(done) { supertest(brisketServer) .get("/fetch200") .expect(200, mocha(done)); }); it("returns 500 when data fetch is 200 BUT route code errors", function(done) { supertest(brisketServer) .get("/fetch200ButRouteFails") .expect(500, mocha(done)); }); it("returns 302 when data fetch is 200 BUT route code redirects", function(done) { supertest(brisketServer) .get("/fetch200ButRouteRedirects") .expect(302, mocha(done)); }); it("returns status from route when data fetch is 200 BUT route sets status", function(done) { supertest(brisketServer) .get("/fetch200ButRouteSetsStatus") .expect(206, mocha(done)); }); it("returns 404 when route does NOT exist", function(done) { supertest(brisketServer) .get("/doesntexist") .expect(404, mocha(done)); }); it("returns 404 when data fetch is 404", function(done) { supertest(brisketServer) .get("/fetch404") .expect(404, mocha(done)); }); it("returns 500 when data fetch is 500", function(done) { supertest(brisketServer) .get("/fetch500") .expect(500, mocha(done)); }); it("returns 500 when data fetch is unexpected error code", function(done) { supertest(brisketServer) .get("/fetch410") .expect(500, mocha(done)); }); function mocha(done) { return function(err) { if (err) { done.fail(err); } else { done(); } }; } });
Java
/** * @projectDescription The SDX controller library for the PatientRecordSet data-type. * @namespace i2b2.sdx.TypeControllers.ENS * @inherits i2b2.sdx.TypeControllers * @author Mike Mendis * @version 1.6 * @see i2b2.sdx * ---------------------------------------------------------------------------------------- */ console.group('Load & Execute component file: CRC > SDX > Encounter Record Set'); console.time('execute time'); i2b2.sdx.TypeControllers.ENS = {}; i2b2.sdx.TypeControllers.ENS.model = {}; // ********************************************************************************* // ENCAPSULATE DATA // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.getEncapsulateInfo = function() { // this function returns the encapsulation head information return {sdxType: 'ENS', sdxKeyName: 'result_instance_id', sdxControlCell:'CRC', sdxDisplayNameKey: 'title'}; } i2b2.sdx.TypeControllers.ENS.SaveToDataModel = function(sdxData, sdxParentNode) { // save to CRC data model if (!sdxParentNode) { return false; } var qm_id = sdxData.sdxInfo.sdxKeyValue; var qm_hash = i2b2.sdx.Master._KeyHash(qm_id); // class for all SDX communications function i2b2_SDX_Encapsulation_EXTENDED() {} // create an instance and populate with info var t = new i2b2_SDX_Encapsulation_EXTENDED(); t.origData = Object.clone(sdxData.origData); t.sdxInfo = Object.clone(sdxData.sdxInfo); t.parent = sdxParentNode; t.children = new Hash(); t.children.loaded = false; // add to hash sdxParentNode.children.set(qm_hash, t); // TODO: send data update signal (use JOINING-MUTEX or AGGREGATING-MUTEX to avoid rapid fire of event!) return t; } i2b2.sdx.TypeControllers.ENS.LoadFromDataModel = function(key_value) {} i2b2.sdx.TypeControllers.ENS.ClearAllFromDataModel= function(sdxOptionalParent) { if (sdxOptionalParent) { try { var findFunc = function(item_rec) { // this function expects the second argument to be the target node's key value var hash_key = item_rec[0]; var QM_rec = item_rec[1]; if (QM_rec.sdxInfo.sdxKeyValue == this.strip()) { return true; } } var dm_loc = 'i2b2.CRC.model.QueryMasters.'+i2b2.sdx.Master._KeyHash(sdxOptionalParent.sdxInfo.sdxKeyValue); var targets = i2b2.CRC.model.QueryMasters.findAll(findFunc, sdxOptionalParent.sdxInfo.sdxKeyValue); for (var i=0; i < targets.length; i++) { var t = parent_QM[i].value; t.children = new Hash(); } } catch(e) { console.error('Could not clear children of given parent node!'); } } else { var dm_loc = 'i2b2.CRC.model.QueryMasters'; i2b2.CRC.model.QueryMasters.each(function(item_rec) { try { item_rec[1].children = new Hash(); } catch(e) { console.error('Could not clear children of all QueryMasters'); } }); } // TODO: send data update signal (use JOINING-MUTEX or AGGREGATING-MUTEX to avoid rapid fire of event!) // updated dm_loc of the data model return true; } // ********************************************************************************* // GENERATE HTML (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.RenderHTML= function(sdxData, options, targetDiv) { // OPTIONS: // title: string // showchildren: true | false // cssClass: string // icon: [data object] // icon: (filename of img, appended to i2b2_root+cellDir + '/assets') // iconExp: (filename of img, appended to i2b2_root+cellDir + '/assets') // dragdrop: string (function name) // context: string // click: string // dblclick: string if (Object.isUndefined(options)) { options = {}; } var render = {html: retHtml, htmlID: id}; var conceptId = sdxData.name; var id = "CRC_ID-" + i2b2.GUID(); // process drag drop controllers if (!Object.isUndefined(options.dragdrop)) { // NOTE TO SELF: should attachment of node dragdrop controller be handled by the SDX system as well? // This would ensure removal of the onmouseover call in a cross-browser way var sDD = ' onmouseover="' + options.dragdrop + '(\''+ targetDiv.id +'\',\'' + id + '\')" '; } else { var sDD = ''; } if (Object.isUndefined(options.cssClass)) { options.cssClass = 'sdxDefaultPRS';} // user can override bCanExp = true; if (Object.isBoolean(options.showchildren)) { bCanExp = options.showchildren; } render.canExpand = bCanExp; render.iconType = "PRS"; if (!Object.isUndefined(options.icon)) { render.icon = i2b2.hive.cfg.urlFramework + 'cells/CRC/assets/'+ options.icon } if (!Object.isUndefined(options.iconExp)) { render.iconExp = i2b2.hive.cfg.urlFramework + 'cells/CRC/assets/'+ options.iconExp } // in cases of one set icon, copy valid icon to the missing icon if (Object.isUndefined(render.icon) && !Object.isUndefined(render.iconExp)) { render.icon = render.iconExp; } if (!Object.isUndefined(render.icon) && Object.isUndefined(render.iconExp)) { render.iconExp = render.icon; } // handle the event controllers var sMainEvents = sDD; var sImgEvents = sDD; // **** Render the HTML *** var retHtml = '<DIV id="' + id + '" ' + sMainEvents + ' style="white-space:nowrap;cursor:pointer;">'; retHtml += '<DIV '; if (Object.isString(options.cssClass)) { retHtml += ' class="'+options.cssClass+'" '; } else { retHtml += ' class= "sdxDefaultPRS" '; } retHtml += sImgEvents; retHtml += '>'; retHtml += '<IMG src="'+render.icon+'"/> '; if (!Object.isUndefined(options.title)) { retHtml += options.title; } else { console.warn('[SDX RenderHTML] no title was given in the creation options for an CRC > ENS node!'); retHtml += ' PRS '+id; } retHtml += '</DIV></DIV>'; render.html = retHtml; render.htmlID = id; var retObj = {}; Object.extend(retObj, sdxData); retObj.renderData = render; return retObj; } // ********************************************************************************* // HANDLE HOVER OVER TARGET ENTRY (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.onHoverOver = function(e, id, ddProxy) { var el = $(id); if (el) { Element.addClassName(el,'ddPRSTarget'); } } // ********************************************************************************* // HANDLE HOVER OVER TARGET EXIT (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.onHoverOut = function(e, id, ddProxy) { var el = $(id); if (el) { Element.removeClassName(el,'ddPRSTarget'); } } // ********************************************************************************* // ADD DATA TO TREENODE (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.AppendTreeNode = function(yuiTree, yuiRootNode, sdxDataPack, callbackLoader) { var myobj = { html: sdxDataPack.renderData.html, nodeid: sdxDataPack.renderData.htmlID} var tmpNode = new YAHOO.widget.HTMLNode(myobj, yuiRootNode, false, true); if (sdxDataPack.renderData.canExpand && !Object.isUndefined(callbackLoader)) { // add the callback to load child nodes sdxDataPack.sdxInfo.sdxLoadChildren = callbackLoader; } tmpNode.data.i2b2_SDX= sdxDataPack; tmpNode.toggle = function() { if (!this.tree.locked && ( this.hasChildren(true) ) ) { var data = this.data.i2b2_SDX.renderData; var img = this.getContentEl(); img = Element.select(img,'img')[0]; if (this.expanded) { img.src = data.icon; this.collapse(); } else { img.src = data.iconExp; this.expand(); } } }; if (!sdxDataPack.renderData.canExpand) { tmpNode.dynamicLoadComplete = true; } return tmpNode; } // ********************************************************************************* // ATTACH DRAG TO DATA (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.AttachDrag2Data = function(divParentID, divDataID){ if (Object.isUndefined($(divDataID))) { return false; } // get the i2b2 data from the yuiTree node var tvTree = YAHOO.widget.TreeView.getTree(divParentID); var tvNode = tvTree.getNodeByProperty('nodeid', divDataID); if (!Object.isUndefined(tvNode.DDProxy)) { return true; } // attach DD var t = new i2b2.sdx.TypeControllers.ENS.DragDrop(divDataID) t.yuiTree = tvTree; t.yuiTreeNode = tvNode; tvNode.DDProxy = t; // clear the mouseover attachment function var tdn = $(divDataID); if (!Object.isUndefined(tdn.onmouseover)) { try { delete tdn.onmouseover; } catch(e) { tdn.onmouseover; } } if (!Object.isUndefined(tdn.attributes)) { for (var i=0;i<tdn.attributes.length; i++) { if (tdn.attributes[i].name=="onmouseover") { try { delete tdn.onmouseover; } catch(e) { tdn.onmouseover; } } } } } /** * Get the child records for the given PatientRecordSet. * @param {Object} sdxParentNode The parent node we want to find the children of. * @param {ScopedCallback} onCompleteCallback A scoped-callback function to be executed using the results array. * @return {Boolean} Returns true to the calling function. * @return {Array} Returns an array of PatientRecord data represented as SDX Objects (without render data) to the callback function passed. * @memberOf i2b2.sdx.TypeControllers.QI * @method * @author Nick Benik * @version 1.0 * @alias i2b2.sdx.Master.getChildRecords */ i2b2.sdx.TypeControllers.ENS.getChildRecords = function(sdxParentNode, onCompleteCallback, options) { var scopedCallback = new i2b2_scopedCallback(); scopedCallback.scope = sdxParentNode; scopedCallback.callback = function(results) { var cl_node = sdxParentNode; var cl_onCompleteCB = onCompleteCallback; // THIS function is used to process the AJAX results of the getChild call // results data object contains the following attributes: // refXML: xmlDomObject <--- for data processing // msgRequest: xml (string) // msgResponse: xml (string) // error: boolean // errorStatus: string [only with error=true] // errorMsg: string [only with error=true] var retMsg = { error: results.error, msgRequest: results.msgRequest, msgResponse: results.msgResponse, msgUrl: results.msgUrl, results: null }; var retChildren = []; // extract records from XML msg var ps = results.refXML.getElementsByTagName('event'); var dm = i2b2.CRC.model.QueryMasters; for(var i1=0; i1<ps.length; i1++) { var o = new Object; o.xmlOrig = ps[i1]; o.patient_id = i2b2.h.getXNodeVal(ps[i1],'patient_id'); o.event_id = i2b2.h.getXNodeVal(ps[i1],'event_id'); //o.vital_status = i2b2.h.XPath(ps[i1],'param[@name="vital_status_cd"]/text()')[0].nodeValue; //o.age = i2b2.h.XPath(ps[i1],'param[@name="age_in_years_num"]/text()')[0].nodeValue; //o.sex = i2b2.h.XPath(ps[i1],'param[@name="sex_cd"]/text()')[0].nodeValue; //o.race = i2b2.h.XPath(ps[i1],'param[@name="race_cd"]/text()')[0].nodeValue; //o.title = o.patient_id+" ["+o.age+" y/o "+ o.sex+" "+o.race+"]"; var sdxDataNode = i2b2.sdx.Master.EncapsulateData('PR',o); // save record in the SDX system sdxDataNode = i2b2.sdx.Master.Save(sdxDataNode, cl_node); // append the data node to our returned results retChildren.push(sdxDataNode); } cl_node.children.loaded = true; // TODO: broadcast a data update event of the CRC data model retMsg.results = retChildren; if (getObjectClass(cl_onCompleteCB)=='i2b2_scopedCallback') { cl_onCompleteCB.callback.call(cl_onCompleteCB.scope, retMsg); } else { cl_onCompleteCB(retMsg); } } var msg_filter = '<input_list>\n' + ' <event_list max="1000000" min="0">\n'+ ' <patient_event_coll_id>'+sdxParentNode.sdxInfo.sdxKeyValue+'</patient_event_coll_id>\n'+ ' </event_list>\n'+ '</input_list>\n'+ '<filter_list/>\n'+ '<output_option>\n'+ ' <event_set select="using_input_list" onlykeys="true"/>\n'+ '</output_option>\n'; // AJAX CALL var options = { patient_limit: 0, PDO_Request: msg_filter }; i2b2.CRC.ajax.getPDO_fromInputList("CRC:SDX:PatientRecordSet", options, scopedCallback); } i2b2.sdx.TypeControllers.ENS.LoadChildrenFromTreeview = function(node, onCompleteCallback) { var scopedCallback = new i2b2_scopedCallback(); scopedCallback.scope = node.data.i2b2_SDX; scopedCallback.callback = function(retCellPack) { var cl_node = node; var cl_onCompleteCB = onCompleteCallback; var results = retCellPack.results; for(var i1=0; i1<1*results.length; i1++) { var o = results[i1]; var renderOptions = { dragdrop: "i2b2.sdx.TypeControllers.PRC.AttachDrag2Data", icon: "sdx_CRC_PR.jpg", title: o.sdxInfo.sdxDisplayName, showchildren: false }; var sdxRenderData = i2b2.sdx.Master.RenderHTML(cl_node.tree.id, o, renderOptions); i2b2.sdx.Master.AppendTreeNode(cl_node.tree, cl_node, sdxRenderData); } // handle the callback if (getObjectClass(cl_onCompleteCB)=='i2b2_scopedCallback') { cl_onCompleteCB.callback.call(cl_onCompleteCB.scope, retCellPack); } else { cl_onCompleteCB(retCellPack); } } var sdxParentNode = node.data.i2b2_SDX; var options = i2b2.CRC.params; i2b2.sdx.Master.getChildRecords(sdxParentNode, scopedCallback, options); } // ********************************************************************************* // DRAG DROP PROXY CONTROLLER // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.DragDrop = function(id, config) { if (id) { this.init(id, 'ENS',{isTarget:false}); this.initFrame(); } var s = this.getDragEl().style; s.borderColor = "transparent"; s.opacity = 0.75; s.filter = "alpha(opacity=75)"; s.whiteSpace = "nowrap"; s.overflow = "hidden"; s.textOverflow = "ellipsis"; }; YAHOO.extend(i2b2.sdx.TypeControllers.ENS.DragDrop, YAHOO.util.DDProxy); i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.startDrag = function(x, y) { var dragEl = this.getDragEl(); var clickEl = this.getEl(); dragEl.innerHTML = clickEl.innerHTML; dragEl.className = clickEl.className; dragEl.style.backgroundColor = '#FFFFEE'; dragEl.style.color = clickEl.style.color; dragEl.style.border = "1px solid blue"; dragEl.style.width = "160px"; dragEl.style.height = "20px"; this.setDelta(15,10); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.endDrag = function(e) { // remove DragDrop targeting CCS var targets = YAHOO.util.DDM.getRelated(this, true); for (var i=0; i<targets.length; i++) { var targetEl = targets[i]._domRef; i2b2.sdx.Master.onHoverOut('ENS', e, targetEl, this); } }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.alignElWithMouse = function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; YAHOO.util.Dom.setXY(el, aCoord); var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 ); var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 ); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { var posX = (oCoord.x + this.deltaSetXY[0]); var posY = (oCoord.y + this.deltaSetXY[1]); var scrSize = document.viewport.getDimensions(); var maxX = parseInt(scrSize.width-25-160); var maxY = parseInt(scrSize.height-25); if (posX > maxX) {posX = maxX;} if (posX < 6) {posX = 6;} if (posY > maxY) {posY = maxY;} if (posY < 6) {posY = 6;} YAHOO.util.Dom.setStyle(el, "left", posX + "px"); YAHOO.util.Dom.setStyle(el, "top", posY + "px"); } this.cachePosition(oCoord.x, oCoord.y); this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragOver = function(e, id) { // fire the onHoverOver (use SDX so targets can override default event handler) i2b2.sdx.Master.onHoverOver('ENS', e, id, this); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragOut = function(e, id) { // fire the onHoverOut handler (use SDX so targets can override default event handlers) i2b2.sdx.Master.onHoverOut('ENS', e, id, this); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragDrop = function(e, id) { i2b2.sdx.Master.onHoverOut('ENS', e, id, this); // retreive the concept data from the dragged element draggedData = this.yuiTreeNode.data.i2b2_SDX; i2b2.sdx.Master.ProcessDrop(draggedData, id); }; // ********************************************************************************* // <BLANK> DROP HANDLER // !!!! DO NOT EDIT - ATTACH YOUR OWN CUSTOM ROUTINE USING // !!!! THE i2b2.sdx.Master.setHandlerCustom FUNCTION // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.DropHandler = function(sdxData) { alert('[PatientRecordSet DROPPED] You need to create your own custom drop event handler.'); } console.timeEnd('execute time'); console.groupEnd();
Java
from pony.orm.core import *
Java
package com.mc.phonefinder.usersettings; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.mc.phonefinder.R; import com.mc.phonefinder.login.FindPhoneActivity; import com.mc.phonefinder.login.SampleApplication; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseGeoPoint; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; public class FindPhoneInterface extends ActionBarActivity { /* For the below: check if the setting is set for the user and if so let the user use the functionality. View location - Referes to location column in Settings table Show Phone finder image - Displays the image of the person who find the phone View nearby users - Refers to otherUsers in Settings table Alert my phone - Rings the phone to easily identify it */ static final boolean[] nearByUserSetting = new boolean[1]; static final boolean[] locationSetting = new boolean[1]; AtomicBoolean nearByUserSetting_check = new AtomicBoolean(); AtomicBoolean locPrefs_check = new AtomicBoolean(); public static String test = "Class"; static final String TAG="bharathdebug"; public void savePrefs(String key, boolean value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = sp.edit(); edit.putBoolean(key, value); edit.commit(); } public boolean loadBoolPrefs(String key) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean cbVal = sp.getBoolean(key, false); return cbVal; } public void savePrefs(String key, String value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = sp.edit(); edit.putString(key, value); edit.commit(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_find_phone_interface); final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId"); nearByUserSetting[0] = false; locationSetting[0] = false; savePrefs("nearByUserSetting", false); savePrefs("locationSetting", false); Log.i(TAG,"Before inner class"+test); // final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId"); ParseQuery<ParseObject> getSettings = new ParseQuery<ParseObject>("Settings"); getSettings.whereEqualTo("userObjectId", ObjectId); getSettings.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (objects != null) { Log.i(TAG, "Object not null"); if(objects.size()>0){ // nearByUserSetting[0] = objects.get(0).getBoolean("otherUser"); // locationSetting[0] = objects.get(0).getBoolean("location"); // test = "Inner class"; nearByUserSetting_check.set( objects.get(0).getBoolean("otherUser")); locPrefs_check.set(objects.get(0).getBoolean("location")); Log.i(TAG, "Inner class neary by " + String.valueOf(nearByUserSetting_check.get())); Log.i(TAG,"Inner class Location pref "+ (String.valueOf(locPrefs_check.get()))); // // savePrefs("nearByUserSetting", nearByUserSetting[0]); // savePrefs("locationSetting", locationSetting[0]); } } } }); // nearByUserSetting_check=loadBoolPrefs("nearByUserSetting"); // locPrefs_check = loadBoolPrefs("locationSetting"); // // Log.i(TAG,"Final val after inner class "+test); // System.out.print("Camera Setting " + nearByUserSetting[0]); Log.i(TAG,"Near by user "+ (String.valueOf(nearByUserSetting_check.get()))); Log.i(TAG,"Location pref "+ (String.valueOf(locPrefs_check.get()))); ((Button) findViewById(R.id.nearbyUsers)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(nearByUserSetting_check.get()) { Intent i = new Intent(); savePrefs("findPhoneId", ObjectId); Log.i(TAG, "FindPhoneInterface Object id " + ObjectId); i.setClass(FindPhoneInterface.this, NearbyUserView.class); //i.putExtra("userObjectId", ObjectId); startActivity(i); startActivity(new Intent(FindPhoneInterface.this, NearbyUserView.class)); } else { Toast.makeText(FindPhoneInterface.this, "Find nearby user service not set ", Toast.LENGTH_SHORT).show(); } } }); ((Button) findViewById(R.id.viewLocation)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(locPrefs_check.get()) { Toast.makeText(FindPhoneInterface.this, "Getting Your Location", Toast.LENGTH_LONG) .show(); String ObjectId = (String) FindPhoneInterface.this.getIntent().getSerializableExtra("userObjectId"); ParseQuery<ParseObject> query = ParseQuery.getQuery("Location"); if (!ObjectId.equals(null) && !ObjectId.equals("")) { query.whereEqualTo("userId", ObjectId); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { ParseGeoPoint userLocation; for (int i = 0; i < objects.size(); i++) { userLocation = objects.get(i).getParseGeoPoint("location"); String uri = String.format(Locale.ENGLISH, "geo:%f,%f?q=%f,%f", userLocation.getLatitude(), userLocation.getLongitude(), userLocation.getLatitude(), userLocation.getLongitude()); //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:%f,%f?q=%f,%f",userLocation.getLatitude(), userLocation.getLongitude(),userLocation.getLatitude(), userLocation.getLongitude())); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); startActivity(intent); Toast.makeText(FindPhoneInterface.this, "Opening Maps", Toast.LENGTH_LONG) .show(); } } }); } } else { Toast.makeText(FindPhoneInterface.this, "Location Preference service not set ", Toast.LENGTH_SHORT).show(); } }}); //Bharath - View image of person who picked phone ((Button) findViewById(R.id.btn_phonepicker)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Starts an intent of the log in activity Log.i(TAG,"Find face object id "+ObjectId); savePrefs("findfaceObjId",ObjectId); startActivity(new Intent(FindPhoneInterface.this, ShowPhoneFinderImage.class)); } }); //Change ringer alert ((Button) findViewById(R.id.triggerAlert)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ParseQuery<ParseObject> query = ParseQuery.getQuery("Settings"); query.whereEqualTo("userObjectId", ObjectId); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> scoreList, ParseException e) { //get current user ParseUser user = ParseUser.getCurrentUser(); if (e == null) { if (scoreList != null) { if (scoreList.size() > 0) { //store the location of the user with the objectId of the user scoreList.get(0).put("alertPhone", true); scoreList.get(0).saveInBackground(); Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG) .show(); } } else { ParseObject alertVal = new ParseObject("Settings"); alertVal.put("userObjectId", ObjectId); alertVal.put("alertPhone", true); scoreList.get(0).saveInBackground(); Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG) .show(); } } } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_find_phone_interface, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Mon Mar 28 17:12:17 AEST 2016 --> <title>Uses of Class org.apache.river.constants.TxnConstants (River-Internet vtrunk API Documentation (internals))</title> <meta name="date" content="2016-03-28"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.river.constants.TxnConstants (River-Internet vtrunk API Documentation (internals))"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/river/constants/TxnConstants.html" title="class in org.apache.river.constants">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/river/constants/class-use/TxnConstants.html" target="_top">Frames</a></li> <li><a href="TxnConstants.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.river.constants.TxnConstants" class="title">Uses of Class<br>org.apache.river.constants.TxnConstants</h2> </div> <div class="classUseContainer">No usage of org.apache.river.constants.TxnConstants</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/river/constants/TxnConstants.html" title="class in org.apache.river.constants">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/river/constants/class-use/TxnConstants.html" target="_top">Frames</a></li> <li><a href="TxnConstants.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright 2007-2013, multiple authors.<br>Licensed under the <a href=http://www.apache.org/licenses/LICENSE-2.0 target=child >Apache License, Version 2.0</a>, see the <a href=../../../../../doc-files/NOTICE target=child >NOTICE</a> file for attributions.</small></p> </body> </html>
Java
import AttributeCompression from "../Core/AttributeCompression.js"; import Cartesian3 from "../Core/Cartesian3.js"; import Cartographic from "../Core/Cartographic.js"; import Ellipsoid from "../Core/Ellipsoid.js"; import IndexDatatype from "../Core/IndexDatatype.js"; import CesiumMath from "../Core/Math.js"; import Rectangle from "../Core/Rectangle.js"; import createTaskProcessorWorker from "./createTaskProcessorWorker.js"; var maxShort = 32767; var scratchBVCartographic = new Cartographic(); var scratchEncodedPosition = new Cartesian3(); function decodePositions( positions, rectangle, minimumHeight, maximumHeight, ellipsoid ) { var positionsLength = positions.length / 3; var uBuffer = positions.subarray(0, positionsLength); var vBuffer = positions.subarray(positionsLength, 2 * positionsLength); var heightBuffer = positions.subarray( 2 * positionsLength, 3 * positionsLength ); AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer); var decoded = new Float64Array(positions.length); for (var i = 0; i < positionsLength; ++i) { var u = uBuffer[i]; var v = vBuffer[i]; var h = heightBuffer[i]; var lon = CesiumMath.lerp(rectangle.west, rectangle.east, u / maxShort); var lat = CesiumMath.lerp(rectangle.south, rectangle.north, v / maxShort); var alt = CesiumMath.lerp(minimumHeight, maximumHeight, h / maxShort); var cartographic = Cartographic.fromRadians( lon, lat, alt, scratchBVCartographic ); var decodedPosition = ellipsoid.cartographicToCartesian( cartographic, scratchEncodedPosition ); Cartesian3.pack(decodedPosition, decoded, i * 3); } return decoded; } var scratchRectangle = new Rectangle(); var scratchEllipsoid = new Ellipsoid(); var scratchCenter = new Cartesian3(); var scratchMinMaxHeights = { min: undefined, max: undefined, }; function unpackBuffer(packedBuffer) { packedBuffer = new Float64Array(packedBuffer); var offset = 0; scratchMinMaxHeights.min = packedBuffer[offset++]; scratchMinMaxHeights.max = packedBuffer[offset++]; Rectangle.unpack(packedBuffer, offset, scratchRectangle); offset += Rectangle.packedLength; Ellipsoid.unpack(packedBuffer, offset, scratchEllipsoid); offset += Ellipsoid.packedLength; Cartesian3.unpack(packedBuffer, offset, scratchCenter); } var scratchP0 = new Cartesian3(); var scratchP1 = new Cartesian3(); var scratchPrev = new Cartesian3(); var scratchCur = new Cartesian3(); var scratchNext = new Cartesian3(); function createVectorTilePolylines(parameters, transferableObjects) { var encodedPositions = new Uint16Array(parameters.positions); var widths = new Uint16Array(parameters.widths); var counts = new Uint32Array(parameters.counts); var batchIds = new Uint16Array(parameters.batchIds); unpackBuffer(parameters.packedBuffer); var rectangle = scratchRectangle; var ellipsoid = scratchEllipsoid; var center = scratchCenter; var minimumHeight = scratchMinMaxHeights.min; var maximumHeight = scratchMinMaxHeights.max; var positions = decodePositions( encodedPositions, rectangle, minimumHeight, maximumHeight, ellipsoid ); var positionsLength = positions.length / 3; var size = positionsLength * 4 - 4; var curPositions = new Float32Array(size * 3); var prevPositions = new Float32Array(size * 3); var nextPositions = new Float32Array(size * 3); var expandAndWidth = new Float32Array(size * 2); var vertexBatchIds = new Uint16Array(size); var positionIndex = 0; var expandAndWidthIndex = 0; var batchIdIndex = 0; var i; var offset = 0; var length = counts.length; for (i = 0; i < length; ++i) { var count = counts[i]; var width = widths[i]; var batchId = batchIds[i]; for (var j = 0; j < count; ++j) { var previous; if (j === 0) { var p0 = Cartesian3.unpack(positions, offset * 3, scratchP0); var p1 = Cartesian3.unpack(positions, (offset + 1) * 3, scratchP1); previous = Cartesian3.subtract(p0, p1, scratchPrev); Cartesian3.add(p0, previous, previous); } else { previous = Cartesian3.unpack( positions, (offset + j - 1) * 3, scratchPrev ); } var current = Cartesian3.unpack(positions, (offset + j) * 3, scratchCur); var next; if (j === count - 1) { var p2 = Cartesian3.unpack( positions, (offset + count - 1) * 3, scratchP0 ); var p3 = Cartesian3.unpack( positions, (offset + count - 2) * 3, scratchP1 ); next = Cartesian3.subtract(p2, p3, scratchNext); Cartesian3.add(p2, next, next); } else { next = Cartesian3.unpack(positions, (offset + j + 1) * 3, scratchNext); } Cartesian3.subtract(previous, center, previous); Cartesian3.subtract(current, center, current); Cartesian3.subtract(next, center, next); var startK = j === 0 ? 2 : 0; var endK = j === count - 1 ? 2 : 4; for (var k = startK; k < endK; ++k) { Cartesian3.pack(current, curPositions, positionIndex); Cartesian3.pack(previous, prevPositions, positionIndex); Cartesian3.pack(next, nextPositions, positionIndex); positionIndex += 3; var direction = k - 2 < 0 ? -1.0 : 1.0; expandAndWidth[expandAndWidthIndex++] = 2 * (k % 2) - 1; expandAndWidth[expandAndWidthIndex++] = direction * width; vertexBatchIds[batchIdIndex++] = batchId; } } offset += count; } var indices = IndexDatatype.createTypedArray(size, positionsLength * 6 - 6); var index = 0; var indicesIndex = 0; length = positionsLength - 1; for (i = 0; i < length; ++i) { indices[indicesIndex++] = index; indices[indicesIndex++] = index + 2; indices[indicesIndex++] = index + 1; indices[indicesIndex++] = index + 1; indices[indicesIndex++] = index + 2; indices[indicesIndex++] = index + 3; index += 4; } transferableObjects.push( curPositions.buffer, prevPositions.buffer, nextPositions.buffer ); transferableObjects.push( expandAndWidth.buffer, vertexBatchIds.buffer, indices.buffer ); return { indexDatatype: indices.BYTES_PER_ELEMENT === 2 ? IndexDatatype.UNSIGNED_SHORT : IndexDatatype.UNSIGNED_INT, currentPositions: curPositions.buffer, previousPositions: prevPositions.buffer, nextPositions: nextPositions.buffer, expandAndWidth: expandAndWidth.buffer, batchIds: vertexBatchIds.buffer, indices: indices.buffer, }; } export default createTaskProcessorWorker(createVectorTilePolylines);
Java
/* * 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.geode.internal.cache; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.UUID; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.DiskStore; import org.apache.geode.cache.DiskStoreFactory; import org.apache.geode.internal.cache.persistence.DefaultDiskDirs; /** * Creates an attribute object for DiskStore. * </p> * * @since GemFire prPersistSprint2 */ public class DiskStoreAttributes implements Serializable, DiskStore { private static final long serialVersionUID = 1L; public boolean allowForceCompaction; public boolean autoCompact; public int compactionThreshold; public int queueSize; public int writeBufferSize; public long maxOplogSizeInBytes; public long timeInterval; public int[] diskDirSizes; private DiskDirSizesUnit diskDirSizesUnit; public File[] diskDirs; public String name; private volatile float diskUsageWarningPct; private volatile float diskUsageCriticalPct; /** * The default disk directory size unit. */ @Immutable static final DiskDirSizesUnit DEFAULT_DISK_DIR_SIZES_UNIT = DiskDirSizesUnit.MEGABYTES; public DiskStoreAttributes() { // set all to defaults autoCompact = DiskStoreFactory.DEFAULT_AUTO_COMPACT; compactionThreshold = DiskStoreFactory.DEFAULT_COMPACTION_THRESHOLD; allowForceCompaction = DiskStoreFactory.DEFAULT_ALLOW_FORCE_COMPACTION; maxOplogSizeInBytes = DiskStoreFactory.DEFAULT_MAX_OPLOG_SIZE * (1024 * 1024); timeInterval = DiskStoreFactory.DEFAULT_TIME_INTERVAL; writeBufferSize = DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE; queueSize = DiskStoreFactory.DEFAULT_QUEUE_SIZE; diskDirs = DefaultDiskDirs.getDefaultDiskDirs(); diskDirSizes = DiskStoreFactory.DEFAULT_DISK_DIR_SIZES; diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT; diskUsageWarningPct = DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE; diskUsageCriticalPct = DiskStoreFactory.DEFAULT_DISK_USAGE_CRITICAL_PERCENTAGE; } @Override public UUID getDiskStoreUUID() { throw new UnsupportedOperationException("Not Implemented!"); } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getAllowForceCompaction() */ @Override public boolean getAllowForceCompaction() { return allowForceCompaction; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getAutoCompact() */ @Override public boolean getAutoCompact() { return autoCompact; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getCompactionThreshold() */ @Override public int getCompactionThreshold() { return compactionThreshold; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getDiskDirSizes() */ @Override public int[] getDiskDirSizes() { int[] result = new int[diskDirSizes.length]; System.arraycopy(diskDirSizes, 0, result, 0, diskDirSizes.length); return result; } public DiskDirSizesUnit getDiskDirSizesUnit() { return diskDirSizesUnit; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getDiskDirs() */ @Override public File[] getDiskDirs() { File[] result = new File[diskDirs.length]; System.arraycopy(diskDirs, 0, result, 0, diskDirs.length); return result; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getMaxOplogSize() */ @Override public long getMaxOplogSize() { return maxOplogSizeInBytes / (1024 * 1024); } /** * Used by unit tests */ public long getMaxOplogSizeInBytes() { return maxOplogSizeInBytes; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getName() */ @Override public String getName() { return name; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getQueueSize() */ @Override public int getQueueSize() { return queueSize; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getTimeInterval() */ @Override public long getTimeInterval() { return timeInterval; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getWriteBufferSize() */ @Override public int getWriteBufferSize() { return writeBufferSize; } @Override public void flush() { // nothing needed } @Override public void forceRoll() { // nothing needed } @Override public boolean forceCompaction() { return false; } @Override public void destroy() { // nothing needed } @Override public float getDiskUsageWarningPercentage() { return diskUsageWarningPct; } @Override public float getDiskUsageCriticalPercentage() { return diskUsageCriticalPct; } @Override public void setDiskUsageWarningPercentage(float warningPercent) { DiskStoreMonitor.checkWarning(warningPercent); diskUsageWarningPct = warningPercent; } @Override public void setDiskUsageCriticalPercentage(float criticalPercent) { DiskStoreMonitor.checkCritical(criticalPercent); diskUsageCriticalPct = criticalPercent; } public void setDiskDirSizesUnit(DiskDirSizesUnit unit) { diskDirSizesUnit = unit; } private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (diskDirSizesUnit == null) { diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT; } } public static void checkMinAndMaxOplogSize(long maxOplogSize) { long MAX = Long.MAX_VALUE / (1024 * 1024); if (maxOplogSize > MAX) { throw new IllegalArgumentException( String.format( "%s has to be a number that does not exceed %s so the value given %s is not acceptable", "max oplog size", maxOplogSize, MAX)); } checkMinOplogSize(maxOplogSize); } public static void checkMinOplogSize(long maxOplogSize) { if (maxOplogSize < 0) { throw new IllegalArgumentException( String.format( "Maximum Oplog size specified has to be a non-negative number and the value given %s is not acceptable", maxOplogSize)); } } public static void checkQueueSize(int queueSize) { if (queueSize < 0) { throw new IllegalArgumentException( String.format( "Queue size specified has to be a non-negative number and the value given %s is not acceptable", queueSize)); } } public static void checkWriteBufferSize(int writeBufferSize) { if (writeBufferSize < 0) { throw new IllegalArgumentException( String.format( "Write buffer size specified has to be a non-negative number and the value given %s is not acceptable", writeBufferSize)); } } /** * Verify all directory sizes are positive */ public static void verifyNonNegativeDirSize(int[] sizes) { for (int size : sizes) { if (size < 0) { throw new IllegalArgumentException( String.format("Dir size cannot be negative : %s", size)); } } } public static void checkTimeInterval(long timeInterval) { if (timeInterval < 0) { throw new IllegalArgumentException( String.format( "Time Interval specified has to be a non-negative number and the value given %s is not acceptable", timeInterval)); } } }
Java
/* Copyright 2017 The Kubernetes Authors. 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 signer import ( "crypto/x509" "io/ioutil" "reflect" "strings" "testing" "time" capi "k8s.io/api/certificates/v1beta1" "k8s.io/client-go/util/cert" ) func TestSigner(t *testing.T) { s, err := newCFSSLSigner("./testdata/ca.crt", "./testdata/ca.key", nil, 1*time.Hour) if err != nil { t.Fatalf("failed to create signer: %v", err) } csrb, err := ioutil.ReadFile("./testdata/kubelet.csr") if err != nil { t.Fatalf("failed to read CSR: %v", err) } csr := &capi.CertificateSigningRequest{ Spec: capi.CertificateSigningRequestSpec{ Request: []byte(csrb), Usages: []capi.KeyUsage{ capi.UsageSigning, capi.UsageKeyEncipherment, capi.UsageServerAuth, capi.UsageClientAuth, }, }, } csr, err = s.sign(csr) if err != nil { t.Fatalf("failed to sign CSR: %v", err) } certData := csr.Status.Certificate if len(certData) == 0 { t.Fatalf("expected a certificate after signing") } certs, err := cert.ParseCertsPEM(certData) if err != nil { t.Fatalf("failed to parse certificate: %v", err) } if len(certs) != 1 { t.Fatalf("expected one certificate") } crt := certs[0] if crt.Subject.CommonName != "system:node:k-a-node-s36b" { t.Errorf("expected common name of 'system:node:k-a-node-s36b', but got: %v", certs[0].Subject.CommonName) } if !reflect.DeepEqual(crt.Subject.Organization, []string{"system:nodes"}) { t.Errorf("expected organization to be [system:nodes] but got: %v", crt.Subject.Organization) } if crt.KeyUsage != x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment { t.Errorf("bad key usage") } if !reflect.DeepEqual(crt.ExtKeyUsage, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}) { t.Errorf("bad extended key usage") } } func TestSignerExpired(t *testing.T) { hundredYearsFromNowFn := func() time.Time { return time.Now().Add(24 * time.Hour * 365 * 100) } s, err := newCFSSLSigner("./testdata/ca.crt", "./testdata/ca.key", nil, 1*time.Hour) if err != nil { t.Fatalf("failed to create signer: %v", err) } s.nowFn = hundredYearsFromNowFn csrb, err := ioutil.ReadFile("./testdata/kubelet.csr") if err != nil { t.Fatalf("failed to read CSR: %v", err) } csr := &capi.CertificateSigningRequest{ Spec: capi.CertificateSigningRequestSpec{ Request: []byte(csrb), Usages: []capi.KeyUsage{ capi.UsageSigning, capi.UsageKeyEncipherment, capi.UsageServerAuth, capi.UsageClientAuth, }, }, } _, err = s.sign(csr) if err == nil { t.Fatal("missing error") } if !strings.HasPrefix(err.Error(), "the signer has expired") { t.Fatal(err) } } func TestDurationLongerThanExpiry(t *testing.T) { testNow := time.Now() testNowFn := func() time.Time { return testNow } hundredYears := 24 * time.Hour * 365 * 100 s, err := newCFSSLSigner("./testdata/ca.crt", "./testdata/ca.key", nil, hundredYears) if err != nil { t.Fatalf("failed to create signer: %v", err) } s.nowFn = testNowFn csrb, err := ioutil.ReadFile("./testdata/kubelet.csr") if err != nil { t.Fatalf("failed to read CSR: %v", err) } csr := &capi.CertificateSigningRequest{ Spec: capi.CertificateSigningRequestSpec{ Request: []byte(csrb), Usages: []capi.KeyUsage{ capi.UsageSigning, capi.UsageKeyEncipherment, capi.UsageServerAuth, capi.UsageClientAuth, }, }, } _, err = s.sign(csr) if err != nil { t.Fatalf("failed to sign CSR: %v", err) } // now we just need to verify that the expiry is based on the signing cert certData := csr.Status.Certificate if len(certData) == 0 { t.Fatalf("expected a certificate after signing") } certs, err := cert.ParseCertsPEM(certData) if err != nil { t.Fatalf("failed to parse certificate: %v", err) } if len(certs) != 1 { t.Fatalf("expected one certificate") } crt := certs[0] expected, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", "2044-05-09 00:20:11 +0000 UTC") if err != nil { t.Fatal(err) } // there is some jitter that we need to tolerate diff := expected.Sub(crt.NotAfter) if diff > 10*time.Minute || diff < -10*time.Minute { t.Fatal(crt.NotAfter) } }
Java
/* * SVG Salamander * Copyright (c) 2004, Mark McKay * 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. * * 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 * COPYRIGHT HOLDER 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. * * Mark McKay can be contacted at [email protected]. Salamander and other * projects can be found at http://www.kitfox.com * * Created on January 26, 2004, 8:40 PM */ package com.kitfox.svg.pathcmd; //import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; import java.awt.*; import java.awt.geom.*; /** * This is a little used SVG function, as most editors will save curves as * Beziers. To reduce the need to rely on the Batik library, this functionallity * is being bypassed for the time being. In the future, it would be nice to * extend the GeneralPath command to include the arcTo ability provided by Batik. * * @author Mark McKay * @author <a href="mailto:[email protected]">Mark McKay</a> */ public class Arc extends PathCommand { public float rx = 0f; public float ry = 0f; public float xAxisRot = 0f; public boolean largeArc = false; public boolean sweep = false; public float x = 0f; public float y = 0f; /** Creates a new instance of MoveTo */ public Arc() { } public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) { super(isRelative); this.rx = rx; this.ry = ry; this.xAxisRot = xAxisRot; this.largeArc = largeArc; this.sweep = sweep; this.x = x; this.y = y; } // public void appendPath(ExtendedGeneralPath path, BuildHistory hist) @Override public void appendPath(GeneralPath path, BuildHistory hist) { float offx = isRelative ? hist.lastPoint.x : 0f; float offy = isRelative ? hist.lastPoint.y : 0f; arcTo(path, rx, ry, xAxisRot, largeArc, sweep, x + offx, y + offy, hist.lastPoint.x, hist.lastPoint.y); // path.lineTo(x + offx, y + offy); // hist.setPoint(x + offx, y + offy); hist.setLastPoint(x + offx, y + offy); hist.setLastKnot(x + offx, y + offy); } @Override public int getNumKnotsAdded() { return 6; } /** * Adds an elliptical arc, defined by two radii, an angle from the * x-axis, a flag to choose the large arc or not, a flag to * indicate if we increase or decrease the angles and the final * point of the arc. * * @param rx the x radius of the ellipse * @param ry the y radius of the ellipse * * @param angle the angle from the x-axis of the current * coordinate system to the x-axis of the ellipse in degrees. * * @param largeArcFlag the large arc flag. If true the arc * spanning less than or equal to 180 degrees is chosen, otherwise * the arc spanning greater than 180 degrees is chosen * * @param sweepFlag the sweep flag. If true the line joining * center to arc sweeps through decreasing angles otherwise it * sweeps through increasing angles * * @param x the absolute x coordinate of the final point of the arc. * @param y the absolute y coordinate of the final point of the arc. * @param x0 - The absolute x coordinate of the initial point of the arc. * @param y0 - The absolute y coordinate of the initial point of the arc. */ public void arcTo(GeneralPath path, float rx, float ry, float angle, boolean largeArcFlag, boolean sweepFlag, float x, float y, float x0, float y0) { // Ensure radii are valid if (rx == 0 || ry == 0) { path.lineTo((float) x, (float) y); return; } if (x0 == x && y0 == y) { // If the endpoints (x, y) and (x0, y0) are identical, then this // is equivalent to omitting the elliptical arc segment entirely. return; } Arc2D arc = computeArc(x0, y0, rx, ry, angle, largeArcFlag, sweepFlag, x, y); if (arc == null) return; AffineTransform t = AffineTransform.getRotateInstance (Math.toRadians(angle), arc.getCenterX(), arc.getCenterY()); Shape s = t.createTransformedShape(arc); path.append(s, true); } /** * This constructs an unrotated Arc2D from the SVG specification of an * Elliptical arc. To get the final arc you need to apply a rotation * transform such as: * * AffineTransform.getRotateInstance * (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2); */ public static Arc2D computeArc(double x0, double y0, double rx, double ry, double angle, boolean largeArcFlag, boolean sweepFlag, double x, double y) { // // Elliptical arc implementation based on the SVG specification notes // // Compute the half distance between the current and the final point double dx2 = (x0 - x) / 2.0; double dy2 = (y0 - y) / 2.0; // Convert angle from degrees to radians angle = Math.toRadians(angle % 360.0); double cosAngle = Math.cos(angle); double sinAngle = Math.sin(angle); // // Step 1 : Compute (x1, y1) // double x1 = (cosAngle * dx2 + sinAngle * dy2); double y1 = (-sinAngle * dx2 + cosAngle * dy2); // Ensure radii are large enough rx = Math.abs(rx); ry = Math.abs(ry); double Prx = rx * rx; double Pry = ry * ry; double Px1 = x1 * x1; double Py1 = y1 * y1; // check that radii are large enough double radiiCheck = Px1/Prx + Py1/Pry; if (radiiCheck > 1) { rx = Math.sqrt(radiiCheck) * rx; ry = Math.sqrt(radiiCheck) * ry; Prx = rx * rx; Pry = ry * ry; } // // Step 2 : Compute (cx1, cy1) // double sign = (largeArcFlag == sweepFlag) ? -1 : 1; double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1)); sq = (sq < 0) ? 0 : sq; double coef = (sign * Math.sqrt(sq)); double cx1 = coef * ((rx * y1) / ry); double cy1 = coef * -((ry * x1) / rx); // // Step 3 : Compute (cx, cy) from (cx1, cy1) // double sx2 = (x0 + x) / 2.0; double sy2 = (y0 + y) / 2.0; double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); // // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) // double ux = (x1 - cx1) / rx; double uy = (y1 - cy1) / ry; double vx = (-x1 - cx1) / rx; double vy = (-y1 - cy1) / ry; double p, n; // Compute the angle start n = Math.sqrt((ux * ux) + (uy * uy)); p = ux; // (1 * ux) + (0 * uy) sign = (uy < 0) ? -1d : 1d; double angleStart = Math.toDegrees(sign * Math.acos(p / n)); // Compute the angle extent n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); p = ux * vx + uy * vy; sign = (ux * vy - uy * vx < 0) ? -1d : 1d; double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); if(!sweepFlag && angleExtent > 0) { angleExtent -= 360f; } else if (sweepFlag && angleExtent < 0) { angleExtent += 360f; } angleExtent %= 360f; angleStart %= 360f; // // We can now build the resulting Arc2D in double precision // Arc2D.Double arc = new Arc2D.Double(); arc.x = cx - rx; arc.y = cy - ry; arc.width = rx * 2.0; arc.height = ry * 2.0; arc.start = -angleStart; arc.extent = -angleExtent; return arc; } @Override public String toString() { return "A " + rx + " " + ry + " " + xAxisRot + " " + largeArc + " " + sweep + " " + x + " " + y; } }
Java
// Copyright (C) 2011-2012 the original author or authors. // See the LICENCE.txt file distributed with this work for additional // information regarding copyright ownership. // // 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.scalastyle.file import org.junit.Test import org.scalatest.junit.AssertionsForJUnit // scalastyle:off magic.number multiple.string.literals class HeaderMatchesCheckerTest extends AssertionsForJUnit with CheckerTest { val key = "header.matches" val classUnderTest = classOf[HeaderMatchesChecker] val licenseLines = List( "/**", " * Copyright (C) 2009-2010 the original author or authors.", " * See the notice.md file distributed with this work for additional", " * information regarding copyright ownership.", " *", " * 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.", " */" ) val licenseUnix = licenseLines.mkString("\n") val licenseWin = licenseLines.mkString("\r\n") val baseSourceLines = List( "", "package foobar", "", " object Foobar {", "}", "" ) @Test def testOK(): Unit = { val sourceLines = licenseLines ::: baseSourceLines val sourceUnix = sourceLines.mkString("\n") val sourceWin = sourceLines.mkString("\r\n") assertErrors(List(), sourceUnix, Map("header" -> licenseUnix)) assertErrors(List(), sourceWin, Map("header" -> licenseWin)) assertErrors(List(), sourceUnix, Map("header" -> licenseWin)) assertErrors(List(), sourceWin, Map("header" -> licenseUnix)) } @Test def testKO(): Unit = { val sourceLines = licenseLines ::: baseSourceLines val sourceUnix = sourceLines.mkString("\n").replaceAll("BASIS,", "XXX") val sourceWin = sourceLines.mkString("\r\n").replaceAll("BASIS,", "XXX") assertErrors(List(lineError(13)), sourceUnix, Map("header" -> licenseUnix)) assertErrors(List(lineError(13)), sourceWin, Map("header" -> licenseWin)) assertErrors(List(lineError(13)), sourceUnix, Map("header" -> licenseWin)) assertErrors(List(lineError(13)), sourceWin, Map("header" -> licenseUnix)) } @Test def testTooShort(): Unit = { val shortSourceLines = licenseLines.take(4) val shortSourceUnix = shortSourceLines.mkString("\n") val shortSourceWin = shortSourceLines.mkString("\r\n") assertErrors(List(lineError(4)), shortSourceUnix, Map("header" -> licenseUnix)) assertErrors(List(lineError(4)), shortSourceWin, Map("header" -> licenseWin)) assertErrors(List(lineError(4)), shortSourceUnix, Map("header" -> licenseWin)) assertErrors(List(lineError(4)), shortSourceWin, Map("header" -> licenseUnix)) } def literalOK(c: Char): Boolean = c match { case ' '|'-'|':'|'/'|'\n' => true case ld: Any if ld.isLetterOrDigit => true case _ => false } val licenceRegexUnix = { (licenseUnix flatMap { c => if (literalOK(c)) c.toString else "\\" + c}).replace("2009-2010", "(?:\\d{4}-)?\\d{4}") } val licenceRegexWin = { (licenseWin flatMap { c => if (literalOK(c)) c.toString else "\\" + c}).replace("2009-2010", "(?:\\d{4}-)?\\d{4}") } @Test def testRegexOK(): Unit = { val sourceLines = licenseLines ::: baseSourceLines val sourceUnix = sourceLines.mkString("\n") val sourceWin = sourceLines.mkString("\r\n") assertErrors(List(), sourceUnix, Map("header" -> licenceRegexUnix, "regex" -> "true")) assertErrors(List(), sourceWin, Map("header" -> licenceRegexWin, "regex" -> "true")) assertErrors(List(), sourceUnix, Map("header" -> licenceRegexWin, "regex" -> "true")) assertErrors(List(), sourceWin, Map("header" -> licenceRegexUnix, "regex" -> "true")) } @Test def testRegexFlexible(): Unit = { val sourceLines = licenseLines ::: baseSourceLines val sourceUnix = sourceLines.mkString("\n").replace("2009-2010", "2009-2014") val sourceWin = sourceLines.mkString("\r\n").replace("2009-2010", "2009-2014") assertErrors(List(), sourceUnix, Map("header" -> licenceRegexUnix, "regex" -> "true")) assertErrors(List(), sourceWin, Map("header" -> licenceRegexWin, "regex" -> "true")) assertErrors(List(), sourceUnix, Map("header" -> licenceRegexWin, "regex" -> "true")) assertErrors(List(), sourceWin, Map("header" -> licenceRegexUnix, "regex" -> "true")) } @Test def testRegexKO(): Unit = { val sourceLines = licenseLines ::: baseSourceLines val sourceUnix = sourceLines.mkString("\n").replace("2009-2010", "xxxx-xxxx") val sourceWin = sourceLines.mkString("\r\n").replace("2009-2010", "xxxx-xxxx") assertErrors(List(fileError()), sourceUnix, Map("header" -> licenceRegexUnix, "regex" -> "true")) assertErrors(List(fileError()), sourceWin, Map("header" -> licenceRegexWin, "regex" -> "true")) assertErrors(List(fileError()), sourceUnix, Map("header" -> licenceRegexWin, "regex" -> "true")) assertErrors(List(fileError()), sourceWin, Map("header" -> licenceRegexUnix, "regex" -> "true")) } }
Java
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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 com.hazelcast.cache; import com.hazelcast.cache.impl.CachePartitionEventData; import com.hazelcast.cache.impl.CachePartitionSegment; import com.hazelcast.cache.impl.CacheService; import com.hazelcast.cache.impl.operation.CacheReplicationOperation; import com.hazelcast.cache.impl.record.CacheRecord; import com.hazelcast.cache.impl.record.CacheRecordFactory; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.impl.MemberImpl; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.instance.impl.HazelcastInstanceImpl; import com.hazelcast.instance.impl.HazelcastInstanceProxy; import com.hazelcast.internal.serialization.Data; import com.hazelcast.internal.serialization.SerializationService; import com.hazelcast.internal.serialization.SerializationServiceBuilder; import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder; import com.hazelcast.internal.services.ServiceNamespace; import com.hazelcast.internal.util.Clock; import com.hazelcast.internal.util.CollectionUtil; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import com.hazelcast.version.MemberVersion; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.configuration.CompleteConfiguration; import javax.cache.configuration.MutableConfiguration; import javax.cache.spi.CachingProvider; import java.lang.reflect.Field; import java.net.UnknownHostException; import java.util.Collection; import static com.hazelcast.cache.CacheTestSupport.createServerCachingProvider; import static org.junit.Assert.assertEquals; /** * Serialization test class for JCache */ @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class CacheSerializationTest extends HazelcastTestSupport { SerializationService service; @Before public void setup() { SerializationServiceBuilder builder = new DefaultSerializationServiceBuilder(); service = builder.build(); } @After public void tearDown() { } @Test public void testCacheRecord_withBinaryInMemoryData() { String value = randomString(); CacheRecord cacheRecord = createRecord(InMemoryFormat.BINARY, value); Data cacheRecordData = service.toData(cacheRecord); CacheRecord deserialized = service.toObject(cacheRecordData); assertEquals(value, service.toObject(deserialized.getValue())); } @Test public void testCacheRecord_withObjectInMemoryData() { String value = randomString(); CacheRecord cacheRecord = createRecord(InMemoryFormat.OBJECT, value); Data cacheRecordData = service.toData(cacheRecord); CacheRecord deserialized = service.toObject(cacheRecordData); assertEquals(value, deserialized.getValue()); } @Test public void test_CacheReplicationOperation_serialization() throws Exception { TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1); HazelcastInstance hazelcastInstance = factory.newHazelcastInstance(); try { CachingProvider provider = createServerCachingProvider(hazelcastInstance); CacheManager manager = provider.getCacheManager(); CompleteConfiguration configuration = new MutableConfiguration(); Cache cache1 = manager.createCache("cache1", configuration); Cache cache2 = manager.createCache("cache2", configuration); Cache cache3 = manager.createCache("cache3", configuration); for (int i = 0; i < 1000; i++) { cache1.put("key" + i, i); cache2.put("key" + i, i); cache3.put("key" + i, i); } HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) hazelcastInstance; Field original = HazelcastInstanceProxy.class.getDeclaredField("original"); original.setAccessible(true); HazelcastInstanceImpl impl = (HazelcastInstanceImpl) original.get(proxy); NodeEngineImpl nodeEngine = impl.node.nodeEngine; CacheService cacheService = nodeEngine.getService(CacheService.SERVICE_NAME); int partitionCount = nodeEngine.getPartitionService().getPartitionCount(); for (int partitionId = 0; partitionId < partitionCount; partitionId++) { CachePartitionSegment segment = cacheService.getSegment(partitionId); int replicaIndex = 1; Collection<ServiceNamespace> namespaces = segment.getAllNamespaces(replicaIndex); if (CollectionUtil.isEmpty(namespaces)) { continue; } CacheReplicationOperation operation = new CacheReplicationOperation(); operation.prepare(segment, namespaces, replicaIndex); Data serialized = service.toData(operation); try { service.toObject(serialized); } catch (Exception e) { throw new Exception("Partition: " + partitionId, e); } } } finally { factory.shutdownAll(); } } @Test public void testCachePartitionEventData() throws UnknownHostException { Address address = new Address("127.0.0.1", 5701); Member member = new MemberImpl(address, MemberVersion.UNKNOWN, true); CachePartitionEventData cachePartitionEventData = new CachePartitionEventData("test", 1, member); CachePartitionEventData deserialized = service.toObject(cachePartitionEventData); assertEquals(cachePartitionEventData, deserialized); } private CacheRecord createRecord(InMemoryFormat format, String value) { CacheRecordFactory factory = new CacheRecordFactory(format, service); return factory.newRecordWithExpiry(value, Clock.currentTimeMillis(), -1); } }
Java
'use strict'; angular.module('publisherApp') .config(function ($stateProvider) { $stateProvider .state('settings', { parent: 'account', url: '/settings', data: { roles: ['ROLE_USER'], pageTitle: 'global.menu.account.settings' }, views: { 'container@': { templateUrl: 'scripts/app/account/settings/settings.html', controller: 'SettingsController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('settings'); return $translate.refresh(); }] } }); });
Java
package com.sean.im.client.push.handler; import com.alibaba.fastjson.JSON; import com.sean.im.client.constant.Global; import com.sean.im.client.core.ApplicationContext; import com.sean.im.client.core.PushHandler; import com.sean.im.client.form.MainForm; import com.sean.im.client.tray.TrayManager; import com.sean.im.client.util.MusicUtil; import com.sean.im.commom.core.Protocol; import com.sean.im.commom.entity.Message; /** * 移除群成员 * @author sean */ public class KickOutFlockHandler implements PushHandler { @Override public void execute(Protocol notify) { Message msg = JSON.parseObject(notify.getParameter("msg"), Message.class); // 界面上删除群 long flockId = Long.parseLong(msg.getContent()); MainForm.FORM.getFlockList().removeFlock(flockId); // 压入消息队列 ApplicationContext.CTX.getMessageQueue().add(msg); // 提示系统托盘闪烁 TrayManager.getInstance().startLight(0); MusicUtil.play(Global.Root + "resource/sound/msg.wav"); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Mon Mar 28 17:12:30 AEST 2016 --> <title>Uses of Class org.apache.river.start.SharedActivatableServiceDescriptor (River-Internet vtrunk API Documentation (internals))</title> <meta name="date" content="2016-03-28"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.river.start.SharedActivatableServiceDescriptor (River-Internet vtrunk API Documentation (internals))"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/river/start/class-use/SharedActivatableServiceDescriptor.html" target="_top">Frames</a></li> <li><a href="SharedActivatableServiceDescriptor.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.river.start.SharedActivatableServiceDescriptor" class="title">Uses of Class<br>org.apache.river.start.SharedActivatableServiceDescriptor</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">SharedActivatableServiceDescriptor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.river.tool.envcheck.plugins">org.apache.river.tool.envcheck.plugins</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.river.tool.envcheck.plugins"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">SharedActivatableServiceDescriptor</a> in <a href="../../../../../org/apache/river/tool/envcheck/plugins/package-summary.html">org.apache.river.tool.envcheck.plugins</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/river/tool/envcheck/plugins/package-summary.html">org.apache.river.tool.envcheck.plugins</a> with parameters of type <a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">SharedActivatableServiceDescriptor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>private <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">CheckPersistence.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/river/tool/envcheck/plugins/CheckPersistence.html#checkDir-java.lang.String-org.apache.river.start.SharedActivatableServiceDescriptor-">checkDir</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;dir, <a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">SharedActivatableServiceDescriptor</a>&nbsp;d)</code> <div class="block">Perform a check on the given persistence directory.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private void</code></td> <td class="colLast"><span class="typeNameLabel">CheckPersistence.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/river/tool/envcheck/plugins/CheckPersistence.html#checkDirectory-org.apache.river.start.SharedActivatableServiceDescriptor-">checkDirectory</a></span>(<a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">SharedActivatableServiceDescriptor</a>&nbsp;d)</code> <div class="block">Launch a subtask for the given descriptor to obtain all the <code>persistenceDirectory</code> entries.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private void</code></td> <td class="colLast"><span class="typeNameLabel">CheckPersistence.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/river/tool/envcheck/plugins/CheckPersistence.html#checkEntries-java.lang.String:A-org.apache.river.start.SharedActivatableServiceDescriptor-java.lang.String-">checkEntries</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;entries, <a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">SharedActivatableServiceDescriptor</a>&nbsp;d, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;source)</code> <div class="block">Check <code>entries</code> for validity.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/river/start/SharedActivatableServiceDescriptor.html" title="class in org.apache.river.start">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/river/start/class-use/SharedActivatableServiceDescriptor.html" target="_top">Frames</a></li> <li><a href="SharedActivatableServiceDescriptor.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright 2007-2013, multiple authors.<br>Licensed under the <a href=http://www.apache.org/licenses/LICENSE-2.0 target=child >Apache License, Version 2.0</a>, see the <a href=../../../../../doc-files/NOTICE target=child >NOTICE</a> file for attributions.</small></p> </body> </html>
Java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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 com.intellij.psi.impl.cache.impl.idCache; import com.intellij.lexer.Lexer; import com.intellij.lexer.XHtmlHighlightingLexer; import com.intellij.psi.impl.cache.impl.BaseFilterLexer; import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer; public class XHtmlIdIndexer extends LexerBasedIdIndexer { protected Lexer createLexer(final BaseFilterLexer.OccurrenceConsumer consumer) { return new XHtmlFilterLexer(new XHtmlHighlightingLexer(), consumer); } }
Java
/* * 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. */ /* * $Id: XSValueTest.cpp 568078 2007-08-21 11:43:25Z amassari $ * $Log$ * Revision 1.17 2005/05/05 09:46:11 cargilld * Update XSValue to handle float and double the same way the main library does, converting values to infinityr or zero, as the C ranges for float and double are less than the schema ranges. * * Revision 1.16 2005/04/05 20:26:48 cargilld * Update XSValue to handle leading and trailing whitespace. * * Revision 1.15 2005/02/25 18:30:46 cargilld * Attempt to fix compiler errors. * * Revision 1.14 2005/02/25 09:38:23 gareth * Fix for compile under gcc 4. Patch by Scott Cantor. * * Revision 1.13 2004/12/23 16:11:21 cargilld * Various XSValue updates: use ulong for postiveInteger; reset date fields to zero; modifty XSValueTest to test the returned value from getActualValue. * * Revision 1.12 2004/11/14 19:02:21 peiyongz * error status for numeric data types tested * * Revision 1.11 2004/09/13 21:25:11 peiyongz * DATATYPE_TEST added * * Revision 1.10 2004/09/10 13:55:00 peiyongz * to run on 64 box * * Revision 1.9 2004/09/09 20:10:04 peiyongz * Using new error code * * Revision 1.8 2004/09/08 19:56:32 peiyongz * Remove parameter toValidate from validation interface * * Revision 1.7 2004/09/08 13:57:06 peiyongz * Apache License Version 2.0 * * Revision 1.6 2004/08/31 20:53:43 peiyongz * Testing time zone * * Revision 1.5 2004/08/31 15:15:16 peiyongz * remove XSValueContext * * Revision 1.4 2004/08/24 16:00:15 peiyongz * To build on AIX/Win2003-ecl * * Revision 1.3 2004/08/23 17:07:57 peiyongz * Minimum representable range on all platforms * * Revision 1.2 2004/08/19 21:29:28 peiyongz * no message * * Revision 1.1 2004/08/19 17:17:21 peiyongz * XSValueTest * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "XSValueTest.hpp" #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/XMLUni.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <fstream> #else #include <fstream.h> #endif #include <stdio.h> #include <math.h> #include <xercesc/framework/psvi/XSValue.hpp> #include <xercesc/util/PlatformUtils.hpp> static const bool EXP_RET_VALID_TRUE = true; static const bool EXP_RET_VALUE_TRUE = true; static const bool EXP_RET_CANREP_TRUE = true; static const bool EXP_RET_VALID_FALSE = false; static const bool EXP_RET_VALUE_FALSE = false; static const bool EXP_RET_CANREP_FALSE = false; static const XSValue::Status DONT_CARE = XSValue::st_UnknownType; static bool errSeen = false; static const XMLCh* getDataTypeString(const XSValue::DataType dt) { switch(dt) { case XSValue::dt_string: return SchemaSymbols::fgDT_STRING; case XSValue::dt_boolean: return SchemaSymbols::fgDT_BOOLEAN; case XSValue::dt_decimal: return SchemaSymbols::fgDT_DECIMAL; case XSValue::dt_float: return SchemaSymbols::fgDT_FLOAT; case XSValue::dt_double: return SchemaSymbols::fgDT_DOUBLE; case XSValue::dt_duration: return SchemaSymbols::fgDT_DURATION; case XSValue::dt_dateTime: return SchemaSymbols::fgDT_DATETIME; case XSValue::dt_time: return SchemaSymbols::fgDT_TIME; case XSValue::dt_date: return SchemaSymbols::fgDT_DATE; case XSValue::dt_gYearMonth: return SchemaSymbols::fgDT_YEARMONTH; case XSValue::dt_gYear: return SchemaSymbols::fgDT_YEAR; case XSValue::dt_gMonthDay: return SchemaSymbols::fgDT_MONTHDAY; case XSValue::dt_gDay: return SchemaSymbols::fgDT_DAY; case XSValue::dt_gMonth: return SchemaSymbols::fgDT_MONTH; case XSValue::dt_hexBinary: return SchemaSymbols::fgDT_HEXBINARY; case XSValue::dt_base64Binary: return SchemaSymbols::fgDT_BASE64BINARY; case XSValue::dt_anyURI: return SchemaSymbols::fgDT_ANYURI; case XSValue::dt_QName: return SchemaSymbols::fgDT_QNAME; case XSValue::dt_NOTATION: return XMLUni::fgNotationString; case XSValue::dt_normalizedString: return SchemaSymbols::fgDT_NORMALIZEDSTRING; case XSValue::dt_token: return SchemaSymbols::fgDT_TOKEN; case XSValue::dt_language: return SchemaSymbols::fgDT_LANGUAGE; case XSValue::dt_NMTOKEN: return XMLUni::fgNmTokenString; case XSValue::dt_NMTOKENS: return XMLUni::fgNmTokensString; case XSValue::dt_Name: return SchemaSymbols::fgDT_NAME; case XSValue::dt_NCName: return SchemaSymbols::fgDT_NCNAME; case XSValue::dt_ID: return XMLUni::fgIDString; case XSValue::dt_IDREF: return XMLUni::fgIDRefString; case XSValue::dt_IDREFS: return XMLUni::fgIDRefsString; case XSValue::dt_ENTITY: return XMLUni::fgEntityString; case XSValue::dt_ENTITIES: return XMLUni::fgEntitiesString; case XSValue::dt_integer: return SchemaSymbols::fgDT_INTEGER; case XSValue::dt_nonPositiveInteger: return SchemaSymbols::fgDT_NONPOSITIVEINTEGER; case XSValue::dt_negativeInteger: return SchemaSymbols::fgDT_NEGATIVEINTEGER; case XSValue::dt_long: return SchemaSymbols::fgDT_LONG; case XSValue::dt_int: return SchemaSymbols::fgDT_INT; case XSValue::dt_short: return SchemaSymbols::fgDT_SHORT; case XSValue::dt_byte: return SchemaSymbols::fgDT_BYTE; case XSValue::dt_nonNegativeInteger: return SchemaSymbols::fgDT_NONNEGATIVEINTEGER; case XSValue::dt_unsignedLong: return SchemaSymbols::fgDT_ULONG; case XSValue::dt_unsignedInt: return SchemaSymbols::fgDT_UINT; case XSValue::dt_unsignedShort: return SchemaSymbols::fgDT_USHORT; case XSValue::dt_unsignedByte: return SchemaSymbols::fgDT_UBYTE; case XSValue::dt_positiveInteger: return SchemaSymbols::fgDT_POSITIVEINTEGER; default: return 0; } } static bool compareActualValue( const XSValue::DataType datatype , const XSValue::XSValue_Data actValue , const XSValue::XSValue_Data expValue) { switch (datatype) { case XSValue::dt_boolean: if (actValue.fValue.f_bool == expValue.fValue.f_bool) return true; printf("ACTVALUE_TEST Unexpected XSValue for dt_boolean, got %d expected %d\n", actValue.fValue.f_bool, expValue.fValue.f_bool); return false; case XSValue::dt_decimal: if (fabs(actValue.fValue.f_double - expValue.fValue.f_double) < fabs(actValue.fValue.f_double)/1000) return true; printf("ACTVALUE_TEST Unexpected XSValue for datatype %s, got %f expected %f\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_double, expValue.fValue.f_double); return false; case XSValue::dt_double: if (actValue.fValue.f_doubleType.f_doubleEnum == XSValue::DoubleFloatType_Normal) { if (fabs(actValue.fValue.f_double - expValue.fValue.f_double) < fabs(actValue.fValue.f_double)/1000) return true; printf("ACTVALUE_TEST Unexpected XSValue for datatype %s, got %f expected %f\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_double, expValue.fValue.f_double); return false; } else { if (actValue.fValue.f_doubleType.f_doubleEnum == expValue.fValue.f_doubleType.f_doubleEnum) return true; printf("ACTVALUE_TEST Unexpected XSValue enum for datatype %s, got %d expected %d\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_doubleType.f_doubleEnum, expValue.fValue.f_doubleType.f_doubleEnum); return false; } case XSValue::dt_float: if (actValue.fValue.f_floatType.f_floatEnum == XSValue::DoubleFloatType_Normal) { if (fabs(actValue.fValue.f_float - expValue.fValue.f_float) < fabs(actValue.fValue.f_float)/1000) return true; printf("ACTVALUE_TEST Unexpected XSValue for datatype %s, got %f expected %f\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_float, expValue.fValue.f_float); return false; } else { if (actValue.fValue.f_floatType.f_floatEnum == expValue.fValue.f_floatType.f_floatEnum) return true; printf("ACTVALUE_TEST Unexpected XSValue enum for datatype %s, got %d expected %d\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_floatType.f_floatEnum, expValue.fValue.f_floatType.f_floatEnum); return false; } case XSValue::dt_duration: case XSValue::dt_dateTime: case XSValue::dt_time: case XSValue::dt_date: case XSValue::dt_gYearMonth: case XSValue::dt_gYear: case XSValue::dt_gMonthDay: case XSValue::dt_gDay: case XSValue::dt_gMonth: if (actValue.fValue.f_datetime.f_year == expValue.fValue.f_datetime.f_year && actValue.fValue.f_datetime.f_month == expValue.fValue.f_datetime.f_month && actValue.fValue.f_datetime.f_day == expValue.fValue.f_datetime.f_day && actValue.fValue.f_datetime.f_hour == expValue.fValue.f_datetime.f_hour && actValue.fValue.f_datetime.f_min == expValue.fValue.f_datetime.f_min && actValue.fValue.f_datetime.f_second == expValue.fValue.f_datetime.f_second && (fabs(actValue.fValue.f_datetime.f_milisec - expValue.fValue.f_datetime.f_milisec) < 0.01)) return true; printf("ACTVALUE_TEST Unexpected %s XSValue\n", StrX(getDataTypeString(datatype)).localForm()); printf(" Actual year = %d, month = %d, day = %d, hour = %d, min = %d, second = %d, milisec = %f\n", actValue.fValue.f_datetime.f_year, actValue.fValue.f_datetime.f_month, actValue.fValue.f_datetime.f_day, actValue.fValue.f_datetime.f_hour, actValue.fValue.f_datetime.f_min, actValue.fValue.f_datetime.f_second, actValue.fValue.f_datetime.f_milisec); printf(" Expect year = %d, month = %d, day = %d, hour = %d, min = %d, second = %d, milisec = %f\n", expValue.fValue.f_datetime.f_year, expValue.fValue.f_datetime.f_month, expValue.fValue.f_datetime.f_day, expValue.fValue.f_datetime.f_hour, expValue.fValue.f_datetime.f_min, expValue.fValue.f_datetime.f_second, expValue.fValue.f_datetime.f_milisec); return false; case XSValue::dt_hexBinary: // in the tests in this file the hexBinary data is always 2 long... if (actValue.fValue.f_byteVal[0] == expValue.fValue.f_byteVal[0] && actValue.fValue.f_byteVal[1] == expValue.fValue.f_byteVal[1]) return true; printf("ACTVALUE_TEST Unexpected hexBinary value\n"); printf(" Actual Value = %x:%x\n",actValue.fValue.f_byteVal[0],actValue.fValue.f_byteVal[1]); printf(" Expect Value = %x:%x\n",expValue.fValue.f_byteVal[0],expValue.fValue.f_byteVal[1]); return false; case XSValue::dt_base64Binary: // in the tests in this file the base64Binary data is always 9 long (XMLByte[9]) // however, a zero byte is used to indicate when the smaller data stream is empty { for (unsigned int i=0; i<9; i++) { if (!expValue.fValue.f_byteVal[i]) return true; if (actValue.fValue.f_byteVal[i] != expValue.fValue.f_byteVal[i]) { printf("ACTVALUE_TEST Unexpected base64Binary value for byte %d\n", i); printf(" Actual Value = %x\n",actValue.fValue.f_byteVal[i]); printf(" Expect Value = %x\n",expValue.fValue.f_byteVal[i]); return false; } } return true; } case XSValue::dt_string: case XSValue::dt_anyURI: case XSValue::dt_QName: case XSValue::dt_NOTATION: case XSValue::dt_normalizedString: case XSValue::dt_token: case XSValue::dt_language: case XSValue::dt_NMTOKEN: case XSValue::dt_NMTOKENS: case XSValue::dt_Name: case XSValue::dt_NCName: case XSValue::dt_ID: case XSValue::dt_IDREF: case XSValue::dt_IDREFS: case XSValue::dt_ENTITY: case XSValue::dt_ENTITIES: printf("ACTVALUE_TEST no Actual Value for datatype %s\n", StrX(getDataTypeString(datatype)).localForm()); return false; case XSValue::dt_integer: case XSValue::dt_nonPositiveInteger: case XSValue::dt_negativeInteger: case XSValue::dt_long: if (actValue.fValue.f_long == expValue.fValue.f_long) return true; printf("ACTVALUE_TEST Unexpected %s XSValue, got %d expected %d\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_long, expValue.fValue.f_long); return false; case XSValue::dt_int: if (actValue.fValue.f_int == expValue.fValue.f_int) return true; printf("ACTVALUE_TEST Unexpected dt_int XSValue, got %d expected %d\n", actValue.fValue.f_int, expValue.fValue.f_int); return false; case XSValue::dt_short: if (actValue.fValue.f_short == expValue.fValue.f_short) return true; printf("ACTVALUE_TEST Unexpected dt_short XSValue, got %d expected %d\n", actValue.fValue.f_short, expValue.fValue.f_short); return false; case XSValue::dt_byte: if (actValue.fValue.f_char == expValue.fValue.f_char) return true; printf("ACTVALUE_TEST Unexpected dt_byte XSValue, got %d expected %d\n", actValue.fValue.f_char, expValue.fValue.f_char); return false; case XSValue::dt_nonNegativeInteger: case XSValue::dt_unsignedLong: case XSValue::dt_positiveInteger: if (actValue.fValue.f_ulong == expValue.fValue.f_ulong) return true; printf("ACTVALUE_TEST Unexpected %s XSValue, got %d expected %d\n", StrX(getDataTypeString(datatype)).localForm(), actValue.fValue.f_ulong, expValue.fValue.f_ulong); return false; case XSValue::dt_unsignedInt: if (actValue.fValue.f_uint == expValue.fValue.f_uint) return true; printf("ACTVALUE_TEST Unexpected dt_unsignedIntXSValue, got %d expected %d\n", actValue.fValue.f_uint, expValue.fValue.f_uint); return false; case XSValue::dt_unsignedShort: if (actValue.fValue.f_ushort == expValue.fValue.f_ushort) return true; printf("ACTVALUE_TEST Unexpected dt_unsignedShort XSValue, got %d expected %d\n", actValue.fValue.f_ushort, expValue.fValue.f_ushort); return false; case XSValue::dt_unsignedByte: if (actValue.fValue.f_uchar == expValue.fValue.f_uchar) return true; printf("ACTVALUE_TEST Unexpected dt_unsignedByte XSValue, got %d expected %d\n", actValue.fValue.f_uchar, expValue.fValue.f_uchar); return false; default: printf("ACTVALUE_TEST Unexpected datatype\n"); return false; } } static char* getStatusString(const XSValue::Status status) { switch (status) { case XSValue::st_Init: return "st_Init"; break; case XSValue::st_NoContent: return "st_NoContent"; break; case XSValue::st_NoCanRep: return "st_NoCanRep"; break; case XSValue::st_NoActVal: return "st_NoActVal"; break; case XSValue::st_NotSupported: return "st_NotSupported"; break; case XSValue::st_CantCreateRegEx: return "st_CantCreateRegEx"; break; case XSValue::st_FOCA0002: return "st_FOCA0002"; break; case XSValue::st_FOCA0001: return "st_FOCA0001"; break; case XSValue::st_FOCA0003: return "st_FOCA0003"; break; case XSValue::st_FODT0003: return "st_FODT0003"; break; case XSValue::st_UnknownType: return "st_UnknownType"; break; default: return "st_UnknownType"; break; } } /** * This is to test methods for XSValue */ #ifdef _DEBUG void VALIDATE_TEST( const char* const data , const XSValue::DataType datatype , bool expRetValid , const XSValue::Status expStatus ) { XSValue::Status myStatus = XSValue::st_Init; bool actRetValid = XSValue::validate( StrX(data).unicodeForm() , datatype , myStatus , XSValue::ver_10 , XMLPlatformUtils::fgMemoryManager); if (actRetValid != expRetValid) { printf("VALIDATE_TEST Validation Fail: data=<%s>, datatype=<%s>, expRetVal=<%d>\n", data, StrX(getDataTypeString(datatype)).localForm(), expRetValid); errSeen = true; } else { if (!expRetValid && expStatus != DONT_CARE && expStatus != myStatus ) { printf("VALIDATE_TEST Context Diff, data=<%s> datatype=<%s>, expStatus=<%s>, actStatus=<%s>\n", data, StrX(getDataTypeString(datatype)).localForm(), getStatusString(expStatus), getStatusString(myStatus)); errSeen = true; } } } #else #define VALIDATE_TEST(data, datatype, expRetValid, expStatus) \ { \ XSValue::Status myStatus = XSValue::st_Init; \ bool actRetValid = XSValue::validate( \ StrX(data).unicodeForm() \ , datatype \ , myStatus \ , XSValue::ver_10 \ , XMLPlatformUtils::fgMemoryManager); \ if (actRetValid != expRetValid) { \ printf("VALIDATE_TEST Validation Fail: \ at line <%d>, data=<%s>, datatype=<%s>, expRetVal=<%d>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm() \ , expRetValid); \ errSeen = true; \ } \ else { \ if (!expRetValid && \ expStatus != DONT_CARE && \ expStatus != myStatus ) { \ printf("VALIDATE_TEST Context Diff, \ at line <%d>, data=<%s> datatype=<%s>, \ expStatus=<%s>, actStatus=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm(), \ getStatusString(expStatus), getStatusString(myStatus)); \ errSeen = true; \ } \ } \ } #endif #ifdef _DEBUG void ACTVALUE_TEST( const char* const data , const XSValue::DataType datatype , bool toValidate , bool expRetValue , const XSValue::Status expStatus , const XSValue::XSValue_Data expValue ) { XSValue::Status myStatus = XSValue::st_Init; XSValue* actRetValue = XSValue::getActualValue( StrX(data).unicodeForm() , datatype , myStatus , XSValue::ver_10 , toValidate , XMLPlatformUtils::fgMemoryManager); if (actRetValue) { if (!expRetValue) { printf("ACTVALUE_TEST XSValue returned: data=<%s>, datatype=<%s>\n", data, StrX(getDataTypeString(datatype)).localForm()); errSeen = true; } else if (!compareActualValue(datatype, actRetValue->fData, expValue)) { errSeen = true; } delete actRetValue; } else { if (expRetValue) { printf("ACTVALUE_TEST No XSValue returned, data=<%s>, datatype=<%s>\n" , data, StrX(getDataTypeString(datatype)).localForm()); errSeen = true; } else { if (expStatus != DONT_CARE && expStatus != myStatus ) { printf("ACTVALUE_TEST Context Diff, data=<%s>, datatype=<%s>, expStatus=<%s>, actStatus=<%s>\n" , data, StrX(getDataTypeString(datatype)).localForm(), getStatusString(expStatus), getStatusString(myStatus)); errSeen = true; } } } } #else #define ACTVALUE_TEST(data, datatype, toValidate, expRetValue, expStatus, expValue) \ { \ XSValue::Status myStatus = XSValue::st_Init; \ XSValue* actRetValue = XSValue::getActualValue( \ StrX(data).unicodeForm() \ , datatype \ , myStatus \ , XSValue::ver_10 \ , toValidate \ , XMLPlatformUtils::fgMemoryManager); \ if (actRetValue) { \ if (!expRetValue) { \ printf("ACTVALUE_TEST XSValue returned, \ at line <%d> data=<%s>, datatype=<%s>\n" \ ,__LINE__, data, StrX(getDataTypeString(datatype)).localForm()); \ errSeen = true; \ } \ else if (!compareActualValue(datatype, actRetValue->fData, expValue)) { \ errSeen = true; \ } \ delete actRetValue; \ } \ else { \ if (expRetValue) { \ printf("ACTVALUE_TEST No XSValue returned, \ at line <%d> data=<%s>, datatype=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm()); \ errSeen = true; \ } \ else { \ if (expStatus != DONT_CARE && \ expStatus != myStatus) { \ printf("ACTVALUE_TEST Context Diff, \ at line <%d> data=<%s>, datatype=<%s>, \ expStatus=<%s>, actStatus=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm() \ , getStatusString(expStatus), getStatusString(myStatus)); \ errSeen = true; \ } \ } \ } \ } #endif #ifdef _DEBUG void CANREP_TEST(const char* const data , const XSValue::DataType datatype , bool toValidate , bool expRetCanRep , const char* const toCompare , const XSValue::Status expStatus ) { XSValue::Status myStatus = XSValue::st_Init; XMLCh* actRetCanRep = XSValue::getCanonicalRepresentation( StrX(data).unicodeForm() , datatype , myStatus , XSValue::ver_10 , toValidate , XMLPlatformUtils::fgMemoryManager); if (actRetCanRep) { if (!expRetCanRep) { printf("CANREP_TEST CanRep returned, data=<%s>, datatype=<%s>\n" , data, StrX(getDataTypeString(datatype)).localForm()); XMLPlatformUtils::fgMemoryManager->deallocate(actRetCanRep); errSeen = true; } else { char* actRetCanRep_inchar = XMLString::transcode(actRetCanRep); if (!XMLString::equals(actRetCanRep_inchar, toCompare)) { printf("CANREP_TEST CanRep Diff , data=<%s>, datatype=<%s>, actCanRep=<%s>, toCompare=<%s>\n" , data, StrX(getDataTypeString(datatype)).localForm(), actRetCanRep_inchar, toCompare); errSeen = true; } XMLPlatformUtils::fgMemoryManager->deallocate(actRetCanRep); XMLString::release(&actRetCanRep_inchar); } } else { if (expRetCanRep) { printf("CANREP_TEST No CanRep returned, data=<%s>, datatype=<%s>\n" , data, StrX(getDataTypeString(datatype)).localForm()); errSeen = true; } else { if (expStatus != DONT_CARE && expStatus != myStatus ) { printf("CANREP_TEST Context Diff, data=<%s>, datatype=<%s>\n expStatus=<%s>, actStatus=<%s>\n" , data, StrX(getDataTypeString(datatype)).localForm(), getStatusString(expStatus), getStatusString(myStatus)); errSeen = true; } } } } #else #define CANREP_TEST(data, datatype, toValidate, expRetCanRep, toCompare, expStatus) \ { \ XSValue::Status myStatus = XSValue::st_Init; \ XMLCh* actRetCanRep = XSValue::getCanonicalRepresentation( \ StrX(data).unicodeForm() \ , datatype \ , myStatus \ , XSValue::ver_10 \ , toValidate \ , XMLPlatformUtils::fgMemoryManager); \ if (actRetCanRep) { \ if (!expRetCanRep) { \ printf("CANREP_TEST CanRep returned: \ at line <%d> data=<%s>, datatype=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm()); \ XMLPlatformUtils::fgMemoryManager->deallocate(actRetCanRep); \ errSeen = true; \ } \ else { \ char* actRetCanRep_inchar = XMLString::transcode(actRetCanRep); \ if (!XMLString::equals(actRetCanRep_inchar, toCompare)) { \ printf("CANREP_TEST CanRep Diff \ , at line <%d> data=<%s>, datatype=<%s>, \ actCanRep=<%s>, toCompare=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm() \ , actRetCanRep_inchar, toCompare); \ errSeen = true; \ } \ XMLPlatformUtils::fgMemoryManager->deallocate(actRetCanRep); \ XMLString::release(&actRetCanRep_inchar); \ } \ } \ else { \ if (expRetCanRep){ \ printf("CANREP_TEST No CanRep returned, \ at line <%d> data=<%s>, datatype=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm()); \ errSeen = true; \ } \ else { \ if (expStatus != myStatus) { \ printf("CANREP_TEST Context Diff, \ at line <%d> data=<%s>, datatype=<%s>\n \ expStatus=<%s>, actStatus=<%s>\n" \ , __LINE__, data, StrX(getDataTypeString(datatype)).localForm() \ , getStatusString(expStatus), getStatusString(myStatus)); \ errSeen = true; \ } \ } \ } \ } #endif #ifdef _DEBUG void DATATYPE_TEST( const XMLCh* const dt_String , const XSValue::DataType expDataType ) { XSValue::DataType actDataType = XSValue::getDataType(dt_String); if (actDataType != expDataType) { char* dt_str = XMLString::transcode(dt_String); printf("DATATYPE_TEST Fails: data=<%s>, actDataType=<%d>, expDataType=<%d>\n", dt_str, actDataType, expDataType); XMLString::release(&dt_str); errSeen = true; } } #else #define DATATYPE_TEST(dt_String, expDataType) \ { \ XSValue::DataType actDataType = XSValue::getDataType(dt_String); \ if (actDataType != expDataType) \ { \ char* dt_str = XMLString::transcode(dt_String); \ printf("DATATYPE_TEST Fails: data=<%s>, actDataType=<%d>, expDataType=<%d>\n", \ dt_str, actDataType, expDataType); \ XMLString::release(&dt_str); \ errSeen = true; \ } \ } #endif void testNoActVal(const char* const data , const XSValue::DataType datatype , const XSValue::Status expStatus) { XSValue::Status ret_Status = XSValue::st_Init; XSValue* actVal = XSValue::getActualValue(StrX(data).unicodeForm(), datatype, ret_Status); if (actVal) { printf("testNoActVal fails, data=<%s>\n", data); delete actVal; errSeen=true; return; } if (ret_Status != expStatus) { printf("testNoActVal fails, data=<%s> retStatus=<%s> expStatus=<%s>\n", data , getStatusString(ret_Status) , getStatusString(expStatus)); errSeen=true; } } void testNoCanRep(const char* const data , const XSValue::DataType datatype , const XSValue::Status expStatus) { XSValue::Status ret_Status = XSValue::st_Init; XMLCh* canRep = XSValue::getCanonicalRepresentation(StrX(data).unicodeForm(), datatype, ret_Status); if (canRep) { printf("testNoCanRep fails, data=<%s>\n", data); delete canRep; errSeen=true; return; } if (ret_Status != expStatus) { printf("testNoCanRep fails, data=<%s> retStatus=<%s> expStatus=<%s>\n", data , getStatusString(ret_Status) , getStatusString(expStatus)); errSeen=true; } } /*** * Test cases ***/ void test_dt_decimal() { const XSValue::DataType dt = XSValue::dt_decimal; bool toValidate = true; const char lex_v_ran_v_1[]=" 1234.567 \n"; const char lex_v_ran64_v_1[]="18446744073709551615.999"; const char lex_v_ran64_v_2[]="999.18446744073709551615"; const char lex_v_ran64_iv_1[]="18446744073709551616.999"; const char lex_v_ran64_iv_2[]="999.18446744073709551616"; const char lex_v_ran32_v_1[]="4294967295.999"; const char lex_v_ran32_v_2[]="999.4294967295"; const char lex_v_ran32_iv_1[]="4294967296.999"; const char lex_v_ran32_iv_2[]="999.4294967296"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234.56.789"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_double = (double)1234.567; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_1; act_v_ran64_v_1.fValue.f_double = (double)18446744073709551615.999; XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_double = (double)999.18446744073709551615; //XSValue::XSValue_Data act_v_ran64_iv_1;="18446744073709551616.999"; //XSValue::XSValue_Data act_v_ran64_iv_2;="999.18446744073709551616"; #endif XSValue::XSValue_Data act_v_ran32_v_1; act_v_ran32_v_1.fValue.f_double = (double)4294967295.999; XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_double = (double)999.4294967295; //XSValue::XSValue_Data act_v_ran32_iv_1;="4294967296.999"; //XSValue::XSValue_Data act_v_ran32_iv_2;="999.4294967296"; /*** * 3.2.3.2 Canonical representation * * The canonical representation for decimal is defined by prohibiting certain options from the Lexical * representation (§3.2.3.1). Specifically, * 1. the preceding optional "+" sign is prohibited. * 2. The decimal point is required. * 3. Leading and trailing zeroes are prohibited subject to the following: * there must be at least one digit to the right and * to the left of the decimal point which may be a zero. ***/ const char data_rawstr_1[]=" -123.45 \n"; const char data_canrep_1[]="-123.45"; const char data_rawstr_2[]="+123.45"; const char data_canrep_2[]="123.45"; const char data_rawstr_3[]="12345"; const char data_canrep_3[]="12345.0"; const char data_rawstr_4[]="000123.45"; const char data_canrep_4[]="123.45"; const char data_rawstr_5[]="123.45000"; const char data_canrep_5[]="123.45"; const char data_rawstr_6[]="00.12345"; const char data_canrep_6[]="0.12345"; const char data_rawstr_7[]="123.00"; const char data_canrep_7[]="123.0"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_1 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); //ACTVALUE_TEST(lex_v_ran64_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0001); //ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0001); #else ACTVALUE_TEST(lex_v_ran32_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); //ACTVALUE_TEST(lex_v_ran32_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0001); //ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0001); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, DONT_CARE); CANREP_TEST(data_rawstr_3, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_3, DONT_CARE); CANREP_TEST(data_rawstr_4, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_4, DONT_CARE); CANREP_TEST(data_rawstr_5, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_5, DONT_CARE); CANREP_TEST(data_rawstr_6, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_6, DONT_CARE); CANREP_TEST(data_rawstr_7, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_7, DONT_CARE); CANREP_TEST(lex_v_ran64_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_1, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_1, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } /*** * FLT_EPSILON 1.192092896e-07F * FLT_MIN 1.175494351e-38F * FLT_MAX 3.402823466e+38F ***/ void test_dt_float() { const XSValue::DataType dt = XSValue::dt_float; bool toValidate = true; const char lex_v_ran_v_0[]=" 1234.e+10 \n"; const char lex_v_ran_v_1[]="+3.402823466e+38"; const char lex_v_ran_v_2[]="-3.402823466e+38"; const char lex_v_ran_v_3[]="+1.175494351e-38"; const char lex_v_ran_v_4[]="-1.175494351e-38"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_float = (float)1234.e+10; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_float = (float)+3.402823466e+38; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_float = (float)-3.402823466e+38; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_float = (float)+1.175494351e-38; XSValue::XSValue_Data act_v_ran_v_4; act_v_ran_v_4.fValue.f_float = (float)-1.175494351e-38; const char lex_v_ran_iv_1[]="+3.402823466e+39"; const char lex_v_ran_iv_2[]="-3.402823466e+39"; const char lex_v_ran_iv_3[]="+1.175494351e-39"; const char lex_v_ran_iv_4[]="-1.175494351e-39"; XSValue::XSValue_Data lex_iv_ran_v_1; lex_iv_ran_v_1.fValue.f_float = (float)0.0; lex_iv_ran_v_1.fValue.f_floatType.f_floatEnum = XSValue::DoubleFloatType_PosINF; XSValue::XSValue_Data lex_iv_ran_v_2; lex_iv_ran_v_2.fValue.f_float = (float)0.0; lex_iv_ran_v_2.fValue.f_floatType.f_floatEnum = XSValue::DoubleFloatType_NegINF; XSValue::XSValue_Data lex_iv_ran_v_3; lex_iv_ran_v_3.fValue.f_float = (float)0.0; lex_iv_ran_v_3.fValue.f_floatType.f_floatEnum = XSValue::DoubleFloatType_Zero; XSValue::XSValue_Data lex_iv_ran_v_4; lex_iv_ran_v_4.fValue.f_float = (float)0.0; lex_iv_ran_v_4.fValue.f_floatType.f_floatEnum = XSValue::DoubleFloatType_Zero; const char lex_v_ran_iv_1_canrep[]="INF"; // 3.402823466E39"; const char lex_v_ran_iv_2_canrep[]="-INF"; //-3.402823466E39"; const char lex_v_ran_iv_3_canrep[]="0"; // 1.175494351E-39"; const char lex_v_ran_iv_4_canrep[]="0"; //-1.175494351E-39"; const char lex_iv_1[]="12x.e+10"; const char lex_iv_2[]="12.e+1x"; /*** * 3.2.4.2 Canonical representation * * The canonical representation for float is defined by prohibiting certain options from the Lexical * representation (§3.2.4.1). * Specifically, * 1. the exponent must be indicated by "E". * 2. Leading zeroes and the preceding optional "+" sign are prohibited in the exponent. * 3. For the mantissa, the preceding optional "+" sign is prohibited and the decimal point is required. * Leading and trailing zeroes are prohibited subject to the following: * number representations must be normalized such that there is a single digit to the left of the decimal point * and at least a single digit to the right of the decimal point. * ***/ const char data_rawstr_1[]=" -123.45 \n"; const char data_canrep_1[]="-1.2345E2"; const char data_rawstr_2[]="+123.45"; const char data_canrep_2[]="1.2345E2"; const char data_rawstr_3[]="+123.45e+0012"; const char data_canrep_3[]="1.2345E14"; const char data_rawstr_4[]="+100.000e2"; const char data_canrep_4[]="1.0E4"; const char data_rawstr_5[]="00100.23e2"; const char data_canrep_5[]="1.0023E4"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, range valid VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_3 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_4 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, range invalid VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_3 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_4 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // lexical valid, range valid ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); ACTVALUE_TEST(lex_v_ran_v_4, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_4); // lexical valid, range invalid ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_1); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_3); ACTVALUE_TEST(lex_v_ran_iv_4, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_4); // lexical invalid ACTVALUE_TEST(lex_iv_1 , dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2 , dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // lexical valid, range valid CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, DONT_CARE); CANREP_TEST(data_rawstr_3, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_3, DONT_CARE); CANREP_TEST(data_rawstr_4, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_4, DONT_CARE); CANREP_TEST(data_rawstr_5, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_5, DONT_CARE); // lexical invalid CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); // lexical valid, range invalid (however XML4C ignores that) CANREP_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_3, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_3_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_4, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_4_canrep, DONT_CARE); } } /*** DBL_EPSILON 2.2204460492503131e-016 DBL_MAX 1.7976931348623158e+308 DBL_MIN 2.2250738585072014e-308 ***/ void test_dt_double() { const XSValue::DataType dt = XSValue::dt_double; bool toValidate = true; const char lex_v_ran_v_0[]=" 1234.e+10 \n"; const char lex_v_ran_v_1[]="+1.7976931348623158e+308"; const char lex_v_ran_v_2[]="-1.7976931348623158e+308"; const char lex_v_ran_v_3[]="+2.2250738585072014e-308"; const char lex_v_ran_v_4[]="-2.2250738585072014e-308"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_double = (double)1234.e+10; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_double = (double)+1.7976931348623158e+308; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_double = (double)-1.7976931348623158e+308; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_double = (double)+2.2250738585072014e-308; XSValue::XSValue_Data act_v_ran_v_4; act_v_ran_v_4.fValue.f_double = (double)-2.2250738585072014e-308; const char lex_v_ran_iv_1[]="+1.7976931348623158e+309"; const char lex_v_ran_iv_2[]="-1.7976931348623158e+309"; // on linux, hp, aix, the representable range is around e-324 // or e-325, using e-329 to gain consistent result on all // platforms const char lex_v_ran_iv_3[]="+2.2250738585072014e-329"; const char lex_v_ran_iv_4[]="-2.2250738585072014e-329"; const char lex_v_ran_iv_1_canrep[]="INF"; // 1.7976931348623158E309"; const char lex_v_ran_iv_2_canrep[]="-INF"; //-1.7976931348623158E309"; const char lex_v_ran_iv_3_canrep[]="0"; // 2.2250738585072014E-329"; const char lex_v_ran_iv_4_canrep[]="0"; //-2.2250738585072014E-329"; XSValue::XSValue_Data lex_iv_ran_v_1; lex_iv_ran_v_1.fValue.f_double = (double)0.0; lex_iv_ran_v_1.fValue.f_doubleType.f_doubleEnum = XSValue::DoubleFloatType_PosINF; XSValue::XSValue_Data lex_iv_ran_v_2; lex_iv_ran_v_2.fValue.f_double = (double)0.0; lex_iv_ran_v_2.fValue.f_doubleType.f_doubleEnum = XSValue::DoubleFloatType_NegINF; XSValue::XSValue_Data lex_iv_ran_v_3; lex_iv_ran_v_3.fValue.f_double = (double)0.0; lex_iv_ran_v_3.fValue.f_doubleType.f_doubleEnum = XSValue::DoubleFloatType_Zero; XSValue::XSValue_Data lex_iv_ran_v_4; lex_iv_ran_v_4.fValue.f_double = (double)0.0; lex_iv_ran_v_4.fValue.f_doubleType.f_doubleEnum = XSValue::DoubleFloatType_Zero; const char lex_iv_1[]="12x.e+10"; const char lex_iv_2[]="12.e+1x"; /*** * 3.2.5.2 Canonical representation * * The canonical representation for float is defined by prohibiting certain options from the Lexical * representation (§3.2.5.1). * Specifically, * 1. the exponent must be indicated by "E". * 2. Leading zeroes and the preceding optional "+" sign are prohibited in the exponent. * 3. For the mantissa, the preceding optional "+" sign is prohibited and the decimal point is required. * Leading and trailing zeroes are prohibited subject to the following: * number representations must be normalized such that there is a single digit to the left of the decimal point * and at least a single digit to the right of the decimal point. * ***/ const char data_rawstr_1[]=" -123.45 \n"; const char data_canrep_1[]="-1.2345E2"; const char data_rawstr_2[]="+123.45"; const char data_canrep_2[]="1.2345E2"; const char data_rawstr_3[]="+123.45e+0012"; const char data_canrep_3[]="1.2345E14"; const char data_rawstr_4[]="+100.000e2"; const char data_canrep_4[]="1.0E4"; const char data_rawstr_5[]="00100.23e2"; const char data_canrep_5[]="1.0023E4"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, range valid VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_3 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_4 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, range invalid however XML4C converts to INF / ZERO VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_3 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_4 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // lexical valid, range valid ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); ACTVALUE_TEST(lex_v_ran_v_4, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_4); // lexical valid, range invalid ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_1); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_3); ACTVALUE_TEST(lex_v_ran_iv_4, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, lex_iv_ran_v_4); // lexical invalid ACTVALUE_TEST(lex_iv_1 , dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2 , dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // lexical valid, range valid CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, DONT_CARE); CANREP_TEST(data_rawstr_3, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_3, DONT_CARE); CANREP_TEST(data_rawstr_4, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_4, DONT_CARE); CANREP_TEST(data_rawstr_5, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_5, DONT_CARE); // lexical invalid CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); // lexical valid, range invalid (XML4C doesn't treat as invalid) CANREP_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_3, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_3_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_4, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_iv_4_canrep, DONT_CARE); } } /*** * 9223372036854775807 * -9223372036854775808 * 2147483647 * -2147483648 ***/ void test_dt_integer() { const XSValue::DataType dt = XSValue::dt_integer; bool toValidate = true; const char lex_v_ran_v_1[]=" 1234 \n"; const char lex_v_ran64_v_1[]="+9223372036854775807"; const char lex_v_ran64_v_2[]="-9223372036854775808"; const char lex_v_ran64_iv_1[]="+9223372036854775808"; const char lex_v_ran64_iv_2[]="-9223372036854775809"; const char lex_v_ran32_v_1[]="+2147483647"; const char lex_v_ran32_v_2[]="-2147483648"; const char lex_v_ran32_iv_1[]="+2147483648"; const char lex_v_ran32_iv_2[]="-2147483649"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_long = (long)1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_1; act_v_ran64_v_1.fValue.f_long = (long)+9223372036854775807; XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_long = (long)-9223372036854775808; #endif XSValue::XSValue_Data act_v_ran32_v_1; act_v_ran32_v_1.fValue.f_long = (long)+2147483647; XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_long = -(long)2147483648L; const char lex_v_ran64_v_1_canrep[]="9223372036854775807"; const char lex_v_ran64_v_2_canrep[]="-9223372036854775808"; const char lex_v_ran64_iv_1_canrep[]="9223372036854775808"; const char lex_v_ran64_iv_2_canrep[]="-9223372036854775809"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.13.2 Canonical representation * * The canonical representation for integer is defined by prohibiting certain options from the Lexical * representation (§3.3.13.1). Specifically, * 1. the preceding optional "+" sign is prohibited and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_1 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_1); #else ACTVALUE_TEST(lex_v_ran32_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_1); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran64_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_nonPositiveInteger() { const XSValue::DataType dt = XSValue::dt_nonPositiveInteger; bool toValidate = true; const char lex_v_ran_v_1[]=" -1234 \n"; const char lex_v_ran_iv_1[]="+1"; const char lex_v_ran64_v_2[]="-9223372036854775808"; const char lex_v_ran64_iv_2[]="-9223372036854775809"; const char lex_v_ran32_v_2[]="-2147483648"; const char lex_v_ran32_iv_2[]="-2147483649"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_long = (long)-1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_long = (long)-9223372036854775808; #endif XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_long = -(long)2147483648L; const char lex_v_ran64_v_2_canrep[]="-9223372036854775808"; const char lex_v_ran64_iv_2_canrep[]="-9223372036854775809"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.14.2 Canonical representation * * The canonical representation for nonPositiveInteger is defined by prohibiting certain options from the * Lexical representation (§3.3.14.1). Specifically, * 1. the sign must be omitted for token "0" and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" 0 \n"; const char data_canrep_1[]="0"; const char data_rawstr_2[]="-00012345"; const char data_canrep_2[]="-12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_2); #else ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_2); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_negativeInteger() { const XSValue::DataType dt = XSValue::dt_negativeInteger; bool toValidate = true; const char lex_v_ran_v_1[]=" -1234 \n"; const char lex_v_ran_iv_1[]="0"; const char lex_v_ran64_v_2[]="-9223372036854775808"; const char lex_v_ran64_iv_2[]="-9223372036854775809"; const char lex_v_ran32_v_2[]="-2147483648"; const char lex_v_ran32_iv_2[]="-2147483649"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_long = (long)-1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_long = (long)-9223372036854775808; #endif XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_long = -(long)2147483648L; const char lex_v_ran64_v_2_canrep[]="-9223372036854775808"; const char lex_v_ran64_iv_2_canrep[]="-9223372036854775809"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.15.2 Canonical representation * * The canonical representation for negativeInteger is defined by prohibiting certain options * from the Lexical representation (§3.3.15.1). Specifically, * 1. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" -00012345 \n"; const char data_canrep_1[]="-12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_2); #else ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_2); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_long() { const XSValue::DataType dt = XSValue::dt_long; bool toValidate = true; const char lex_v_ran_v_1[]=" 1234 \n"; const char lex_v_ran64_v_1[]="+9223372036854775807"; const char lex_v_ran64_v_2[]="-9223372036854775808"; const char lex_v_ran64_iv_1[]="+9223372036854775808"; const char lex_v_ran64_iv_2[]="-9223372036854775809"; const char lex_v_ran32_v_1[]="+2147483647"; const char lex_v_ran32_v_2[]="-2147483648"; const char lex_v_ran32_iv_1[]="+2147483648"; const char lex_v_ran32_iv_2[]="-2147483649"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_long = (long)1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_1; act_v_ran64_v_1.fValue.f_long = (long)+9223372036854775807; XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_long = (long)-9223372036854775808; #endif XSValue::XSValue_Data act_v_ran32_v_1; act_v_ran32_v_1.fValue.f_long = (long)+2147483647; XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_long = -(long)2147483648L; const char lex_v_ran64_v_1_canrep[]="9223372036854775807"; const char lex_v_ran64_v_2_canrep[]="-9223372036854775808"; const char lex_v_ran64_iv_1_canrep[]="9223372036854775808"; const char lex_v_ran64_iv_2_canrep[]="-9223372036854775809"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.16.2 Canonical representation * * The canonical representation for long is defined by prohibiting certain options from the * Lexical representation (§3.3.16.1). Specifically, * 1. the the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran64_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_1 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_1); #else ACTVALUE_TEST(lex_v_ran32_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_1); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran64_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran64_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran64_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran64_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); } void test_dt_int() { const XSValue::DataType dt = XSValue::dt_int; bool toValidate = true; const char lex_v_ran_v_0[]=" 1234 \n"; const char lex_v_ran_v_1[]="+2147483647"; const char lex_v_ran_v_2[]="-2147483648"; const char lex_v_ran_iv_1[]="+2147483648"; const char lex_v_ran_iv_2[]="-2147483649"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_int = (int)1234; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_int = (int)+2147483647; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_int = -(int)2147483648; const char lex_v_ran_v_1_canrep[]="2147483647"; const char lex_v_ran_v_2_canrep[]="-2147483648"; const char lex_v_ran_iv_1_canrep[]="2147483648"; const char lex_v_ran_iv_2_canrep[]="-2147483649"; const char lex_iv_1[]="1234.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.17.2 Canonical representation * * The canonical representation for int is defined by prohibiting certain options from the * Lexical representation (§3.3.17.1). Specifically, * 1. the the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); } // 32767 // -32768 void test_dt_short() { const XSValue::DataType dt = XSValue::dt_short; bool toValidate = true; const char lex_v_ran_v_0[]=" 1234 \n"; const char lex_v_ran_v_1[]="+32767"; const char lex_v_ran_v_2[]="-32768"; const char lex_v_ran_iv_1[]="+32768"; const char lex_v_ran_iv_2[]="-32769"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_short = (short)1234; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_short = (short)+32767; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_short = (short)-32768; const char lex_v_ran_v_1_canrep[]="32767"; const char lex_v_ran_v_2_canrep[]="-32768"; const char lex_v_ran_iv_1_canrep[]="32768"; const char lex_v_ran_iv_2_canrep[]="-32769"; const char lex_iv_1[]="1234.456"; const char lex_iv_2[]="1234b56"; /*** * * 3.3.18.2 Canonical representation * * The canonical representation for short is defined by prohibiting certain options from the * Lexical representation (§3.3.18.1). Specifically, * 1. the the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); } //127 //-128 void test_dt_byte() { const XSValue::DataType dt = XSValue::dt_byte; bool toValidate = true; const char lex_v_ran_v_0[]=" 12 \n"; const char lex_v_ran_v_1[]="+127"; const char lex_v_ran_v_2[]="-128"; const char lex_v_ran_iv_1[]="+128"; const char lex_v_ran_iv_2[]="-129"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_char = (char)12; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_char = (char)+127; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_char = (char)-128; const char lex_v_ran_v_1_canrep[]="127"; const char lex_v_ran_v_2_canrep[]="-128"; const char lex_v_ran_iv_1_canrep[]="128"; const char lex_v_ran_iv_2_canrep[]="-129"; const char lex_iv_1[]="1234.456"; const char lex_iv_2[]="1234b56"; /*** * * 3.3.19.2 Canonical representation * * The canonical representation for byte is defined by prohibiting certain options from the * Lexical representation (§3.3.19.1). Specifically, * 1. the the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +123 \n"; const char data_canrep_1[]="123"; const char data_rawstr_2[]="000123"; const char data_canrep_2[]="123"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); } void test_dt_nonNegativeInteger() { const XSValue::DataType dt = XSValue::dt_nonNegativeInteger; bool toValidate = true; const char lex_v_ran_v_1[]=" 1234 \n"; const char lex_v_ran_iv_1[]="-1"; const char lex_v_ran64_v_2[]="+18446744073709551615"; const char lex_v_ran64_iv_2[]="+18446744073709551616"; const char lex_v_ran32_v_2[]="4294967295"; const char lex_v_ran32_iv_2[]="4294967296"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_ulong = (unsigned long)1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_ulong = (unsigned long)+18446744073709551615; #endif XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_ulong = (unsigned long)4294967295; const char lex_v_ran64_v_2_canrep[]="18446744073709551615"; const char lex_v_ran64_iv_2_canrep[]="18446744073709551616"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.20.2 Canonical representation * * The canonical representation for nonNegativeInteger is defined by prohibiting certain options from the * Lexical representation (§3.3.20.1). Specifically, * 1. the the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" 0 \n"; const char data_canrep_1[]="0"; const char data_rawstr_2[]="+00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_2); #else ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_2); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } //18446744073709551615 // 4294967295 void test_dt_unsignedLong() { const XSValue::DataType dt = XSValue::dt_unsignedLong; bool toValidate = true; const char lex_v_ran_v_1[]=" 1234 \n"; const char lex_v_ran64_v_1[]="+18446744073709551615"; const char lex_v_ran64_v_2[]="0"; const char lex_v_ran64_iv_1[]="+18446744073709551616"; const char lex_v_ran64_iv_2[]="-1"; const char lex_v_ran32_v_1[]="+4294967295"; const char lex_v_ran32_v_2[]="0"; const char lex_v_ran32_iv_1[]="4294967296"; const char lex_v_ran32_iv_2[]="-1"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_ulong = (unsigned long)1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_1; act_v_ran64_v_1.fValue.f_ulong = (unsigned long)+18446744073709551615; XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_ulong = (unsigned long)0; #endif XSValue::XSValue_Data act_v_ran32_v_1; act_v_ran32_v_1.fValue.f_ulong = (unsigned long)+4294967295; XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_ulong = (unsigned long)0; const char lex_v_ran64_v_1_canrep[]="18446744073709551615"; const char lex_v_ran64_v_2_canrep[]="0"; const char lex_v_ran64_iv_1_canrep[]="18446744073709551616"; const char lex_v_ran64_iv_2_canrep[]="-1"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.16.2 Canonical representation * * The canonical representation for long is defined by prohibiting certain options from the * Lexical representation (§3.3.16.1). Specifically, * 1. the the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran64_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_1 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_1); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran64_v_1); #else ACTVALUE_TEST(lex_v_ran32_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_1); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran64_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran64_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran64_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran64_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); } //4294967295 void test_dt_unsignedInt() { const XSValue::DataType dt = XSValue::dt_unsignedInt; bool toValidate = true; const char lex_v_ran_v_0[]=" 1234 \n"; const char lex_v_ran_v_1[]="+4294967295"; const char lex_v_ran_v_2[]="0"; const char lex_v_ran_iv_1[]="4294967296"; const char lex_v_ran_iv_2[]="-1"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_uint = (unsigned int)1234; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_uint = (unsigned int)+4294967295; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_uint = (unsigned int)0; const char lex_v_ran_v_1_canrep[]="4294967295"; const char lex_v_ran_v_2_canrep[]="0"; const char lex_v_ran_iv_1_canrep[]="4294967296"; const char lex_v_ran_iv_2_canrep[]="-1"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.22.2 Canonical representation * * The canonical representation for unsignedInt is defined by prohibiting certain options from the * Lexical representation (§3.3.22.1). Specifically, * leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); } //65535 void test_dt_unsignedShort() { const XSValue::DataType dt = XSValue::dt_unsignedShort; bool toValidate = true; const char lex_v_ran_v_0[]=" 1234 \n"; const char lex_v_ran_v_1[]="+65535"; const char lex_v_ran_v_2[]="0"; const char lex_v_ran_iv_1[]="+65536"; const char lex_v_ran_iv_2[]="-1"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_ushort = (unsigned short)1234; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_ushort = (unsigned short)+65535; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_ushort = (unsigned short)0; const char lex_v_ran_v_1_canrep[]="65535"; const char lex_v_ran_v_2_canrep[]="0"; const char lex_v_ran_iv_1_canrep[]="65536"; const char lex_v_ran_iv_2_canrep[]="-1"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.23.2 Canonical representation * * The canonical representation for unsignedShort is defined by prohibiting certain options from the * Lexical representation (§3.3.23.1). Specifically, * 1. the leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +12345 \n"; const char data_canrep_1[]="12345"; const char data_rawstr_2[]="00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); } // 255 void test_dt_unsignedByte() { const XSValue::DataType dt = XSValue::dt_unsignedByte; bool toValidate = true; const char lex_v_ran_v_0[]=" 123 \n"; const char lex_v_ran_v_1[]="+255"; const char lex_v_ran_v_2[]="0"; const char lex_v_ran_iv_1[]="+256"; const char lex_v_ran_iv_2[]="-1"; XSValue::XSValue_Data act_v_ran_v_0; act_v_ran_v_0.fValue.f_uchar = (unsigned char)123; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_uchar = (unsigned char)+255; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_uchar = (unsigned char)0; const char lex_v_ran_v_1_canrep[]="255"; const char lex_v_ran_v_2_canrep[]="0"; const char lex_v_ran_iv_1_canrep[]="256"; const char lex_v_ran_iv_2_canrep[]="-1"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.24.2 Canonical representation * * The canonical representation for unsignedByte is defined by prohibiting certain options from the * Lexical representation (§3.3.24.1). Specifically, * 1. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +123 \n"; const char data_canrep_1[]="123"; const char data_rawstr_2[]="000123"; const char data_canrep_2[]="123"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid false st_FOCA0002 * lexical invalid false st_FOCA0002 * ***/ // lexical valid, valid range VALIDATE_TEST(lex_v_ran_v_0 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical valid, invalid range VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_0, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_ran_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_v_ran_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_0); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid 0 st_FOCA0002 * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran_v_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } //validation on CANREP_TEST(lex_v_ran_iv_1, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_v_ran_iv_2, dt, true, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); //validation off CANREP_TEST(lex_v_ran_iv_1, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_1_canrep, DONT_CARE); CANREP_TEST(lex_v_ran_iv_2, dt, false, EXP_RET_CANREP_TRUE, lex_v_ran_iv_2_canrep, DONT_CARE); } void test_dt_positiveInteger() { const XSValue::DataType dt = XSValue::dt_positiveInteger; bool toValidate = true; const char lex_v_ran_v_1[]=" 1234 \n"; const char lex_v_ran_iv_1[]="0"; const char lex_v_ran64_v_2[]="+18446744073709551615"; const char lex_v_ran64_iv_2[]="+18446744073709551616"; const char lex_v_ran32_v_2[]="4294967295"; const char lex_v_ran32_iv_2[]="4294967296"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_ulong = (unsigned long)1234; #if defined(XML_BITSTOBUILD_64) XSValue::XSValue_Data act_v_ran64_v_2; act_v_ran64_v_2.fValue.f_ulong = (unsigned long)+18446744073709551615; #endif XSValue::XSValue_Data act_v_ran32_v_2; act_v_ran32_v_2.fValue.f_ulong = (unsigned long)+4294967295; const char lex_v_ran64_v_2_canrep[]="18446744073709551615"; const char lex_v_ran64_iv_2_canrep[]="18446744073709551616"; const char lex_iv_1[]="12b34.456"; const char lex_iv_2[]="1234b56"; /*** * 3.3.25.2 Canonical representation * * The canonical representation for positiveInteger is defined by prohibiting certain options from the * Lexical representation (§3.3.25.1). Specifically, * 1. the optional "+" sign is prohibited and * 2. leading zeroes are prohibited. * ***/ const char data_rawstr_1[]=" +1 \n"; const char data_canrep_1[]="1"; const char data_rawstr_2[]="+00012345"; const char data_canrep_2[]="12345"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid * range valid true n/a * range invalid n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_ran_v_1 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_v_ran64_v_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_ran64_iv_2 , dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2 , dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XSValue n/a * range invalid 0 st_Unpresentable * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; ACTVALUE_TEST(lex_v_ran_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); #if defined(XML_BITSTOBUILD_64) ACTVALUE_TEST(lex_v_ran64_v_2 , dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran64_v_2); ACTVALUE_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran64_v_2); #else ACTVALUE_TEST(lex_v_ran32_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran32_v_2); ACTVALUE_TEST(lex_v_ran32_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0003, act_v_ran32_v_2); #endif ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran32_v_2); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid * range valid XMLCh n/a * range invalid n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j)? true : false; CANREP_TEST(data_rawstr_1, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_1, DONT_CARE); CANREP_TEST(data_rawstr_2, dt, toValidate, EXP_RET_CANREP_TRUE, data_canrep_2, DONT_CARE); CANREP_TEST(lex_v_ran64_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_v_2_canrep, DONT_CARE); CANREP_TEST(lex_v_ran64_iv_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_ran64_iv_2_canrep, DONT_CARE); CANREP_TEST(lex_iv_1 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2 , dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_boolean() { const XSValue::DataType dt = XSValue::dt_boolean; bool toValidate = true; const char lex_v_1[]=" 1 \n"; const char lex_v_2[]="0"; const char lex_v_3[]="true"; const char lex_v_4[]="false"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_bool = true; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_bool = false; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_bool = true; XSValue::XSValue_Data act_v_ran_v_4; act_v_ran_v_4.fValue.f_bool = false; const char lex_iv_1[]="2"; const char lex_v_1_canrep[]="true"; const char lex_v_2_canrep[]="false"; const char lex_v_3_canrep[]="true"; const char lex_v_4_canrep[]="false"; /*** * 3.2.2.2 Canonical representation * * The canonical representation for boolean is the set of literals {true, false}. * ***/ /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid true n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_4, dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid XSValue n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid XSValue n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // lexical valid ACTVALUE_TEST(lex_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(lex_v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); ACTVALUE_TEST(lex_v_4, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_4); // lexical invalid ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * lexical valid XMLCh n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // lexical valid CANREP_TEST(lex_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_2_canrep, DONT_CARE); CANREP_TEST(lex_v_3, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_3_canrep, DONT_CARE); CANREP_TEST(lex_v_4, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_4_canrep, DONT_CARE); // lexical invalid CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_hexBinary() { const XSValue::DataType dt = XSValue::dt_hexBinary; bool toValidate = true; const char lex_v_1[]=" 0fb7 \n"; const char lex_v_2[]="1234"; const char lex_iv_1[]="0gb7"; const char lex_iv_2[]="123"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_1.fValue.f_byteVal = new XMLByte[2]; act_v_ran_v_1.fValue.f_byteVal[0] = 0xf; act_v_ran_v_1.fValue.f_byteVal[1] = 0xb7; act_v_ran_v_2.fValue.f_byteVal = new XMLByte[2]; act_v_ran_v_2.fValue.f_byteVal[0] = 0x12; act_v_ran_v_2.fValue.f_byteVal[1] = 0x34; const char lex_v_1_canrep[]="0FB7"; const char lex_v_2_canrep[]="1234"; /*** * 3.2.15.2 Canonical Rrepresentation * * The canonical representation for hexBinary is defined by prohibiting certain options from the * Lexical Representation (§3.2.15.1). Specifically, * 1. the lower case hexadecimal digits ([a-f]) are not allowed. * ***/ /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid true n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid XSValue n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid XSValue n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // lexical valid ACTVALUE_TEST(lex_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); // lexical invalid ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * lexical valid XMLCh n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // lexical valid CANREP_TEST(lex_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_2_canrep, DONT_CARE); // lexical invalid CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_base64Binary() { const XSValue::DataType dt = XSValue::dt_base64Binary; bool toValidate = true; const char lex_v_1[]=" 134x cv56 gui0 \n"; const char lex_v_2[]="wxtz 8e4k"; const char lex_iv_2[]="134xcv56gui"; const char lex_iv_1[]="wxtz8e4"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; //actual values: //"134x cv56 gui0" : D7 7E 31 72 FE 7A 82 E8 B4 //"wxtz 8e4k" : C3 1B 73 F1 EE 24 act_v_ran_v_1.fValue.f_byteVal = new XMLByte[9]; act_v_ran_v_1.fValue.f_byteVal[0] = 0xd7; act_v_ran_v_1.fValue.f_byteVal[1] = 0x7e; act_v_ran_v_1.fValue.f_byteVal[2] = 0x31; act_v_ran_v_1.fValue.f_byteVal[3] = 0x72; act_v_ran_v_1.fValue.f_byteVal[4] = 0xfe; act_v_ran_v_1.fValue.f_byteVal[5] = 0x7a; act_v_ran_v_1.fValue.f_byteVal[6] = 0x82; act_v_ran_v_1.fValue.f_byteVal[7] = 0xe8; act_v_ran_v_1.fValue.f_byteVal[8] = 0xb4; act_v_ran_v_2.fValue.f_byteVal = new XMLByte[9]; act_v_ran_v_2.fValue.f_byteVal[0] = 0xc3; act_v_ran_v_2.fValue.f_byteVal[1] = 0x1b; act_v_ran_v_2.fValue.f_byteVal[2] = 0x73; act_v_ran_v_2.fValue.f_byteVal[3] = 0xf1; act_v_ran_v_2.fValue.f_byteVal[4] = 0xee; act_v_ran_v_2.fValue.f_byteVal[5] = 0x24; act_v_ran_v_2.fValue.f_byteVal[6] = 0; act_v_ran_v_2.fValue.f_byteVal[7] = 0; act_v_ran_v_2.fValue.f_byteVal[8] = 0; const char lex_v_1_canrep[]="134xcv56gui0"; const char lex_v_2_canrep[]="wxtz8e4k"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * lexical valid true n/a * lexical invalid false st_FOCA0002 * ***/ // lexical valid VALIDATE_TEST(lex_v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(lex_v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); // lexical invalid VALIDATE_TEST(lex_iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(lex_iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * lexical valid XSValue n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid XSValue n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // lexical valid ACTVALUE_TEST(lex_v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(lex_v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); // lexical invalid ACTVALUE_TEST(lex_iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(lex_iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * lexical valid XMLCh n/a * lexical invalid 0 st_FOCA0002 * * validation off * ============== * lexical valid XMLCh n/a * lexical invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // lexical valid CANREP_TEST(lex_v_1, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_1_canrep, DONT_CARE); CANREP_TEST(lex_v_2, dt, toValidate, EXP_RET_CANREP_TRUE, lex_v_2_canrep, DONT_CARE); // lexical invalid CANREP_TEST(lex_iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(lex_iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_duration() { const XSValue::DataType dt = XSValue::dt_duration; bool toValidate = true; const char v_1[]=" P1Y1M1DT1H1M1S \n"; const char v_2[]="P1Y1M31DT23H119M120S"; const char v_3[]="-P1Y1M1DT23H"; const char iv_1[]="P-1Y2M3DT10H30M"; const char iv_2[]="P1Y1M1DT1H1M1X"; const char iv_3[]="P1Z1M1DT23H"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_1.fValue.f_datetime.f_year = 1; act_v_ran_v_1.fValue.f_datetime.f_month = 1; act_v_ran_v_1.fValue.f_datetime.f_day = 1; act_v_ran_v_1.fValue.f_datetime.f_hour = 1; act_v_ran_v_1.fValue.f_datetime.f_min = 1; act_v_ran_v_1.fValue.f_datetime.f_second = 1; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 1; act_v_ran_v_2.fValue.f_datetime.f_month = 1; act_v_ran_v_2.fValue.f_datetime.f_day = 31; act_v_ran_v_2.fValue.f_datetime.f_hour = 23; act_v_ran_v_2.fValue.f_datetime.f_min = 119; act_v_ran_v_2.fValue.f_datetime.f_second = 120; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = -1; act_v_ran_v_3.fValue.f_datetime.f_month = -1; act_v_ran_v_3.fValue.f_datetime.f_day = -1; act_v_ran_v_3.fValue.f_datetime.f_hour = -23; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_date() { const XSValue::DataType dt = XSValue::dt_date; bool toValidate = true; const char v_1[]=" 1991-05-31 \n"; const char v_2[]="9999-06-30Z"; const char v_3[]="99991-07-31+14:00"; const char iv_1[]="2000-12-32"; const char iv_2[]="2001-02-29"; const char iv_3[]="2001-06-31"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; const char v_1_canrep[]="1991-05-31"; const char v_2_canrep[]="9999-06-30Z"; const char v_3_canrep[]="99991-07-30-10:00"; /* * Case Date Actual Value Canonical Value * 1 yyyy-mm-dd yyyy-mm-dd yyyy-mm-dd * 2 yyyy-mm-ddZ yyyy-mm-ddT00:00Z yyyy-mm-ddZ * 3 yyyy-mm-dd+00:00 yyyy-mm-ddT00:00Z yyyy-mm-ddZ * 4 yyyy-mm-dd+00:01 YYYY-MM-DCT23:59Z yyyy-mm-dd+00:01 * 5 yyyy-mm-dd+12:00 YYYY-MM-DCT12:00Z yyyy-mm-dd+12:00 * 6 yyyy-mm-dd+12:01 YYYY-MM-DCT11:59Z YYYY-MM-DC-11:59 * 7 yyyy-mm-dd+14:00 YYYY-MM-DCT10:00Z YYYY-MM-DC-10:00 * 8 yyyy-mm-dd-00:00 yyyy-mm-ddT00:00Z yyyy-mm-ddZ * 9 yyyy-mm-dd-00:01 yyyy-mm-ddT00:01Z yyyy-mm-dd-00:01 * 11 yyyy-mm-dd-11:59 yyyy-mm-ddT11:59Z YYYY-MM-DD-11:59 * 10 yyyy-mm-dd-12:00 yyyy-mm-ddT12:00Z YYYY-MM-DD+12:00 * 12 yyyy-mm-dd-14:00 yyyy-mm-ddT14:00Z YYYY-MM-DD+10:00 */ const char c_1[] = " 1993-05-31 "; const char r_1[] = "1993-05-31"; const char c_2[] = " 1993-05-31Z "; const char r_2[] = "1993-05-31Z"; const char c_3[] = " 1993-05-31+00:00 "; const char r_3[] = "1993-05-31Z"; const char c_4[] = " 1993-05-31+00:01 "; const char r_4[] = "1993-05-31+00:01"; const char c_5[] = " 1993-05-31+12:00 "; const char r_5[] = "1993-05-31+12:00"; const char c_6[] = " 1994-01-01+12:01 "; const char r_6[] = "1993-12-31-11:59"; const char c_7[] = " 1994-01-01+14:00 "; const char r_7[] = "1993-12-31-10:00"; const char c_8[] = " 1993-06-01-00:00 "; const char r_8[] = "1993-06-01Z"; const char c_9[] = " 1993-06-01-00:01 "; const char r_9[] = "1993-06-01-00:01"; const char c_a[] = " 1993-06-01-11:59 "; const char r_a[] = "1993-06-01-11:59"; const char c_b[] = " 1993-05-31-12:00 "; const char r_b[] = "1993-06-01+12:00"; const char c_c[] = " 1993-05-31-14:00 "; const char r_c[] = "1993-06-01+10:00"; act_v_ran_v_1.fValue.f_datetime.f_year = 1991; act_v_ran_v_1.fValue.f_datetime.f_month = 05; act_v_ran_v_1.fValue.f_datetime.f_day = 31; act_v_ran_v_1.fValue.f_datetime.f_hour = 0; act_v_ran_v_1.fValue.f_datetime.f_min = 0; act_v_ran_v_1.fValue.f_datetime.f_second = 0; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 9999; act_v_ran_v_2.fValue.f_datetime.f_month = 06; act_v_ran_v_2.fValue.f_datetime.f_day = 30; act_v_ran_v_2.fValue.f_datetime.f_hour = 0; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 99991; act_v_ran_v_3.fValue.f_datetime.f_month = 07; act_v_ran_v_3.fValue.f_datetime.f_day = 30; act_v_ran_v_3.fValue.f_datetime.f_hour = 00; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh n/a * invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_TRUE, v_1_canrep, DONT_CARE); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_TRUE, v_2_canrep, DONT_CARE); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_TRUE, v_3_canrep, DONT_CARE); CANREP_TEST(c_1, dt, toValidate, EXP_RET_CANREP_TRUE, r_1, DONT_CARE); CANREP_TEST(c_2, dt, toValidate, EXP_RET_CANREP_TRUE, r_2, DONT_CARE); CANREP_TEST(c_3, dt, toValidate, EXP_RET_CANREP_TRUE, r_3, DONT_CARE); CANREP_TEST(c_4, dt, toValidate, EXP_RET_CANREP_TRUE, r_4, DONT_CARE); CANREP_TEST(c_5, dt, toValidate, EXP_RET_CANREP_TRUE, r_5, DONT_CARE); CANREP_TEST(c_6, dt, toValidate, EXP_RET_CANREP_TRUE, r_6, DONT_CARE); CANREP_TEST(c_7, dt, toValidate, EXP_RET_CANREP_TRUE, r_7, DONT_CARE); CANREP_TEST(c_8, dt, toValidate, EXP_RET_CANREP_TRUE, r_8, DONT_CARE); CANREP_TEST(c_9, dt, toValidate, EXP_RET_CANREP_TRUE, r_9, DONT_CARE); CANREP_TEST(c_a, dt, toValidate, EXP_RET_CANREP_TRUE, r_a, DONT_CARE); CANREP_TEST(c_b, dt, toValidate, EXP_RET_CANREP_TRUE, r_b, DONT_CARE); CANREP_TEST(c_c, dt, toValidate, EXP_RET_CANREP_TRUE, r_c, DONT_CARE); // invalid // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); } } void test_dt_gYearMonth() { const XSValue::DataType dt = XSValue::dt_gYearMonth; bool toValidate = true; const char v_1[]=" 20000-02 \n"; const char v_2[]="0200-11+14:00"; const char v_3[]="2000-02-14:00"; const char iv_1[]="0000-12"; const char iv_2[]="+2000-11"; const char iv_3[]="2000.90-02"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_1.fValue.f_datetime.f_year = 20000; act_v_ran_v_1.fValue.f_datetime.f_month = 02; act_v_ran_v_1.fValue.f_datetime.f_day = 0; act_v_ran_v_1.fValue.f_datetime.f_hour = 0; act_v_ran_v_1.fValue.f_datetime.f_min = 0; act_v_ran_v_1.fValue.f_datetime.f_second = 0; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 200; act_v_ran_v_2.fValue.f_datetime.f_month = 11; act_v_ran_v_2.fValue.f_datetime.f_day = 0; act_v_ran_v_2.fValue.f_datetime.f_hour = 0; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 2000; act_v_ran_v_3.fValue.f_datetime.f_month = 02; act_v_ran_v_3.fValue.f_datetime.f_day = 0; act_v_ran_v_3.fValue.f_datetime.f_hour = 0; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_gYear() { const XSValue::DataType dt = XSValue::dt_gYear; bool toValidate = true; const char v_1[]=" 0001-14:00 \n"; const char v_2[]="9999+14:00"; const char v_3[]="-1999"; const char iv_1[]="0000"; const char iv_2[]="+2000"; const char iv_3[]="2000.90"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_1.fValue.f_datetime.f_year = 1; act_v_ran_v_1.fValue.f_datetime.f_month = 0; act_v_ran_v_1.fValue.f_datetime.f_day = 0; act_v_ran_v_1.fValue.f_datetime.f_hour = 0; act_v_ran_v_1.fValue.f_datetime.f_min = 0; act_v_ran_v_1.fValue.f_datetime.f_second = 0; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 9999; act_v_ran_v_2.fValue.f_datetime.f_month = 0; act_v_ran_v_2.fValue.f_datetime.f_day = 0; act_v_ran_v_2.fValue.f_datetime.f_hour = 0; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = -1999; act_v_ran_v_3.fValue.f_datetime.f_month = 0; act_v_ran_v_3.fValue.f_datetime.f_day = 0; act_v_ran_v_3.fValue.f_datetime.f_hour = 0; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_gMonthDay() { const XSValue::DataType dt = XSValue::dt_gMonthDay; bool toValidate = true; const char v_1[]=" --01-31+00:01 \n"; const char v_2[]="--03-31-00:01"; const char v_3[]="--04-01"; const char iv_1[]="--14-31"; const char iv_2[]="--12-32"; const char iv_3[]="--02-30"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_1.fValue.f_datetime.f_year = 0; act_v_ran_v_1.fValue.f_datetime.f_month = 1; act_v_ran_v_1.fValue.f_datetime.f_day = 30; act_v_ran_v_1.fValue.f_datetime.f_hour = 0; act_v_ran_v_1.fValue.f_datetime.f_min = 0; act_v_ran_v_1.fValue.f_datetime.f_second = 0; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 0; act_v_ran_v_2.fValue.f_datetime.f_month = 3; act_v_ran_v_2.fValue.f_datetime.f_day = 31; act_v_ran_v_2.fValue.f_datetime.f_hour = 0; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 0; act_v_ran_v_3.fValue.f_datetime.f_month = 4; act_v_ran_v_3.fValue.f_datetime.f_day = 1; act_v_ran_v_3.fValue.f_datetime.f_hour = 0; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_gDay() { const XSValue::DataType dt = XSValue::dt_gDay; bool toValidate = true; const char v_1[]=" ---31+01:30 \n"; const char v_2[]="---01-01:30"; const char v_3[]="---28"; const char iv_1[]="---+31"; const char iv_2[]="---28.00"; const char iv_3[]="--31"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_1.fValue.f_datetime.f_year = 0; act_v_ran_v_1.fValue.f_datetime.f_month = 0; act_v_ran_v_1.fValue.f_datetime.f_day = 30; act_v_ran_v_1.fValue.f_datetime.f_hour = 0; act_v_ran_v_1.fValue.f_datetime.f_min = 0; act_v_ran_v_1.fValue.f_datetime.f_second = 0; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 0; act_v_ran_v_2.fValue.f_datetime.f_month = 0; act_v_ran_v_2.fValue.f_datetime.f_day = 1; act_v_ran_v_2.fValue.f_datetime.f_hour = 0; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 0; act_v_ran_v_3.fValue.f_datetime.f_month = 0; act_v_ran_v_3.fValue.f_datetime.f_day = 28; act_v_ran_v_3.fValue.f_datetime.f_hour = 0; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_2); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_3); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_gMonth() { const XSValue::DataType dt = XSValue::dt_gMonth; bool toValidate = true; const char v_1[]=" --02+10:10 \n"; const char v_2[]="--10-12:12"; const char v_3[]="--12"; const char iv_1[]="--+11"; const char iv_2[]="---02.09"; const char iv_3[]="--14--"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_1.fValue.f_datetime.f_year = 0; act_v_ran_v_1.fValue.f_datetime.f_month = 2; act_v_ran_v_1.fValue.f_datetime.f_day = 0; act_v_ran_v_1.fValue.f_datetime.f_hour = 0; act_v_ran_v_1.fValue.f_datetime.f_min = 0; act_v_ran_v_1.fValue.f_datetime.f_second = 0; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0; act_v_ran_v_2.fValue.f_datetime.f_year = 0; act_v_ran_v_2.fValue.f_datetime.f_month = 10; act_v_ran_v_2.fValue.f_datetime.f_day = 0; act_v_ran_v_2.fValue.f_datetime.f_hour = 0; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 0; act_v_ran_v_3.fValue.f_datetime.f_month = 12; act_v_ran_v_3.fValue.f_datetime.f_day = 0; act_v_ran_v_3.fValue.f_datetime.f_hour = 0; act_v_ran_v_3.fValue.f_datetime.f_min = 0; act_v_ran_v_3.fValue.f_datetime.f_second = 0; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_2); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_3); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_dateTime() { const XSValue::DataType dt = XSValue::dt_dateTime; bool toValidate = true; const char v_1[]=" 2000-12-31T23:59:59.00389 \n"; const char v_2[]="2000-10-01T11:10:20+13:30"; const char v_3[]="2000-10-01T11:10:20-06:00"; const char iv_1[]="0000-12-31T23:59:59"; const char iv_2[]="+2000-11-30T23:59:59Z"; const char iv_3[]="2000-02-28T23:59.1:59Z"; const char iv_4[]="2000-11-30T01:01:01Z99"; const char iv_5[]="2000-02-28T01:01:01Z10:61"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; const char v_1_canrep[]="2000-12-31T23:59:59.00389"; const char v_2_canrep[]="2000-09-30T21:40:20Z"; const char v_3_canrep[]="2000-10-01T17:10:20Z"; act_v_ran_v_1.fValue.f_datetime.f_year = 2000; act_v_ran_v_1.fValue.f_datetime.f_month = 12; act_v_ran_v_1.fValue.f_datetime.f_day = 31; act_v_ran_v_1.fValue.f_datetime.f_hour = 23; act_v_ran_v_1.fValue.f_datetime.f_min = 59; act_v_ran_v_1.fValue.f_datetime.f_second = 59; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0.00389; act_v_ran_v_2.fValue.f_datetime.f_year = 2000; act_v_ran_v_2.fValue.f_datetime.f_month = 9; act_v_ran_v_2.fValue.f_datetime.f_day = 30; act_v_ran_v_2.fValue.f_datetime.f_hour = 21; act_v_ran_v_2.fValue.f_datetime.f_min = 40; act_v_ran_v_2.fValue.f_datetime.f_second = 20; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 2000; act_v_ran_v_3.fValue.f_datetime.f_month = 10; act_v_ran_v_3.fValue.f_datetime.f_day = 1; act_v_ran_v_3.fValue.f_datetime.f_hour = 17; act_v_ran_v_3.fValue.f_datetime.f_min = 10; act_v_ran_v_3.fValue.f_datetime.f_second = 20; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * E2-41 * * 3.2.7.2 Canonical representation * * Except for trailing fractional zero digits in the seconds representation, * '24:00:00' time representations, and timezone (for timezoned values), * the mapping from literals to values is one-to-one. Where there is more * than one possible representation, the canonical representation is as follows: * redundant trailing zero digits in fractional-second literals are prohibited. * An hour representation of '24' is prohibited. Timezoned values are canonically * represented by appending 'Z' to the nontimezoned representation. (All * timezoned dateTime values are UTC.) * * .'24:00:00' -> '00:00:00' * .milisecond: trailing zeros removed * .'Z' * ***/ /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_4, dt, EXP_RET_VALID_FALSE, XSValue::st_FODT0003); VALIDATE_TEST(iv_5, dt, EXP_RET_VALID_FALSE, XSValue::st_FODT0003); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_4, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FODT0003, act_v_ran_v_1); ACTVALUE_TEST(iv_5, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FODT0003, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh n/a * invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_TRUE, v_1_canrep, DONT_CARE); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_TRUE, v_2_canrep, DONT_CARE); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_TRUE, v_3_canrep, DONT_CARE); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_4, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FODT0003); CANREP_TEST(iv_5, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FODT0003); } } void test_dt_time() { const XSValue::DataType dt = XSValue::dt_time; bool toValidate = true; const char v_1[]=" 23:59:59.38900Z \n"; const char v_2[]="24:00:00"; const char v_3[]="23:59:59+00:01"; const char iv_1[]="55:59:59"; const char iv_2[]="03:99:59"; const char iv_3[]="23:59.1:59"; const char iv_4[]="01:01:01Z99"; const char iv_5[]="01:01:01Z10:61"; XSValue::XSValue_Data act_v_ran_v_1; XSValue::XSValue_Data act_v_ran_v_2; XSValue::XSValue_Data act_v_ran_v_3; const char v_1_canrep[]="23:59:59.389Z"; const char v_2_canrep[]="00:00:00"; const char v_3_canrep[]="23:58:59Z"; act_v_ran_v_1.fValue.f_datetime.f_year = 0; act_v_ran_v_1.fValue.f_datetime.f_month = 0; act_v_ran_v_1.fValue.f_datetime.f_day = 0; act_v_ran_v_1.fValue.f_datetime.f_hour = 23; act_v_ran_v_1.fValue.f_datetime.f_min = 59; act_v_ran_v_1.fValue.f_datetime.f_second = 59; act_v_ran_v_1.fValue.f_datetime.f_milisec = 0.389; act_v_ran_v_2.fValue.f_datetime.f_year = 0; act_v_ran_v_2.fValue.f_datetime.f_month = 0; act_v_ran_v_2.fValue.f_datetime.f_day = 0; act_v_ran_v_2.fValue.f_datetime.f_hour = 24; act_v_ran_v_2.fValue.f_datetime.f_min = 0; act_v_ran_v_2.fValue.f_datetime.f_second = 0; act_v_ran_v_2.fValue.f_datetime.f_milisec = 0; act_v_ran_v_3.fValue.f_datetime.f_year = 0; act_v_ran_v_3.fValue.f_datetime.f_month = 0; act_v_ran_v_3.fValue.f_datetime.f_day = 0; act_v_ran_v_3.fValue.f_datetime.f_hour = 23; act_v_ran_v_3.fValue.f_datetime.f_min = 58; act_v_ran_v_3.fValue.f_datetime.f_second = 59; act_v_ran_v_3.fValue.f_datetime.f_milisec = 0; /*** * 3.2.8.2 Canonical representation * * The canonical representation for time is defined by prohibiting certain options * from the Lexical representation (§3.2.8.1). Specifically, * 1. either the time zone must be omitted or, * 2. if present, the time zone must be Coordinated Universal Time (UTC) * indicated by a "Z". * 3. Additionally, the canonical representation for midnight is 00:00:00. * ***/ /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, XSValue::st_FOCA0002); VALIDATE_TEST(iv_4, dt, EXP_RET_VALID_FALSE, XSValue::st_FODT0003); VALIDATE_TEST(iv_5, dt, EXP_RET_VALID_FALSE, XSValue::st_FODT0003); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid XSValue n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XSValue n/a * invalid 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_TRUE, DONT_CARE, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FOCA0002, act_v_ran_v_1); ACTVALUE_TEST(iv_4, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FODT0003, act_v_ran_v_1); ACTVALUE_TEST(iv_5, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_FODT0003, act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid XMLCh n/a * invalid 0 st_FOCA0002 * * validation off * ============== * valid XMLCh n/a * invalid 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_TRUE, v_1_canrep, DONT_CARE); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_TRUE, v_2_canrep, DONT_CARE); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_TRUE, v_3_canrep, DONT_CARE); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FOCA0002); CANREP_TEST(iv_4, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FODT0003); CANREP_TEST(iv_5, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_FODT0003); } } void test_dt_string() { const XSValue::DataType dt = XSValue::dt_string; bool toValidate = true; const char v_1[]="mystring"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 n/a * invalid n/a 0 st_FOCA0002 * * validation off * ============== * valid 0 n/a * invalid n/a 0 st_FOCA0002 * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); // invalid } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 n/a * invalid n/a 0 st_FOCA0002 * * validation off * ============== * valid 0 n/a * invalid n/a 0 st_FOCA0002 * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid } } void test_dt_anyURI() { const XSValue::DataType dt = XSValue::dt_anyURI; bool toValidate = true; const char v_1[]=" http://www.schemaTest.org/IBMd3_2_17v01 \n"; const char v_2[]="gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles"; const char v_3[]="ftp://www.noNamespace.edu"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; const char iv_1[]="+htp://peiyongz@:90"; const char iv_2[]=">////1.2.3.4."; const char iv_3[]="<///www.ibm.9om"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_QName() { const XSValue::DataType dt = XSValue::dt_QName; bool toValidate = true; const char v_1[]=" Ant:Eater \n"; const char v_2[]="Minimum_Length"; const char v_3[]="abcde:a2345"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; const char iv_1[]="Three:Two:One"; const char iv_2[]=":my"; const char iv_3[]="+name"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate? XSValue::st_FOCA0002: XSValue::st_NoCanRep)); } } void test_dt_NOTATION() { const XSValue::DataType dt = XSValue::dt_NOTATION; bool toValidate = true; const char v_1[]=" http://www.ibm.com/test:notation1 \n"; const char iv_1[]="invaliduri:notation2"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid n/a 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid n/a 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); // invalid } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid n/a 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid n/a 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid } } void test_dt_normalizedString() { const XSValue::DataType dt = XSValue::dt_normalizedString; bool toValidate = true; const char v_1[]="4+4=8"; const char v_2[]="a b"; const char v_3[]="someChars=*_-"; const char iv_1[]="a\tb"; const char iv_2[]="a\nb"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_2); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_token() { const XSValue::DataType dt = XSValue::dt_token; bool toValidate = true; const char v_1[]="4+4=8"; const char v_2[]="Number2"; const char v_3[]="someChars=*_-"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; const char iv_1[]="a\tb"; const char iv_2[]="a\nb"; const char iv_3[]="a b"; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_language() { const XSValue::DataType dt = XSValue::dt_language; bool toValidate = true; const char v_1[]="en-AT"; const char v_2[]="ja"; const char v_3[]="uk-GB"; const char iv_1[]="ja_JP"; const char iv_2[]="en+US"; const char iv_3[]="12-en"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_NMTOKEN() { const XSValue::DataType dt = XSValue::dt_NMTOKEN; bool toValidate = true; const char v_1[]="Four:-_."; const char v_2[]="Zeerochert"; const char v_3[]="007"; const char iv_1[]="#board"; const char iv_2[]="@com"; const char iv_3[]=";abc"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_2); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_3); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_NMTOKENS() { const XSValue::DataType dt = XSValue::dt_NMTOKENS; bool toValidate = true; const char v_1[]="name1 name2 name3 "; const char v_2[]="Zeerochert total number"; const char v_3[]="007 009 123"; const char iv_1[]="#board"; const char iv_2[]="@com"; const char iv_3[]=";abc"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_Name() { const XSValue::DataType dt = XSValue::dt_Name; bool toValidate = true; const char v_1[]="Four:-_."; const char v_2[]="_Zeerochert"; const char v_3[]=":007"; const char iv_1[]="9name"; const char iv_2[]="-name"; const char iv_3[]=".name"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_2); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_3); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_NCName_ID_IDREF_ENTITY(XSValue::DataType dt) { bool toValidate = true; const char v_1[]="Four-_."; const char v_2[]="_Zeerochert"; const char v_3[]="L007"; const char iv_1[]=":Four-_."; const char iv_2[]="_Zeerochert:"; const char iv_3[]="0:07"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_dt_IDREFS_ENTITIES(XSValue::DataType dt) { bool toValidate = true; const char v_1[]="Four-_. Five Seven"; const char v_2[]="_Zeerochert _Hundere Bye"; const char v_3[]="L007 L009 L008"; const char iv_1[]=":Four-_."; const char iv_2[]="_Zeerochert:"; const char iv_3[]="0:07"; XSValue::XSValue_Data act_v_ran_v_1; act_v_ran_v_1.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_2; act_v_ran_v_2.fValue.f_strVal = 0; XSValue::XSValue_Data act_v_ran_v_3; act_v_ran_v_3.fValue.f_strVal = 0; /*** * * validate * --------- * availability return value context * ---------------------------------------------- * valid true n/a * invalid n/a false st_FOCA0002 * ***/ // valid VALIDATE_TEST(v_1, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_2, dt, EXP_RET_VALID_TRUE, DONT_CARE); VALIDATE_TEST(v_3, dt, EXP_RET_VALID_TRUE, DONT_CARE); // invalid VALIDATE_TEST(iv_1, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_2, dt, EXP_RET_VALID_FALSE, DONT_CARE); VALIDATE_TEST(iv_3, dt, EXP_RET_VALID_FALSE, DONT_CARE); /*** * * getActualValue * --------------- * availability return value context * ---------------------------------------------- * validation on * ============= * valid 0 st_NoActVal * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoActVal * invalid 0 st_NoActVal * ***/ for (int i = 0; i < 2; i++) { //validation on/off toValidate = ( 0 == i) ? true : false; // valid ACTVALUE_TEST(v_1, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_1); ACTVALUE_TEST(v_2, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_2); ACTVALUE_TEST(v_3, dt, toValidate, EXP_RET_VALUE_FALSE, XSValue::st_NoActVal, act_v_ran_v_3); // invalid ACTVALUE_TEST(iv_1, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_2, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); ACTVALUE_TEST(iv_3, dt, toValidate, EXP_RET_VALUE_FALSE, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoActVal), act_v_ran_v_1); } /*** * * getCanonicalRepresentation * --------------------------- * availability return value context * ---------------------------------------------- * * validation on * ============= * valid 0 st_NoCanRep * invalid 0 st_FOCA0002 * * validation off * ============== * valid 0 st_NoCanRep * invalid 0 st_NoCanRep * ***/ for (int j = 0; j < 2; j++) { //validation on/off toValidate = ( 0 == j) ? true : false; // valid CANREP_TEST(v_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); CANREP_TEST(v_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, XSValue::st_NoCanRep); // invalid CANREP_TEST(iv_1, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_2, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); CANREP_TEST(iv_3, dt, toValidate, EXP_RET_CANREP_FALSE, 0, (toValidate ? XSValue::st_FOCA0002 : XSValue::st_NoCanRep)); } } void test_DataType() { DATATYPE_TEST( SchemaSymbols::fgDT_STRING, XSValue::dt_string); DATATYPE_TEST( SchemaSymbols::fgDT_BOOLEAN, XSValue::dt_boolean); DATATYPE_TEST( SchemaSymbols::fgDT_DECIMAL, XSValue::dt_decimal); DATATYPE_TEST( SchemaSymbols::fgDT_FLOAT, XSValue::dt_float); DATATYPE_TEST( SchemaSymbols::fgDT_DOUBLE, XSValue::dt_double); DATATYPE_TEST( SchemaSymbols::fgDT_DURATION, XSValue::dt_duration); DATATYPE_TEST( SchemaSymbols::fgDT_DATETIME, XSValue::dt_dateTime); DATATYPE_TEST( SchemaSymbols::fgDT_TIME, XSValue::dt_time); DATATYPE_TEST( SchemaSymbols::fgDT_DATE, XSValue::dt_date); DATATYPE_TEST( SchemaSymbols::fgDT_YEARMONTH, XSValue::dt_gYearMonth); DATATYPE_TEST( SchemaSymbols::fgDT_YEAR, XSValue::dt_gYear); DATATYPE_TEST( SchemaSymbols::fgDT_MONTHDAY, XSValue::dt_gMonthDay); DATATYPE_TEST( SchemaSymbols::fgDT_DAY, XSValue::dt_gDay); DATATYPE_TEST( SchemaSymbols::fgDT_MONTH, XSValue::dt_gMonth); DATATYPE_TEST( SchemaSymbols::fgDT_HEXBINARY, XSValue::dt_hexBinary); DATATYPE_TEST( SchemaSymbols::fgDT_BASE64BINARY, XSValue::dt_base64Binary); DATATYPE_TEST( SchemaSymbols::fgDT_ANYURI, XSValue::dt_anyURI); DATATYPE_TEST( SchemaSymbols::fgDT_QNAME, XSValue::dt_QName); DATATYPE_TEST( XMLUni::fgNotationString, XSValue::dt_NOTATION); DATATYPE_TEST( SchemaSymbols::fgDT_NORMALIZEDSTRING, XSValue::dt_normalizedString); DATATYPE_TEST( SchemaSymbols::fgDT_TOKEN, XSValue::dt_token); DATATYPE_TEST( SchemaSymbols::fgDT_LANGUAGE, XSValue::dt_language); DATATYPE_TEST( XMLUni::fgNmTokenString, XSValue::dt_NMTOKEN); DATATYPE_TEST( XMLUni::fgNmTokensString, XSValue::dt_NMTOKENS); DATATYPE_TEST( SchemaSymbols::fgDT_NAME, XSValue::dt_Name); DATATYPE_TEST( SchemaSymbols::fgDT_NCNAME, XSValue::dt_NCName); DATATYPE_TEST( XMLUni::fgIDString, XSValue::dt_ID); DATATYPE_TEST( XMLUni::fgIDRefString, XSValue::dt_IDREF); DATATYPE_TEST( XMLUni::fgIDRefsString, XSValue::dt_IDREFS); DATATYPE_TEST( XMLUni::fgEntityString, XSValue::dt_ENTITY); DATATYPE_TEST( XMLUni::fgEntitiesString, XSValue::dt_ENTITIES); DATATYPE_TEST( SchemaSymbols::fgDT_INTEGER, XSValue::dt_integer); DATATYPE_TEST( SchemaSymbols::fgDT_NONPOSITIVEINTEGER, XSValue::dt_nonPositiveInteger); DATATYPE_TEST( SchemaSymbols::fgDT_NEGATIVEINTEGER, XSValue::dt_negativeInteger); DATATYPE_TEST( SchemaSymbols::fgDT_LONG, XSValue::dt_long); DATATYPE_TEST( SchemaSymbols::fgDT_INT, XSValue::dt_int); DATATYPE_TEST( SchemaSymbols::fgDT_SHORT, XSValue::dt_short); DATATYPE_TEST( SchemaSymbols::fgDT_BYTE, XSValue::dt_byte); DATATYPE_TEST( SchemaSymbols::fgDT_NONNEGATIVEINTEGER, XSValue::dt_nonNegativeInteger); DATATYPE_TEST( SchemaSymbols::fgDT_ULONG, XSValue::dt_unsignedLong); DATATYPE_TEST( SchemaSymbols::fgDT_UINT, XSValue::dt_unsignedInt); DATATYPE_TEST( SchemaSymbols::fgDT_USHORT, XSValue::dt_unsignedShort); DATATYPE_TEST( SchemaSymbols::fgDT_UBYTE, XSValue::dt_unsignedByte); DATATYPE_TEST( SchemaSymbols::fgDT_POSITIVEINTEGER, XSValue::dt_positiveInteger); DATATYPE_TEST( XMLUni::fgLongMaxInc, XSValue::dt_MAXCOUNT); } void testErrorStatus() { /*** DataType Interface Inv Char Out-Of-Bound To Big for C Type dt_decimal canRep st_FOCA0002 n.a. n.a. actVal st_FOCA0002 n.a. st_FOCA0001 ***/ { const char d1[]="12b34.456"; const char d2[]="44444444444466666666666666666666666666666666666666666666666666666555555555555555555555555555555555555555555555555444294967296444444444444444444444444444445555555555555555555555555555555555555555555555555555555555555555555555555222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222.999"; testNoCanRep(d1, XSValue::dt_decimal, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_decimal, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_decimal, XSValue::st_FOCA0001); } /*** dt_float canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="+3.402823466e+39"; const char d2[]="-3.4028234x66"; const char d3[]="+1.175494351e-39"; testNoCanRep(d1, XSValue::dt_float, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_float, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_float, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_float, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_float, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_float, XSValue::st_FOCA0002); } /*** dt_double canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="+3.402823466e+308"; const char d2[]="-3.4028234x66"; const char d3[]="+1.175494351e-329"; testNoCanRep(d1, XSValue::dt_double, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_double, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_double, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_double, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_double, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_double, XSValue::st_FOCA0002); } /*** dt_integer canRep st_FOCA0002 n.a. n.a. actVal st_FOCA0002 n.a. st_FOCA0003 ***/ { const char d1[]="+2147483648"; const char d2[]="-2147483649"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d3, XSValue::dt_integer, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_integer, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_integer, XSValue::st_FOCA0003); testNoActVal(d2, XSValue::dt_integer, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_integer, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_integer, XSValue::st_FOCA0002); } /*** dt_negativeInteger canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 st_FOCA0003 ***/ { const char d1[]="0"; const char d2[]="-2147483649"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_negativeInteger, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_negativeInteger, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_negativeInteger, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_negativeInteger, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_negativeInteger, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_negativeInteger, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_negativeInteger, XSValue::st_FOCA0002); } /*** dt_nonPositiveInteger canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 st_FOCA0003 ***/ { const char d1[]="1"; const char d2[]="-2147483649"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_nonPositiveInteger, XSValue::st_FOCA0002); } /*** dt_nonNegativeInteger canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 st_FOCA0003 ***/ { const char d1[]="-1"; const char d2[]="+2147483649"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_nonNegativeInteger, XSValue::st_FOCA0002); } /*** dt_positiveInteger canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 st_FOCA0003 ***/ { const char d1[]="0"; const char d2[]="+2147483649"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_positiveInteger, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_positiveInteger, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_positiveInteger, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_positiveInteger, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_positiveInteger, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_positiveInteger, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_positiveInteger, XSValue::st_FOCA0002); } /*** dt_long canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 st_FOCA0003. ***/ { const char d1[]="-9223372036854775809"; const char d2[]="+9223372036854775808"; const char d3[]="123x456"; const char d4[]="123.456"; const char d5[]="-92233720368547758"; const char d6[]="+92233720368547758"; testNoCanRep(d1, XSValue::dt_long, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_long, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_long, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_long, XSValue::st_FOCA0002); testNoActVal(d5, XSValue::dt_long, XSValue::st_FOCA0003); testNoActVal(d6, XSValue::dt_long, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_long, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_long, XSValue::st_FOCA0002); } /*** dt_int canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-2147483649"; const char d2[]="+2147483648"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_int, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_int, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_int, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_int, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_int, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_int, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_int, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_int, XSValue::st_FOCA0002); } /*** dt_short canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-32769"; const char d2[]="+32768"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_short, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_short, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_short, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_short, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_short, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_short, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_short, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_short, XSValue::st_FOCA0002); } /*** dt_byte canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-129"; const char d2[]="+128"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_byte, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_byte, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_byte, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_byte, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_byte, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_byte, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_byte, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_byte, XSValue::st_FOCA0002); } /*** dt_unsignedLong canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-1"; const char d2[]="+18446744073709551616"; const char d3[]="123x456"; const char d4[]="123.456"; const char d5[]="-3"; const char d6[]="+92233720368547758"; testNoCanRep(d1, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); testNoActVal(d5, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); testNoActVal(d6, XSValue::dt_unsignedLong, XSValue::st_FOCA0003); testNoActVal(d3, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_unsignedLong, XSValue::st_FOCA0002); } /*** dt_unsignedInt canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-1"; const char d2[]="+4294967296"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_unsignedInt, XSValue::st_FOCA0002); } /*** dt_unsignedShort canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-1"; const char d2[]="+65536"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_unsignedShort, XSValue::st_FOCA0002); } /*** dt_unsignedByte canRep st_FOCA0002 st_FOCA0002 n.a. actVal st_FOCA0002 st_FOCA0002 n.a. ***/ { const char d1[]="-1"; const char d2[]="+256"; const char d3[]="123x456"; const char d4[]="123.456"; testNoCanRep(d1, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoCanRep(d2, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoCanRep(d3, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoCanRep(d4, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoActVal(d1, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoActVal(d2, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoActVal(d3, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); testNoActVal(d4, XSValue::dt_unsignedByte, XSValue::st_FOCA0002); } } // --------------------------------------------------------------------------- // Program entry point // --------------------------------------------------------------------------- int main(int, char* ) { // Initialize the XML4C system try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { StrX msg(toCatch.getMessage()); XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n" << msg << XERCES_STD_QUALIFIER endl; return 1; } test_dt_string(); test_dt_boolean(); test_dt_decimal(); test_dt_float(); test_dt_double(); test_dt_duration(); test_dt_dateTime(); test_dt_time(); test_dt_date(); test_dt_gYearMonth(); test_dt_gYear(); test_dt_gMonthDay(); test_dt_gDay(); test_dt_gMonth(); test_dt_hexBinary(); test_dt_base64Binary(); test_dt_anyURI(); test_dt_QName(); test_dt_NOTATION(); test_dt_normalizedString(); test_dt_token(); test_dt_language(); test_dt_NMTOKEN(); test_dt_NMTOKENS(); test_dt_Name(); test_dt_NCName_ID_IDREF_ENTITY(XSValue::dt_NCName); test_dt_NCName_ID_IDREF_ENTITY(XSValue::dt_ID); test_dt_NCName_ID_IDREF_ENTITY(XSValue::dt_IDREF); test_dt_IDREFS_ENTITIES(XSValue::dt_IDREFS); test_dt_NCName_ID_IDREF_ENTITY(XSValue::dt_ENTITY); test_dt_IDREFS_ENTITIES(XSValue::dt_ENTITIES); test_dt_integer(); test_dt_nonPositiveInteger(); test_dt_negativeInteger(); test_dt_long(); test_dt_int(); test_dt_short(); test_dt_byte(); test_dt_nonNegativeInteger(); test_dt_unsignedLong(); test_dt_unsignedInt(); test_dt_unsignedShort(); test_dt_unsignedByte(); test_dt_positiveInteger(); test_DataType(); printf("\nXSValueTest %s\n", errSeen? "Fail" : "Pass"); // And call the termination method XMLPlatformUtils::Terminate(); return 0; }
Java
# =============================================================================== # Copyright 2013 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= from chaco.data_label import DataLabel from chaco.plot_label import PlotLabel # ============= standard library imports ======================== from numpy import max from traits.api import Bool, Str # ============= local library imports ========================== from pychron.pipeline.plot.overlays.mean_indicator_overlay import MovableMixin try: class FlowPlotLabel(PlotLabel, MovableMixin): def overlay(self, component, gc, *args, **kw): if self.ox: self.x = self.ox - self.offset_x self.y = self.oy - self.offset_y super(FlowPlotLabel, self).overlay(component, gc, *args, **kw) def hittest(self, pt): x, y = pt w, h = self.get_preferred_size() return abs(x - self.x) < w and abs(y - self.y) < h except TypeError: # documentation auto doc hack class FlowPlotLabel: pass class FlowDataLabel(DataLabel): """ this label repositions itself if doesn't fit within the its component bounds. """ constrain_x = Bool(True) constrain_y = Bool(True) # position_event=Event id = Str # _ox=None # def _draw(self, gc, **kw): # self.font='modern 18' # gc.set_font(self.font) # print 'draw', self.font # super(FlowDataLabel, self)._draw(gc,**kw) # def _set_x(self, val): # super(FlowDataLabel, self)._set_x(val) # if self._ox is None: # self._ox = val # elif self._ox != val: # self.position_event=(self.x, self.y) # # def _set_y(self, val): # super(FlowDataLabel, self)._set_y(val) # if val>0: # self.position_event = (self.x, self.y) def overlay(self, component, gc, *args, **kw): # face name was getting set to "Helvetica" by reportlab during pdf generation # set face_name back to "" to prevent font display issue. see issue #72 self.font.face_name = "" super(FlowDataLabel, self).overlay(component, gc, *args, **kw) def do_layout(self, **kw): DataLabel.do_layout(self, **kw) ws, hs = self._cached_line_sizes.T if self.constrain_x: w = max(ws) d = self.component.x2 - (self.x + w + 3 * self.border_padding) if d < 0: self.x += d self.x = max((self.x, 0)) if self.constrain_y: h = max(hs) self.y = max((self.y, 0)) yd = self.component.y2 - h - 2 * self.border_padding - self.line_spacing self.y = min((self.y, yd)) # ============= EOF =============================================
Java
CREATE CONSTRAINT ON (c:Concept) ASSERT c.name IS UNIQUE; ##Creating all the nodes from CSV file USING PERIODIC COMMIT 50 LOAD CSV WITH HEADERS FROM "file:///food.csv" AS Line WITH Line WHERE Line.name IS NOT NULL MERGE (c:Concept {name:Line.name}) SET c.conceptid = Line.`node id` SET c.context = Line.context SET c.desc = Line.description SET c.parent = Line.`parent node id` #---End of creating nodes--- ## create a relationship between nodes dynamically USING PERIODIC COMMIT 50 LOAD CSV WITH HEADERS FROM "file:///food.csv" AS Line WITH Line WHERE Line.name IS NOT NULL MATCH (c:concept {name:Line.name}) MATCH (pc:concept {conceptid:Line.`parent node id`}) call apoc.create.relationship(c, Line.`parent relation`, {}, pc) YIELD rel return c, pc, rel ##Create a relationship if you know the relation between nodes USING PERIODIC COMMIT 50 LOAD CSV WITH HEADERS FROM "file:///food.csv" AS Line WITH Line, Line.`parent relation` as rl WHERE Line.name IS NOT NULL MATCH (c:Concept {name:Line.name}) MATCH (pc:Concept {conceptid:Line.`parent node id`}) FOREACH(ignoreme in CASE WHEN rl = "subconcept of" THEN [1] ELSE [] END | MERGE (c)-[:`subconcept of`]->(pc)) FOREACH(ignoreme in CASE WHEN rl = "related" THEN [1] ELSE [] END | MERGE (c)-[:`related`]->(pc)) ##Creating a Domain and create relation between domain and concepts Match (c:Concept {context: 'Food'}) merge (d:Domain {name:'Food'}) merge (c)-[r:ConceptOf]->(d) return c,r,d ##To return all the node from database MATCH (c:Concept) MATCH (pc:Concept) MATCH (d:Domain) MATCH (c)-[]-(pc) MATCH (c)-[]-(d)
Java
/* * 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.synapse.deployers; import org.apache.axiom.om.OMElement; import org.apache.axis2.deployment.DeploymentException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.Startup; import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder; import org.apache.synapse.config.xml.StartupFinder; import java.io.File; import java.util.Properties; /** * Handles the <code>Startup Task</code> deployment and undeployment * * @see org.apache.synapse.deployers.AbstractSynapseArtifactDeployer */ public class TaskDeployer extends AbstractSynapseArtifactDeployer { private static Log log = LogFactory.getLog(TaskDeployer.class); @Override public String deploySynapseArtifact(OMElement artifactConfig, String fileName, Properties properties) { if (log.isDebugEnabled()) { log.debug("StartupTask Deployment from file : " + fileName + " : Started"); } try { Startup st = StartupFinder.getInstance().getStartup(artifactConfig, properties); st.setFileName((new File(fileName)).getName()); if (log.isDebugEnabled()) { log.debug("StartupTask named '" + st.getName() + "' has been built from the file " + fileName); } st.init(getSynapseEnvironment()); if (log.isDebugEnabled()) { log.debug("Initialized the StartupTask : " + st.getName()); } getSynapseConfiguration().addStartup(st); if (log.isDebugEnabled()) { log.debug("StartupTask Deployment from file : " + fileName + " : Completed"); } log.info("StartupTask named '" + st.getName() + "' has been deployed from file : " + fileName); return st.getName(); } catch (Exception e) { handleSynapseArtifactDeploymentError( "StartupTask Deployment from the file : " + fileName + " : Failed.", e); } return null; } @Override public String updateSynapseArtifact(OMElement artifactConfig, String fileName, String existingArtifactName, Properties properties) { if (log.isDebugEnabled()) { log.debug("StartupTask update from file : " + fileName + " has started"); } try { Startup st = StartupFinder.getInstance().getStartup(artifactConfig, properties); st.setFileName((new File(fileName)).getName()); if (log.isDebugEnabled()) { log.debug("StartupTask: " + st.getName() + " has been built from the file: " + fileName); } Startup existingSt = getSynapseConfiguration().getStartup(existingArtifactName); existingSt.destroy(); st.init(getSynapseEnvironment()); if (existingArtifactName.equals(st.getName())) { getSynapseConfiguration().updateStartup(st); } else { getSynapseConfiguration().addStartup(st); getSynapseConfiguration().removeStartup(existingArtifactName); log.info("StartupTask: " + existingArtifactName + " has been undeployed"); } log.info("StartupTask: " + st.getName() + " has been updated from the file: " + fileName); return st.getName(); } catch (DeploymentException e) { handleSynapseArtifactDeploymentError("Error while updating the startup task from the " + "file: " + fileName); } return null; } @Override public void undeploySynapseArtifact(String artifactName) { if (log.isDebugEnabled()) { log.debug("StartupTask Undeployment of the task named : " + artifactName + " : Started"); } try { Startup st = getSynapseConfiguration().getStartup(artifactName); if (st != null) { getSynapseConfiguration().removeStartup(artifactName); if (log.isDebugEnabled()) { log.debug("Destroying the StartupTask named : " + artifactName); } st.destroy(); if (log.isDebugEnabled()) { log.debug("StartupTask Undeployment of the sequence named : " + artifactName + " : Completed"); } log.info("StartupTask named '" + st.getName() + "' has been undeployed"); } else if (log.isDebugEnabled()) { log.debug("Startup task " + artifactName + " has already been undeployed"); } } catch (Exception e) { handleSynapseArtifactDeploymentError( "StartupTask Undeployement of task named : " + artifactName + " : Failed", e); } } @Override public void restoreSynapseArtifact(String artifactName) { if (log.isDebugEnabled()) { log.debug("Restoring the StartupTask with name : " + artifactName + " : Started"); } try { Startup st = getSynapseConfiguration().getStartup(artifactName); OMElement stElem = StartupFinder.getInstance().serializeStartup(null, st); if (st.getFileName() != null) { String fileName = getServerConfigurationInformation().getSynapseXMLLocation() + File.separator + MultiXMLConfigurationBuilder.TASKS_DIR + File.separator + st.getFileName(); writeToFile(stElem, fileName); if (log.isDebugEnabled()) { log.debug("Restoring the StartupTask with name : " + artifactName + " : Completed"); } log.info("StartupTask named '" + artifactName + "' has been restored"); } else { handleSynapseArtifactDeploymentError("Couldn't restore the StartupTask named '" + artifactName + "', filename cannot be found"); } } catch (Exception e) { handleSynapseArtifactDeploymentError( "Restoring of the StartupTask named '" + artifactName + "' has failed", e); } } }
Java
/* Copyright 2017 The Kubernetes Authors. 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 setmilestone implements the `/milestone` command which allows members of the milestone // maintainers team to specify a milestone to be applied to an Issue or PR. package milestone import ( "fmt" "regexp" "sort" "strings" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/pluginhelp" "k8s.io/test-infra/prow/plugins" ) const pluginName = "milestone" var ( milestoneRegex = regexp.MustCompile(`(?m)^/milestone\s+(.+?)\s*$`) mustBeSigLead = "You must be a member of the [%s/%s](https://github.com/orgs/%s/teams/%s/members) github team to set the milestone." invalidMilestone = "The provided milestone is not valid for this repository. Milestones in this repository: [%s]\n\nUse `/milestone %s` to clear the milestone." milestoneTeamMsg = "The milestone maintainers team is the Github team with ID: %d." clearKeyword = "clear" ) type githubClient interface { CreateComment(owner, repo string, number int, comment string) error ClearMilestone(org, repo string, num int) error SetMilestone(org, repo string, issueNum, milestoneNum int) error ListTeamMembers(id int, role string) ([]github.TeamMember, error) ListMilestones(org, repo string) ([]github.Milestone, error) } func init() { plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, helpProvider) } func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) { pluginHelp := &pluginhelp.PluginHelp{ Description: "The milestone plugin allows members of a configurable GitHub team to set the milestone on an issue or pull request.", Config: func(repos []string) map[string]string { configMap := make(map[string]string) for _, repo := range repos { team, exists := config.RepoMilestone[repo] if exists { configMap[repo] = fmt.Sprintf(milestoneTeamMsg, team) } } configMap[""] = fmt.Sprintf(milestoneTeamMsg, config.RepoMilestone[""]) return configMap }(enabledRepos), } pluginHelp.AddCommand(pluginhelp.Command{ Usage: "/milestone <version> or /milestone clear", Description: "Updates the milestone for an issue or PR", Featured: false, WhoCanUse: "Members of the milestone maintainers GitHub team can use the '/milestone' command.", Examples: []string{"/milestone v1.10", "/milestone v1.9", "/milestone clear"}, }) return pluginHelp, nil } func handleGenericComment(pc plugins.PluginClient, e github.GenericCommentEvent) error { return handle(pc.GitHubClient, pc.Logger, &e, pc.PluginConfig.RepoMilestone) } func buildMilestoneMap(milestones []github.Milestone) map[string]int { m := make(map[string]int) for _, ms := range milestones { m[ms.Title] = ms.Number } return m } func handle(gc githubClient, log *logrus.Entry, e *github.GenericCommentEvent, repoMilestone map[string]plugins.Milestone) error { if e.Action != github.GenericCommentActionCreated { return nil } milestoneMatch := milestoneRegex.FindStringSubmatch(e.Body) if len(milestoneMatch) != 2 { return nil } org := e.Repo.Owner.Login repo := e.Repo.Name milestone, exists := repoMilestone[fmt.Sprintf("%s/%s", org, repo)] if !exists { // fallback default milestone = repoMilestone[""] } milestoneMaintainers, err := gc.ListTeamMembers(milestone.MaintainersID, github.RoleAll) if err != nil { return err } found := false for _, person := range milestoneMaintainers { login := github.NormLogin(e.User.Login) if github.NormLogin(person.Login) == login { found = true break } } if !found { // not in the milestone maintainers team msg := fmt.Sprintf(mustBeSigLead, org, milestone.MaintainersTeam, org, milestone.MaintainersTeam) return gc.CreateComment(org, repo, e.Number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, msg)) } milestones, err := gc.ListMilestones(org, repo) if err != nil { log.WithError(err).Errorf("Error listing the milestones in the %s/%s repo", org, repo) return err } proposedMilestone := milestoneMatch[1] // special case, if the clear keyword is used if proposedMilestone == clearKeyword { if err := gc.ClearMilestone(org, repo, e.Number); err != nil { log.WithError(err).Errorf("Error clearing the milestone for %s/%s#%d.", org, repo, e.Number) } return nil } milestoneMap := buildMilestoneMap(milestones) milestoneNumber, ok := milestoneMap[proposedMilestone] if !ok { slice := make([]string, 0, len(milestoneMap)) for k := range milestoneMap { slice = append(slice, fmt.Sprintf("`%s`", k)) } sort.Strings(slice) msg := fmt.Sprintf(invalidMilestone, strings.Join(slice, ", "), clearKeyword) return gc.CreateComment(org, repo, e.Number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, msg)) } if err := gc.SetMilestone(org, repo, e.Number, milestoneNumber); err != nil { log.WithError(err).Errorf("Error adding the milestone %s to %s/%s#%d.", proposedMilestone, org, repo, e.Number) } return nil }
Java
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // 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. #pragma once #include <string> #include "paddle/fluid/framework/ir/fuse_pass_base.h" #include "paddle/fluid/framework/ir/graph.h" namespace paddle { namespace framework { namespace ir { /* * \brief Fuse the FC and activation operators into single OneDNN's * FC with post-op. * * \note Currently only GeLU, hardswish, sigmoid, mish and tanh are supported * as an activation function. */ class FuseFCActOneDNNPass : public FusePassBase { public: virtual ~FuseFCActOneDNNPass() {} protected: void ApplyImpl(ir::Graph *graph) const override; void FuseFCAct(ir::Graph *graph, const std::string &act_types) const; }; } // namespace ir } // namespace framework } // namespace paddle
Java
/* * Copyright 2012 Rolando Martins, CRACS & INESC-TEC, DCC/FCUP * * 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. * */ /* * File: PeerProvider.h * Author: rmartins * * Created on July 26, 2010, 6:13 PM */ #ifndef PEERPROVIDER_H #define PEERPROVIDER_H #include <stheno/core/p2p/discovery/DiscoveryProvider.h> #include <stheno/core/p2p/common/PeerMap.h> #include <stheno/core/p2p/mesh/Mesh.h> class PeerProvider: public DiscoveryProvider { public: static const UInt PEER_PROVIDER; PeerProvider(MeshPtr& meshService); virtual ~PeerProvider(); virtual void close(); virtual DiscoveryQueryReply* executeQuery( DiscoveryQuery* query, DiscoveryQoS* qos = 0) throw (DiscoveryException&); virtual AsyncDiscoveryQueryReply* executeAsyncQuery( DiscoveryQuery* query, DiscoveryQoS* qos = 0, ACE_Time_Value* timeout = 0) throw (DiscoveryException&); virtual void cancelAsyncQuery(AsyncDiscoveryQueryReply* token) throw (DiscoveryException&); virtual UInt getProviderID(); //caller must free list virtual list<UInt>& getProvidedEvents(); protected: list<UInt> m_providedEvents; MeshPtr m_meshService; PeerMapPtr& getPeerMap(); }; #endif /* PEERPROVIDER_H */
Java
// // Copyright 2014, Sander van Harmelen // // 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 cloudstack44 import ( "encoding/json" "net/url" "strconv" ) type ListStorageProvidersParams struct { p map[string]interface{} } func (p *ListStorageProvidersParams) toURLValues() url.Values { u := url.Values{} if p.p == nil { return u } if v, found := p.p["keyword"]; found { u.Set("keyword", v.(string)) } if v, found := p.p["page"]; found { vv := strconv.Itoa(v.(int)) u.Set("page", vv) } if v, found := p.p["pagesize"]; found { vv := strconv.Itoa(v.(int)) u.Set("pagesize", vv) } if v, found := p.p["type"]; found { u.Set("type", v.(string)) } return u } func (p *ListStorageProvidersParams) SetKeyword(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["keyword"] = v return } func (p *ListStorageProvidersParams) SetPage(v int) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["page"] = v return } func (p *ListStorageProvidersParams) SetPagesize(v int) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["pagesize"] = v return } func (p *ListStorageProvidersParams) SetType(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["storagePoolType"] = v return } // You should always use this function to get a new ListStorageProvidersParams instance, // as then you are sure you have configured all required params func (s *StoragePoolService) NewListStorageProvidersParams(storagePoolType string) *ListStorageProvidersParams { p := &ListStorageProvidersParams{} p.p = make(map[string]interface{}) p.p["storagePoolType"] = storagePoolType return p } // Lists storage providers. func (s *StoragePoolService) ListStorageProviders(p *ListStorageProvidersParams) (*ListStorageProvidersResponse, error) { resp, err := s.cs.newRequest("listStorageProviders", p.toURLValues()) if err != nil { return nil, err } var r ListStorageProvidersResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } return &r, nil } type ListStorageProvidersResponse struct { Count int `json:"count"` StorageProviders []*StorageProvider `json:"storageprovider"` } type StorageProvider struct { Name string `json:"name,omitempty"` Type string `json:"type,omitempty"` } type EnableStorageMaintenanceParams struct { p map[string]interface{} } func (p *EnableStorageMaintenanceParams) toURLValues() url.Values { u := url.Values{} if p.p == nil { return u } if v, found := p.p["id"]; found { u.Set("id", v.(string)) } return u } func (p *EnableStorageMaintenanceParams) SetId(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["id"] = v return } // You should always use this function to get a new EnableStorageMaintenanceParams instance, // as then you are sure you have configured all required params func (s *StoragePoolService) NewEnableStorageMaintenanceParams(id string) *EnableStorageMaintenanceParams { p := &EnableStorageMaintenanceParams{} p.p = make(map[string]interface{}) p.p["id"] = id return p } // Puts storage pool into maintenance state func (s *StoragePoolService) EnableStorageMaintenance(p *EnableStorageMaintenanceParams) (*EnableStorageMaintenanceResponse, error) { resp, err := s.cs.newRequest("enableStorageMaintenance", p.toURLValues()) if err != nil { return nil, err } var r EnableStorageMaintenanceResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } // If we have a async client, we need to wait for the async result if s.cs.async { b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout) if err != nil { return nil, err } // If 'warn' has a value it means the job is running longer than the configured // timeout, the resonse will contain the jobid of the running async job if warn != nil { return &r, warn } b, err = getRawValue(b) if err != nil { return nil, err } if err := json.Unmarshal(b, &r); err != nil { return nil, err } } return &r, nil } type EnableStorageMaintenanceResponse struct { JobID string `json:"jobid,omitempty"` Capacityiops int64 `json:"capacityiops,omitempty"` Clusterid string `json:"clusterid,omitempty"` Clustername string `json:"clustername,omitempty"` Created string `json:"created,omitempty"` Disksizeallocated int64 `json:"disksizeallocated,omitempty"` Disksizetotal int64 `json:"disksizetotal,omitempty"` Disksizeused int64 `json:"disksizeused,omitempty"` Hypervisor string `json:"hypervisor,omitempty"` Id string `json:"id,omitempty"` Ipaddress string `json:"ipaddress,omitempty"` Name string `json:"name,omitempty"` Overprovisionfactor string `json:"overprovisionfactor,omitempty"` Path string `json:"path,omitempty"` Podid string `json:"podid,omitempty"` Podname string `json:"podname,omitempty"` Scope string `json:"scope,omitempty"` State string `json:"state,omitempty"` Storagecapabilities map[string]string `json:"storagecapabilities,omitempty"` Suitableformigration bool `json:"suitableformigration,omitempty"` Tags string `json:"tags,omitempty"` Type string `json:"type,omitempty"` Zoneid string `json:"zoneid,omitempty"` Zonename string `json:"zonename,omitempty"` } type CancelStorageMaintenanceParams struct { p map[string]interface{} } func (p *CancelStorageMaintenanceParams) toURLValues() url.Values { u := url.Values{} if p.p == nil { return u } if v, found := p.p["id"]; found { u.Set("id", v.(string)) } return u } func (p *CancelStorageMaintenanceParams) SetId(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["id"] = v return } // You should always use this function to get a new CancelStorageMaintenanceParams instance, // as then you are sure you have configured all required params func (s *StoragePoolService) NewCancelStorageMaintenanceParams(id string) *CancelStorageMaintenanceParams { p := &CancelStorageMaintenanceParams{} p.p = make(map[string]interface{}) p.p["id"] = id return p } // Cancels maintenance for primary storage func (s *StoragePoolService) CancelStorageMaintenance(p *CancelStorageMaintenanceParams) (*CancelStorageMaintenanceResponse, error) { resp, err := s.cs.newRequest("cancelStorageMaintenance", p.toURLValues()) if err != nil { return nil, err } var r CancelStorageMaintenanceResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } // If we have a async client, we need to wait for the async result if s.cs.async { b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout) if err != nil { return nil, err } // If 'warn' has a value it means the job is running longer than the configured // timeout, the resonse will contain the jobid of the running async job if warn != nil { return &r, warn } b, err = getRawValue(b) if err != nil { return nil, err } if err := json.Unmarshal(b, &r); err != nil { return nil, err } } return &r, nil } type CancelStorageMaintenanceResponse struct { JobID string `json:"jobid,omitempty"` Capacityiops int64 `json:"capacityiops,omitempty"` Clusterid string `json:"clusterid,omitempty"` Clustername string `json:"clustername,omitempty"` Created string `json:"created,omitempty"` Disksizeallocated int64 `json:"disksizeallocated,omitempty"` Disksizetotal int64 `json:"disksizetotal,omitempty"` Disksizeused int64 `json:"disksizeused,omitempty"` Hypervisor string `json:"hypervisor,omitempty"` Id string `json:"id,omitempty"` Ipaddress string `json:"ipaddress,omitempty"` Name string `json:"name,omitempty"` Overprovisionfactor string `json:"overprovisionfactor,omitempty"` Path string `json:"path,omitempty"` Podid string `json:"podid,omitempty"` Podname string `json:"podname,omitempty"` Scope string `json:"scope,omitempty"` State string `json:"state,omitempty"` Storagecapabilities map[string]string `json:"storagecapabilities,omitempty"` Suitableformigration bool `json:"suitableformigration,omitempty"` Tags string `json:"tags,omitempty"` Type string `json:"type,omitempty"` Zoneid string `json:"zoneid,omitempty"` Zonename string `json:"zonename,omitempty"` }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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 com.android.tools.idea.lang.rs; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; public class RenderscriptParser implements PsiParser { @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { final PsiBuilder.Marker rootMarker = builder.mark(); while (!builder.eof()) { builder.advanceLexer(); } rootMarker.done(root); return builder.getTreeBuilt(); } }
Java
module m integer::i=3 integer::j=4 end module m program t use m,only:i integer::j=77 print '(i0)',i,j end program t
Java
--TEST-- Deregisters UDF module at the Aerospike DB which is present. --FILE-- <?php include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc"; aerospike_phpt_runtest("Udf", "testUdfDeregisterModulePositive"); --EXPECT-- OK
Java
--- layout: base title: 'Dependencies' generated: 'true' permalink: uk/dep/all.html --- {% capture lcode %}{{ page.permalink | split:"/" | first }}{% endcapture %} # Dependencies <span about="." property="rdf:type" resource="owl:Ontology"> <span property="owl:imports" resource=" https://www.w3.org/2012/pyRdfa/extract?uri=http://universaldependencies.org/docs/u/dep/all.html&format=xml&rdfagraph=output&vocab_expansion=false&rdfa_lite=false&embedded_rdf=true&space_preserve=false&vocab_cache=true&vocab_cache_report=false&vocab_cache_refresh=false"/> </span> {% include uk-dep-table.html %} <span about="#dep_{{ lcode }}" property="rdfs:label" style="visibility: hidden">{{ page.title }}</span> <span about="#dep_{{ lcode }}" property="rdfs:subClassOf" resource="_:{{ lcode }}"> <span about="_:{{ lcode }}" property="rdf:type" resource="owl:Restriction"> <span property="owl:onProperty" resource="http://purl.org/dc/terms/language"/> <span property="owl:hasValue" lang="" style="visibility: hidden">{{ lcode }}</span> </span> </span> ---------- {% assign sorted = site.uk-dep | sort: 'title' %} {% for p in sorted %} {% capture concept %}{{ p.title | split:':' | first }}{% endcapture %} <div about="#{{ p.title | url_encode }}_{{ lcode }}" property="rdf:type" resource="#dep_{{ lcode }}"> <div property="rdf:type" resource="../../u/dep/all.html#{{ concept }}"/> <a id="al-{{ lcode }}-dep/{{ p.title }}" class="al-dest"/> <h2><code property="oliasystem:hasTag" lang="">{{ p.title }}</code>: <div property="rdfs:label">{{ p.shortdef }}</div></h2> <div property="rdfs:comment"> {% if p.content contains "<!--details-->" %} {{ p.content | split:"<!--details-->" | first | markdownify }} <a property="rdfs:seeAlso" href="{{ p.title }}" class="al-doc">See details</a> {% else %} {{ p.content | markdownify }} {% endif %} </div> <a href="{{ site.git_edit }}/{% if p.collection %}{{ p.relative_path }}{% else %}{{ p.path }}{% endif %}" target="#">edit {{ p.title }}</a> </div> {% endfor %}
Java
<?php namespace edu\wisc\services\caos; class GetCourseByCatalogNumberRequest { /** * @var termCodeType $termCode */ protected $termCode = null; /** * @var string $subjectCode */ protected $subjectCode = null; /** * @var string $catalogNumber */ protected $catalogNumber = null; /** * @param termCodeType $termCode * @param string $subjectCode * @param string $catalogNumber */ public function __construct($termCode, $subjectCode, $catalogNumber) { $this->termCode = $termCode; $this->subjectCode = $subjectCode; $this->catalogNumber = $catalogNumber; } /** * @return termCodeType */ public function getTermCode() { return $this->termCode; } /** * @param termCodeType $termCode * @return \edu\wisc\services\caos\GetCourseByCatalogNumberRequest */ public function setTermCode($termCode) { $this->termCode = $termCode; return $this; } /** * @return string */ public function getSubjectCode() { return $this->subjectCode; } /** * @param string $subjectCode * @return \edu\wisc\services\caos\GetCourseByCatalogNumberRequest */ public function setSubjectCode($subjectCode) { $this->subjectCode = $subjectCode; return $this; } /** * @return string */ public function getCatalogNumber() { return $this->catalogNumber; } /** * @param string $catalogNumber * @return \edu\wisc\services\caos\GetCourseByCatalogNumberRequest */ public function setCatalogNumber($catalogNumber) { $this->catalogNumber = $catalogNumber; return $this; } }
Java
/** * 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.wss4j.stax.impl.securityToken; import org.apache.wss4j.common.bsp.BSPRule; import org.apache.wss4j.common.ext.WSSecurityException; import org.apache.wss4j.common.principal.UsernameTokenPrincipal; import org.apache.wss4j.common.util.UsernameTokenUtil; import org.apache.wss4j.stax.ext.WSInboundSecurityContext; import org.apache.wss4j.stax.ext.WSSConstants; import org.apache.wss4j.stax.securityToken.UsernameSecurityToken; import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants; import org.apache.xml.security.exceptions.XMLSecurityException; import org.apache.xml.security.stax.config.JCEAlgorithmMapper; import org.apache.xml.security.stax.ext.XMLSecurityConstants; import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.Subject; import java.security.Key; import java.security.Principal; public class UsernameSecurityTokenImpl extends AbstractInboundSecurityToken implements UsernameSecurityToken { private static final long DEFAULT_ITERATION = 1000; private WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType; private String username; private String password; private String createdTime; private byte[] nonce; private byte[] salt; private Long iteration; private final WSInboundSecurityContext wsInboundSecurityContext; private Subject subject; private Principal principal; public UsernameSecurityTokenImpl(WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType, String username, String password, String createdTime, byte[] nonce, byte[] salt, Long iteration, WSInboundSecurityContext wsInboundSecurityContext, String id, WSSecurityTokenConstants.KeyIdentifier keyIdentifier) { super(wsInboundSecurityContext, id, keyIdentifier, true); this.usernameTokenPasswordType = usernameTokenPasswordType; this.username = username; this.password = password; this.createdTime = createdTime; this.nonce = nonce; this.salt = salt; this.iteration = iteration; this.wsInboundSecurityContext = wsInboundSecurityContext; } @Override public boolean isAsymmetric() throws XMLSecurityException { return false; } @Override protected Key getKey(String algorithmURI, XMLSecurityConstants.AlgorithmUsage algorithmUsage, String correlationID) throws XMLSecurityException { Key key = getSecretKey().get(algorithmURI); if (key != null) { return key; } byte[] secretToken = generateDerivedKey(wsInboundSecurityContext); String algoFamily = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(algorithmURI); key = new SecretKeySpec(secretToken, algoFamily); setSecretKey(algorithmURI, key); return key; } @Override public WSSecurityTokenConstants.TokenType getTokenType() { return WSSecurityTokenConstants.UsernameToken; } /** * This method generates a derived key as defined in WSS Username * Token Profile. * * @return Returns the derived key a byte array * @throws WSSecurityException */ public byte[] generateDerivedKey() throws WSSecurityException { return generateDerivedKey(wsInboundSecurityContext); } /** * This method generates a derived key as defined in WSS Username * Token Profile. * * @return Returns the derived key a byte array * @throws org.apache.wss4j.common.ext.WSSecurityException * */ protected byte[] generateDerivedKey(WSInboundSecurityContext wsInboundSecurityContext) throws WSSecurityException { if (wsInboundSecurityContext != null) { if (salt == null || salt.length == 0) { wsInboundSecurityContext.handleBSPRule(BSPRule.R4217); } if (iteration == null || iteration < DEFAULT_ITERATION) { wsInboundSecurityContext.handleBSPRule(BSPRule.R4218); } } return UsernameTokenUtil.generateDerivedKey(password, salt, iteration.intValue()); } @Override public Principal getPrincipal() throws WSSecurityException { if (this.principal == null) { this.principal = new UsernameTokenPrincipal() { //todo passwordType and passwordDigest return Enum-Type ? @Override public boolean isPasswordDigest() { return usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_DIGEST; } @Override public String getPasswordType() { return usernameTokenPasswordType.getNamespace(); } @Override public String getName() { return username; } @Override public String getPassword() { return password; } @Override public String getCreatedTime() { return createdTime; } @Override public byte[] getNonce() { return nonce; } }; } return this.principal; } public WSSConstants.UsernameTokenPasswordType getUsernameTokenPasswordType() { return usernameTokenPasswordType; } public String getCreatedTime() { return createdTime; } public String getPassword() { return password; } public String getUsername() { return username; } public byte[] getNonce() { return nonce; } public byte[] getSalt() { return salt; } public Long getIteration() { return iteration; } public void setSubject(Subject subject) { this.subject = subject; } @Override public Subject getSubject() throws WSSecurityException { return subject; } }
Java
# # Author:: Adam Jacob (<[email protected]>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # require "chef/resource/script" require "chef/provider/script" class Chef class Resource class Bash < Chef::Resource::Script def initialize(name, run_context=nil) super @interpreter = "bash" end end end end
Java
/********************************************************************** Copyright (c) 2005 Erik Bengtson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.samples.metadata.datastoreidentity; public class D3 { private String name; /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } }
Java
package com.mic.log.spouts; import java.util.Map; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; public class AppLogWriterSpout extends BaseRichSpout { private SpoutOutputCollector _collector; public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this._collector = collector; } @Override public void nextTuple() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } _collector.emit(new Values("command")); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("command")); } }
Java
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/nix/mime_util_xdg.h" #include <cstdlib> #include <list> #include <map> #include <vector> #include "base/environment.h" #include "base/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/nix/xdg_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" #include "base/third_party/xdg_mime/xdgmime.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" namespace base { namespace nix { namespace { class IconTheme; // None of the XDG stuff is thread-safe, so serialize all access under // this lock. LazyInstance<Lock>::Leaky g_mime_util_xdg_lock = LAZY_INSTANCE_INITIALIZER; class MimeUtilConstants { public: typedef std::map<std::string, IconTheme*> IconThemeMap; typedef std::map<FilePath, Time> IconDirMtimeMap; typedef std::vector<std::string> IconFormats; // Specified by XDG icon theme specs. static const int kUpdateIntervalInSeconds = 5; static const size_t kDefaultThemeNum = 4; static MimeUtilConstants* GetInstance() { return Singleton<MimeUtilConstants>::get(); } // Store icon directories and their mtimes. IconDirMtimeMap icon_dirs_; // Store icon formats. IconFormats icon_formats_; // Store loaded icon_theme. IconThemeMap icon_themes_; // The default theme. IconTheme* default_themes_[kDefaultThemeNum]; TimeTicks last_check_time_; // The current icon theme, usually set through GTK theme integration. std::string icon_theme_name_; private: MimeUtilConstants() { icon_formats_.push_back(".png"); icon_formats_.push_back(".svg"); icon_formats_.push_back(".xpm"); for (size_t i = 0; i < kDefaultThemeNum; ++i) default_themes_[i] = NULL; } ~MimeUtilConstants(); friend struct DefaultSingletonTraits<MimeUtilConstants>; DISALLOW_COPY_AND_ASSIGN(MimeUtilConstants); }; // IconTheme represents an icon theme as defined by the xdg icon theme spec. // Example themes on GNOME include 'Human' and 'Mist'. // Example themes on KDE include 'crystalsvg' and 'kdeclassic'. class IconTheme { public: // A theme consists of multiple sub-directories, like '32x32' and 'scalable'. class SubDirInfo { public: // See spec for details. enum Type { Fixed, Scalable, Threshold }; SubDirInfo() : size(0), type(Threshold), max_size(0), min_size(0), threshold(2) { } size_t size; // Nominal size of the icons in this directory. Type type; // Type of the icon size. size_t max_size; // Maximum size that the icons can be scaled to. size_t min_size; // Minimum size that the icons can be scaled to. size_t threshold; // Maximum difference from desired size. 2 by default. }; explicit IconTheme(const std::string& name); ~IconTheme() {} // Returns the path to an icon with the name |icon_name| and a size of |size| // pixels. If the icon does not exist, but |inherits| is true, then look for // the icon in the parent theme. FilePath GetIconPath(const std::string& icon_name, int size, bool inherits); // Load a theme with the name |theme_name| into memory. Returns null if theme // is invalid. static IconTheme* LoadTheme(const std::string& theme_name); private: // Returns the path to an icon with the name |icon_name| in |subdir|. FilePath GetIconPathUnderSubdir(const std::string& icon_name, const std::string& subdir); // Whether the theme loaded properly. bool IsValid() { return index_theme_loaded_; } // Read and parse |file| which is usually named 'index.theme' per theme spec. bool LoadIndexTheme(const FilePath& file); // Checks to see if the icons in |info| matches |size| (in pixels). Returns // 0 if they match, or the size difference in pixels. size_t MatchesSize(SubDirInfo* info, size_t size); // Yet another function to read a line. std::string ReadLine(FILE* fp); // Set directories to search for icons to the comma-separated list |dirs|. bool SetDirectories(const std::string& dirs); bool index_theme_loaded_; // True if an instance is properly loaded. // store the scattered directories of this theme. std::list<FilePath> dirs_; // store the subdirs of this theme and array index of |info_array_|. std::map<std::string, int> subdirs_; scoped_ptr<SubDirInfo[]> info_array_; // List of sub-directories. std::string inherits_; // Name of the theme this one inherits from. }; IconTheme::IconTheme(const std::string& name) : index_theme_loaded_(false) { ThreadRestrictions::AssertIOAllowed(); // Iterate on all icon directories to find directories of the specified // theme and load the first encountered index.theme. MimeUtilConstants::IconDirMtimeMap::iterator iter; FilePath theme_path; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &MimeUtilConstants::GetInstance()->icon_dirs_; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { theme_path = iter->first.Append(name); if (!DirectoryExists(theme_path)) continue; FilePath theme_index = theme_path.Append("index.theme"); if (!index_theme_loaded_ && PathExists(theme_index)) { if (!LoadIndexTheme(theme_index)) return; index_theme_loaded_ = true; } dirs_.push_back(theme_path); } } FilePath IconTheme::GetIconPath(const std::string& icon_name, int size, bool inherits) { std::map<std::string, int>::iterator subdir_iter; FilePath icon_path; for (subdir_iter = subdirs_.begin(); subdir_iter != subdirs_.end(); ++subdir_iter) { SubDirInfo* info = &info_array_[subdir_iter->second]; if (MatchesSize(info, size) == 0) { icon_path = GetIconPathUnderSubdir(icon_name, subdir_iter->first); if (!icon_path.empty()) return icon_path; } } // Now looking for the mostly matched. size_t min_delta_seen = 9999; for (subdir_iter = subdirs_.begin(); subdir_iter != subdirs_.end(); ++subdir_iter) { SubDirInfo* info = &info_array_[subdir_iter->second]; size_t delta = MatchesSize(info, size); if (delta < min_delta_seen) { FilePath path = GetIconPathUnderSubdir(icon_name, subdir_iter->first); if (!path.empty()) { min_delta_seen = delta; icon_path = path; } } } if (!icon_path.empty() || !inherits || inherits_ == "") return icon_path; IconTheme* theme = LoadTheme(inherits_); // Inheriting from itself means the theme is buggy but we shouldn't crash. if (theme && theme != this) return theme->GetIconPath(icon_name, size, inherits); else return FilePath(); } IconTheme* IconTheme::LoadTheme(const std::string& theme_name) { scoped_ptr<IconTheme> theme; MimeUtilConstants::IconThemeMap* icon_themes = &MimeUtilConstants::GetInstance()->icon_themes_; if (icon_themes->find(theme_name) != icon_themes->end()) { theme.reset((*icon_themes)[theme_name]); } else { theme.reset(new IconTheme(theme_name)); if (!theme->IsValid()) theme.reset(); (*icon_themes)[theme_name] = theme.get(); } return theme.release(); } FilePath IconTheme::GetIconPathUnderSubdir(const std::string& icon_name, const std::string& subdir) { FilePath icon_path; std::list<FilePath>::iterator dir_iter; MimeUtilConstants::IconFormats* icon_formats = &MimeUtilConstants::GetInstance()->icon_formats_; for (dir_iter = dirs_.begin(); dir_iter != dirs_.end(); ++dir_iter) { for (size_t i = 0; i < icon_formats->size(); ++i) { icon_path = dir_iter->Append(subdir); icon_path = icon_path.Append(icon_name + (*icon_formats)[i]); if (PathExists(icon_path)) return icon_path; } } return FilePath(); } bool IconTheme::LoadIndexTheme(const FilePath& file) { FILE* fp = base::OpenFile(file, "r"); SubDirInfo* current_info = NULL; if (!fp) return false; // Read entries. while (!feof(fp) && !ferror(fp)) { std::string buf = ReadLine(fp); if (buf == "") break; std::string entry; TrimWhitespaceASCII(buf, TRIM_ALL, &entry); if (entry.length() == 0 || entry[0] == '#') { // Blank line or Comment. continue; } else if (entry[0] == '[' && info_array_.get()) { current_info = NULL; std::string subdir = entry.substr(1, entry.length() - 2); if (subdirs_.find(subdir) != subdirs_.end()) current_info = &info_array_[subdirs_[subdir]]; } std::string key, value; std::vector<std::string> r; SplitStringDontTrim(entry, '=', &r); if (r.size() < 2) continue; TrimWhitespaceASCII(r[0], TRIM_ALL, &key); for (size_t i = 1; i < r.size(); i++) value.append(r[i]); TrimWhitespaceASCII(value, TRIM_ALL, &value); if (current_info) { if (key == "Size") { current_info->size = atoi(value.c_str()); } else if (key == "Type") { if (value == "Fixed") current_info->type = SubDirInfo::Fixed; else if (value == "Scalable") current_info->type = SubDirInfo::Scalable; else if (value == "Threshold") current_info->type = SubDirInfo::Threshold; } else if (key == "MaxSize") { current_info->max_size = atoi(value.c_str()); } else if (key == "MinSize") { current_info->min_size = atoi(value.c_str()); } else if (key == "Threshold") { current_info->threshold = atoi(value.c_str()); } } else { if (key.compare("Directories") == 0 && !info_array_.get()) { if (!SetDirectories(value)) break; } else if (key.compare("Inherits") == 0) { if (value != "hicolor") inherits_ = value; } } } base::CloseFile(fp); return info_array_.get() != NULL; } size_t IconTheme::MatchesSize(SubDirInfo* info, size_t size) { if (info->type == SubDirInfo::Fixed) { if (size > info->size) return size - info->size; else return info->size - size; } else if (info->type == SubDirInfo::Scalable) { if (size < info->min_size) return info->min_size - size; if (size > info->max_size) return size - info->max_size; return 0; } else { if (size + info->threshold < info->size) return info->size - size - info->threshold; if (size > info->size + info->threshold) return size - info->size - info->threshold; return 0; } } std::string IconTheme::ReadLine(FILE* fp) { if (!fp) return std::string(); std::string result; const size_t kBufferSize = 100; char buffer[kBufferSize]; while ((fgets(buffer, kBufferSize - 1, fp)) != NULL) { result += buffer; size_t len = result.length(); if (len == 0) break; char end = result[len - 1]; if (end == '\n' || end == '\0') break; } return result; } bool IconTheme::SetDirectories(const std::string& dirs) { int num = 0; std::string::size_type pos = 0, epos; std::string dir; while ((epos = dirs.find(',', pos)) != std::string::npos) { TrimWhitespaceASCII(dirs.substr(pos, epos - pos), TRIM_ALL, &dir); if (dir.length() == 0) { DLOG(WARNING) << "Invalid index.theme: blank subdir"; return false; } subdirs_[dir] = num++; pos = epos + 1; } TrimWhitespaceASCII(dirs.substr(pos), TRIM_ALL, &dir); if (dir.length() == 0) { DLOG(WARNING) << "Invalid index.theme: blank subdir"; return false; } subdirs_[dir] = num++; info_array_.reset(new SubDirInfo[num]); return true; } bool CheckDirExistsAndGetMtime(const FilePath& dir, Time* last_modified) { if (!DirectoryExists(dir)) return false; File::Info file_info; if (!GetFileInfo(dir, &file_info)) return false; *last_modified = file_info.last_modified; return true; } // Make sure |dir| exists and add it to the list of icon directories. void TryAddIconDir(const FilePath& dir) { Time last_modified; if (!CheckDirExistsAndGetMtime(dir, &last_modified)) return; MimeUtilConstants::GetInstance()->icon_dirs_[dir] = last_modified; } // For a xdg directory |dir|, add the appropriate icon sub-directories. void AddXDGDataDir(const FilePath& dir) { if (!DirectoryExists(dir)) return; TryAddIconDir(dir.Append("icons")); TryAddIconDir(dir.Append("pixmaps")); } // Add all the xdg icon directories. void InitIconDir() { FilePath home = GetHomeDir(); if (!home.empty()) { FilePath legacy_data_dir(home); legacy_data_dir = legacy_data_dir.AppendASCII(".icons"); if (DirectoryExists(legacy_data_dir)) TryAddIconDir(legacy_data_dir); } const char* env = getenv("XDG_DATA_HOME"); if (env) { AddXDGDataDir(FilePath(env)); } else if (!home.empty()) { FilePath local_data_dir(home); local_data_dir = local_data_dir.AppendASCII(".local"); local_data_dir = local_data_dir.AppendASCII("share"); AddXDGDataDir(local_data_dir); } env = getenv("XDG_DATA_DIRS"); if (!env) { AddXDGDataDir(FilePath("/usr/local/share")); AddXDGDataDir(FilePath("/usr/share")); } else { std::string xdg_data_dirs = env; std::string::size_type pos = 0, epos; while ((epos = xdg_data_dirs.find(':', pos)) != std::string::npos) { AddXDGDataDir(FilePath(xdg_data_dirs.substr(pos, epos - pos))); pos = epos + 1; } AddXDGDataDir(FilePath(xdg_data_dirs.substr(pos))); } } void EnsureUpdated() { MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); if (constants->last_check_time_.is_null()) { constants->last_check_time_ = TimeTicks::Now(); InitIconDir(); return; } // Per xdg theme spec, we should check the icon directories every so often // for newly added icons. TimeDelta time_since_last_check = TimeTicks::Now() - constants->last_check_time_; if (time_since_last_check.InSeconds() > constants->kUpdateIntervalInSeconds) { constants->last_check_time_ += time_since_last_check; bool rescan_icon_dirs = false; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &constants->icon_dirs_; MimeUtilConstants::IconDirMtimeMap::iterator iter; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { Time last_modified; if (!CheckDirExistsAndGetMtime(iter->first, &last_modified) || last_modified != iter->second) { rescan_icon_dirs = true; break; } } if (rescan_icon_dirs) { constants->icon_dirs_.clear(); constants->icon_themes_.clear(); InitIconDir(); } } } // Find a fallback icon if we cannot find it in the default theme. FilePath LookupFallbackIcon(const std::string& icon_name) { MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); MimeUtilConstants::IconDirMtimeMap::iterator iter; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &constants->icon_dirs_; MimeUtilConstants::IconFormats* icon_formats = &constants->icon_formats_; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { for (size_t i = 0; i < icon_formats->size(); ++i) { FilePath icon = iter->first.Append(icon_name + (*icon_formats)[i]); if (PathExists(icon)) return icon; } } return FilePath(); } // Initialize the list of default themes. void InitDefaultThemes() { IconTheme** default_themes = MimeUtilConstants::GetInstance()->default_themes_; scoped_ptr<Environment> env(Environment::Create()); base::nix::DesktopEnvironment desktop_env = base::nix::GetDesktopEnvironment(env.get()); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4) { // KDE std::string kde_default_theme; std::string kde_fallback_theme; // TODO(thestig): Figure out how to get the current icon theme on KDE. // Setting stored in ~/.kde/share/config/kdeglobals under Icons -> Theme. default_themes[0] = NULL; // Try some reasonable defaults for KDE. if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { // KDE 3 kde_default_theme = "default.kde"; kde_fallback_theme = "crystalsvg"; } else { // KDE 4 kde_default_theme = "default.kde4"; kde_fallback_theme = "oxygen"; } default_themes[1] = IconTheme::LoadTheme(kde_default_theme); default_themes[2] = IconTheme::LoadTheme(kde_fallback_theme); } else { // Assume it's Gnome and use GTK to figure out the theme. default_themes[1] = IconTheme::LoadTheme( MimeUtilConstants::GetInstance()->icon_theme_name_); default_themes[2] = IconTheme::LoadTheme("gnome"); } // hicolor needs to be last per icon theme spec. default_themes[3] = IconTheme::LoadTheme("hicolor"); for (size_t i = 0; i < MimeUtilConstants::kDefaultThemeNum; i++) { if (default_themes[i] == NULL) continue; // NULL out duplicate pointers. for (size_t j = i + 1; j < MimeUtilConstants::kDefaultThemeNum; j++) { if (default_themes[j] == default_themes[i]) default_themes[j] = NULL; } } } // Try to find an icon with the name |icon_name| that's |size| pixels. FilePath LookupIconInDefaultTheme(const std::string& icon_name, int size) { EnsureUpdated(); MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); MimeUtilConstants::IconThemeMap* icon_themes = &constants->icon_themes_; if (icon_themes->empty()) InitDefaultThemes(); FilePath icon_path; IconTheme** default_themes = constants->default_themes_; for (size_t i = 0; i < MimeUtilConstants::kDefaultThemeNum; i++) { if (default_themes[i]) { icon_path = default_themes[i]->GetIconPath(icon_name, size, true); if (!icon_path.empty()) return icon_path; } } return LookupFallbackIcon(icon_name); } MimeUtilConstants::~MimeUtilConstants() { for (size_t i = 0; i < kDefaultThemeNum; i++) delete default_themes_[i]; } } // namespace std::string GetFileMimeType(const FilePath& filepath) { if (filepath.empty()) return std::string(); ThreadRestrictions::AssertIOAllowed(); AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); return xdg_mime_get_mime_type_from_file_name(filepath.value().c_str()); } std::string GetDataMimeType(const std::string& data) { ThreadRestrictions::AssertIOAllowed(); AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); return xdg_mime_get_mime_type_for_data(data.data(), data.length(), NULL); } void SetIconThemeName(const std::string& name) { // If the theme name is already loaded, do nothing. Chrome doesn't respond // to changes in the system theme, so we never need to set this more than // once. if (!MimeUtilConstants::GetInstance()->icon_theme_name_.empty()) return; MimeUtilConstants::GetInstance()->icon_theme_name_ = name; } FilePath GetMimeIcon(const std::string& mime_type, size_t size) { ThreadRestrictions::AssertIOAllowed(); std::vector<std::string> icon_names; std::string icon_name; FilePath icon_file; if (!mime_type.empty()) { AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); const char *icon = xdg_mime_get_icon(mime_type.c_str()); icon_name = std::string(icon ? icon : ""); } if (icon_name.length()) icon_names.push_back(icon_name); // For text/plain, try text-plain. icon_name = mime_type; for (size_t i = icon_name.find('/', 0); i != std::string::npos; i = icon_name.find('/', i + 1)) { icon_name[i] = '-'; } icon_names.push_back(icon_name); // Also try gnome-mime-text-plain. icon_names.push_back("gnome-mime-" + icon_name); // Try "deb" for "application/x-deb" in KDE 3. size_t x_substr_pos = mime_type.find("/x-"); if (x_substr_pos != std::string::npos) { icon_name = mime_type.substr(x_substr_pos + 3); icon_names.push_back(icon_name); } // Try generic name like text-x-generic. icon_name = mime_type.substr(0, mime_type.find('/')) + "-x-generic"; icon_names.push_back(icon_name); // Last resort icon_names.push_back("unknown"); for (size_t i = 0; i < icon_names.size(); i++) { if (icon_names[i][0] == '/') { icon_file = FilePath(icon_names[i]); if (PathExists(icon_file)) return icon_file; } else { icon_file = LookupIconInDefaultTheme(icon_names[i], size); if (!icon_file.empty()) return icon_file; } } return FilePath(); } } // namespace nix } // namespace base
Java
package ca.uhn.fhir.cql.dstu3.builder; /*- * #%L * HAPI FHIR JPA Server - Clinical Quality Language * %% * Copyright (C) 2014 - 2022 Smile CDR, Inc. * %% * 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. * #L% */ import ca.uhn.fhir.cql.common.builder.BaseBuilder; import org.hl7.fhir.dstu3.model.MeasureReport; import org.hl7.fhir.dstu3.model.Period; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.exceptions.FHIRException; import org.opencds.cqf.cql.engine.runtime.Interval; import java.util.Date; public class MeasureReportBuilder extends BaseBuilder<MeasureReport> { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MeasureReportBuilder.class); public MeasureReportBuilder() { super(new MeasureReport()); } public MeasureReportBuilder buildStatus(String status) { try { this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.fromCode(status)); } catch (FHIRException e) { ourLog.warn("Exception caught while attempting to set Status to '" + status + "', assuming status COMPLETE!" + System.lineSeparator() + e.getMessage()); this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.COMPLETE); } return this; } public MeasureReportBuilder buildType(MeasureReport.MeasureReportType type) { this.complexProperty.setType(type); return this; } public MeasureReportBuilder buildMeasureReference(String measureRef) { this.complexProperty.setMeasure(new Reference(measureRef)); return this; } public MeasureReportBuilder buildPatientReference(String patientRef) { this.complexProperty.setPatient(new Reference(patientRef)); return this; } public MeasureReportBuilder buildPeriod(Interval period) { this.complexProperty.setPeriod(new Period().setStart((Date) period.getStart()).setEnd((Date) period.getEnd())); return this; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_102) on Thu Sep 29 16:37:39 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class energy.usef.agr.model.SynchronisationConnection (usef-root-pom 1.3.6 API)</title> <meta name="date" content="2016-09-29"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class energy.usef.agr.model.SynchronisationConnection (usef-root-pom 1.3.6 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?energy/usef/agr/model/class-use/SynchronisationConnection.html" target="_top">Frames</a></li> <li><a href="SynchronisationConnection.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class energy.usef.agr.model.SynchronisationConnection" class="title">Uses of Class<br>energy.usef.agr.model.SynchronisationConnection</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#energy.usef.agr.model">energy.usef.agr.model</a></td> <td class="colLast"> <div class="block">Model classes of the Aggregator.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#energy.usef.agr.repository">energy.usef.agr.repository</a></td> <td class="colLast"> <div class="block">Repository classes of the Aggregator.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#energy.usef.agr.service.business">energy.usef.agr.service.business</a></td> <td class="colLast"> <div class="block">Business classes of the Aggregator.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="energy.usef.agr.model"> <!-- --> </a> <h3>Uses of <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a> in <a href="../../../../../energy/usef/agr/model/package-summary.html">energy.usef.agr.model</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../energy/usef/agr/model/package-summary.html">energy.usef.agr.model</a> that return <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></code></td> <td class="colLast"><span class="typeNameLabel">SynchronisationConnectionStatus.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/model/SynchronisationConnectionStatus.html#getSynchronisationConnection--">getSynchronisationConnection</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../energy/usef/agr/model/package-summary.html">energy.usef.agr.model</a> with parameters of type <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">SynchronisationConnectionStatus.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/model/SynchronisationConnectionStatus.html#setSynchronisationConnection-energy.usef.agr.model.SynchronisationConnection-">setSynchronisationConnection</a></span>(<a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a>&nbsp;synchronisationConnection)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="energy.usef.agr.repository"> <!-- --> </a> <h3>Uses of <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a> in <a href="../../../../../energy/usef/agr/repository/package-summary.html">energy.usef.agr.repository</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../energy/usef/agr/repository/package-summary.html">energy.usef.agr.repository</a> that return <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></code></td> <td class="colLast"><span class="typeNameLabel">SynchronisationConnectionRepository.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/repository/SynchronisationConnectionRepository.html#findByEntityAddress-java.lang.String-">findByEntityAddress</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;entityAddress)</code> <div class="block">Gets Synchronisation Connection entity by its entity address.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../energy/usef/agr/repository/package-summary.html">energy.usef.agr.repository</a> that return types with arguments of type <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">SynchronisationConnectionRepository.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/repository/SynchronisationConnectionRepository.html#findAll--">findAll</a></span>()</code> <div class="block">Gets all the connections.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../energy/usef/agr/repository/package-summary.html">energy.usef.agr.repository</a> with parameters of type <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">SynchronisationConnectionStatusRepository.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/repository/SynchronisationConnectionStatusRepository.html#deleteFor-energy.usef.agr.model.SynchronisationConnection-">deleteFor</a></span>(<a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a>&nbsp;synchronisationConnection)</code> <div class="block">Deletes all the <a href="../../../../../energy/usef/agr/model/SynchronisationConnectionStatus.html" title="class in energy.usef.agr.model"><code>SynchronisationConnectionStatus</code></a> object for a .</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="energy.usef.agr.service.business"> <!-- --> </a> <h3>Uses of <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a> in <a href="../../../../../energy/usef/agr/service/business/package-summary.html">energy.usef.agr.service.business</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../energy/usef/agr/service/business/package-summary.html">energy.usef.agr.service.business</a> that return types with arguments of type <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a>&lt;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">SynchronisationConnection</a>&gt;&gt;</code></td> <td class="colLast"><span class="typeNameLabel">AgrPlanboardBusinessService.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/service/business/AgrPlanboardBusinessService.html#findConnectionsPerCRO--">findConnectionsPerCRO</a></span>()</code> <div class="block">Finds all <a href="../../../../../energy/usef/agr/model/CommonReferenceOperator.html" title="class in energy.usef.agr.model"><code>CommonReferenceOperator</code></a>s and <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model"><code>SynchronisationConnection</code></a>s and put them in a Map, all <a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model"><code>SynchronisationConnection</code></a>s are send to all <a href="../../../../../energy/usef/agr/model/CommonReferenceOperator.html" title="class in energy.usef.agr.model"><code>CommonReferenceOperator</code></a>s.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../energy/usef/agr/model/SynchronisationConnection.html" title="class in energy.usef.agr.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?energy/usef/agr/model/class-use/SynchronisationConnection.html" target="_top">Frames</a></li> <li><a href="SynchronisationConnection.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2016. All rights reserved.</small></p> </body> </html>
Java
/* * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.carbon.event.output.adapter.wso2event; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.databridge.agent.AgentHolder; import org.wso2.carbon.databridge.agent.DataPublisher; import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointException; import org.wso2.carbon.databridge.commons.Event; import org.wso2.carbon.databridge.commons.exception.TransportException; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; import org.wso2.carbon.event.output.adapter.core.exception.ConnectionUnavailableException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException; import org.wso2.carbon.event.output.adapter.core.exception.TestConnectionNotSupportedException; import org.wso2.carbon.event.output.adapter.wso2event.internal.util.WSO2EventAdapterConstants; import java.util.Map; import static org.wso2.carbon.event.output.adapter.wso2event.internal.util.WSO2EventAdapterConstants.*; public final class WSO2EventAdapter implements OutputEventAdapter { private static final Log log = LogFactory.getLog(WSO2EventAdapter.class); private final OutputEventAdapterConfiguration eventAdapterConfiguration; private final Map<String, String> globalProperties; private DataPublisher dataPublisher = null; private boolean isBlockingMode = false; private long timeout = 0; private String streamId; public WSO2EventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, Map<String, String> globalProperties) { this.eventAdapterConfiguration = eventAdapterConfiguration; this.globalProperties = globalProperties; } /** * Initialises the resource bundle */ @Override public void init() { streamId = eventAdapterConfiguration.getStaticProperties().get( WSO2EventAdapterConstants.ADAPTER_STATIC_CONFIG_STREAM_NAME) + ":" + eventAdapterConfiguration.getStaticProperties().get(WSO2EventAdapterConstants .ADAPTER_STATIC_CONFIG_STREAM_VERSION); String configPath = globalProperties.get(ADAPTOR_CONF_PATH); if (configPath != null) { AgentHolder.setConfigPath(configPath); } } @Override public void testConnect() throws TestConnectionNotSupportedException { connect(); } @Override public synchronized void connect() { String userName = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_USER_NAME); String password = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_PASSWORD); String authUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_AUTHENTICATOR_URL); String receiverUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_RECEIVER_URL); String protocol = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_PROTOCOL); String publishingMode = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_PUBLISHING_MODE); String timeoutString = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_PUBLISH_TIMEOUT_MS); if (publishingMode.equalsIgnoreCase(ADAPTER_PUBLISHING_MODE_BLOCKING)) { isBlockingMode = true; } else { try { timeout = Long.parseLong(timeoutString); } catch (RuntimeException e) { throwRuntimeException(receiverUrl, authUrl, protocol, userName, e); } } try { if (authUrl != null && authUrl.length() > 0) { dataPublisher = new DataPublisher(protocol, receiverUrl, authUrl, userName, password); } else { dataPublisher = new DataPublisher(protocol, receiverUrl, null, userName, password); } } catch (DataEndpointAgentConfigurationException e) { throwRuntimeException(receiverUrl, authUrl, protocol, userName, e); } catch (DataEndpointException e) { throwConnectionException(receiverUrl, authUrl, protocol, userName, e); } catch (DataEndpointConfigurationException e) { throwRuntimeException(receiverUrl, authUrl, protocol, userName, e); } catch (DataEndpointAuthenticationException e) { throwConnectionException(receiverUrl, authUrl, protocol, userName, e); } catch (TransportException e) { throwConnectionException(receiverUrl, authUrl, protocol, userName, e); } } @Override public void publish(Object message, Map<String, String> dynamicProperties) { Event event = (Event) (message); //StreamDefinition streamDefinition = (StreamDefinition) ((Object[]) message)[1]; event.setStreamId(streamId); if (isBlockingMode) { dataPublisher.publish(event); } else { dataPublisher.tryPublish(event, timeout); } } @Override public void disconnect() { if (dataPublisher != null) { try { dataPublisher.shutdown(); } catch (DataEndpointException e) { String userName = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_USER_NAME); String authUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_AUTHENTICATOR_URL); String receiverUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_RECEIVER_URL); String protocol = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_PROTOCOL); logException("Error in shutting down the data publisher", receiverUrl, authUrl, protocol, userName, e); } } } @Override public void destroy() { } private void throwRuntimeException(String receiverUrl, String authUrl, String protocol, String userName, Exception e) { throw new OutputEventAdapterRuntimeException( "Error in data-bridge config for adaptor " + eventAdapterConfiguration.getName() + " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol + " and userName:" + userName + "," + e.getMessage(), e); } private void logException(String message, String receiverUrl, String authUrl, String protocol, String userName, Exception e) { log.error(message + " for adaptor " + eventAdapterConfiguration.getName() + " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol + " and userName:" + userName + "," + e.getMessage(), e); } private void throwConnectionException(String receiverUrl, String authUrl, String protocol, String userName, Exception e) { throw new ConnectionUnavailableException( "Connection not available for adaptor " + eventAdapterConfiguration.getName() + " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol + " and userName:" + userName + "," + e.getMessage(), e); } }
Java
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA """ import logging _logger = logging.getLogger('websocket') try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass _logger.addHandler(NullHandler()) _traceEnabled = False __all__ = ["enableTrace", "dump", "error", "warning", "debug", "trace", "isEnabledForError", "isEnabledForDebug", "isEnabledForTrace"] def enableTrace(traceable, handler = logging.StreamHandler()): """ turn on/off the traceability. traceable: boolean value. if set True, traceability is enabled. """ global _traceEnabled _traceEnabled = traceable if traceable: _logger.addHandler(handler) _logger.setLevel(logging.DEBUG) def dump(title, message): if _traceEnabled: _logger.debug("--- " + title + " ---") _logger.debug(message) _logger.debug("-----------------------") def error(msg): _logger.error(msg) def warning(msg): _logger.warning(msg) def debug(msg): _logger.debug(msg) def trace(msg): if _traceEnabled: _logger.debug(msg) def isEnabledForError(): return _logger.isEnabledFor(logging.ERROR) def isEnabledForDebug(): return _logger.isEnabledFor(logging.DEBUG) def isEnabledForTrace(): return _traceEnabled
Java
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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. import pytest from mock import Mock from calvin.tests import DummyNode from calvin.runtime.north.actormanager import ActorManager from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint from calvin.actor.actor import Actor pytestmark = pytest.mark.unittest def create_actor(node): actor_manager = ActorManager(node) actor_id = actor_manager.new('std.Identity', {}) actor = actor_manager.actors[actor_id] actor._calvinsys = Mock() return actor @pytest.fixture def actor(): return create_actor(DummyNode()) @pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [ ("invalid", "", "", "", False), ("in", "missing", "", "", False), ("out", "missing", "", "", False), ("out", "token", "missing", "", False), ("in", "token", "missing", "", False), ("out", "token", "name", "new_name", True), ("out", "token", "name", "new_name", True), ]) def test_set_port_property(port_type, port_name, port_property, value, expected): assert actor().set_port_property(port_type, port_name, port_property, value) is expected @pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [ (False, False, False), (False, True, False), (True, False, False), (True, True, True), ]) def test_did_connect(actor, inport_ret_val, outport_ret_val, expected): for port in actor.inports.values(): port.is_connected = Mock(return_value=inport_ret_val) for port in actor.outports.values(): port.is_connected = Mock(return_value=outport_ret_val) actor.fsm = Mock() actor.did_connect(None) if expected: actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED) assert actor._calvinsys.scheduler_wakeup.called else: assert not actor.fsm.transition_to.called assert not actor._calvinsys.scheduler_wakeup.called @pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [ (True, True, False), (True, False, False), (False, True, False), (False, False, True), ]) def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected): for port in actor.inports.values(): port.is_connected = Mock(return_value=inport_ret_val) for port in actor.outports.values(): port.is_connected = Mock(return_value=outport_ret_val) actor.fsm = Mock() actor.did_disconnect(None) if expected: actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY) else: assert not actor.fsm.transition_to.called def test_enabled(actor): actor.enable() assert actor.enabled() actor.disable() assert not actor.enabled() def test_connections(): node = DummyNode() node.id = "node_id" actor = create_actor(node) inport = actor.inports['token'] outport = actor.outports['token'] port = Mock() port.id = "x" peer_port = Mock() peer_port.id = "y" inport.attach_endpoint(LocalInEndpoint(port, peer_port)) outport.attach_endpoint(LocalOutEndpoint(port, peer_port)) assert actor.connections(node) == { 'actor_id': actor.id, 'actor_name': actor.name, 'inports': {inport.id: (node, "y")}, 'outports': {outport.id: [(node, "y")]} } def test_state(actor): inport = actor.inports['token'] outport = actor.outports['token'] correct_state = { '_component_members': set([actor.id]), '_deployment_requirements': [], '_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']), '_signature': None, 'dump': False, 'id': actor.id, 'inports': {'token': {'fifo': {'N': 5, 'fifo': [{'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}], 'read_pos': {inport.id: 0}, 'readers': [inport.id], 'tentative_read_pos': {inport.id: 0}, 'write_pos': 0}, 'id': inport.id, 'name': 'token'}}, 'name': '', 'outports': {'token': {'fanout': 1, 'fifo': {'N': 5, 'fifo': [{'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}, {'data': 0, 'type': 'Token'}], 'read_pos': {}, 'readers': [], 'tentative_read_pos': {}, 'write_pos': 0}, 'id': outport.id, 'name': 'token'}}} test_state = actor.state() for k, v in correct_state.iteritems(): # Read state use list to support JSON serialization if isinstance(v, set): assert set(test_state[k]) == v else: assert test_state[k] == v @pytest.mark.parametrize("prev_signature,new_signature,expected", [ (None, "new_val", "new_val"), ("old_val", "new_val", "old_val") ]) def test_set_signature(actor, prev_signature, new_signature, expected): actor.signature_set(prev_signature) actor.signature_set(new_signature) assert actor._signature == expected def test_component(actor): actor.component_add(1) assert 1 in actor.component_members() actor.component_add([2, 3]) assert 2 in actor.component_members() assert 3 in actor.component_members() actor.component_remove(1) assert 1 not in actor.component_members() actor.component_remove([2, 3]) assert 2 not in actor.component_members() assert 3 not in actor.component_members() def test_requirements(actor): assert actor.requirements_get() == [] actor.requirements_add([1, 2, 3]) assert actor.requirements_get() == [1, 2, 3] actor.requirements_add([4, 5]) assert actor.requirements_get() == [4, 5] actor.requirements_add([6, 7], extend=True) assert actor.requirements_get() == [4, 5, 6, 7]
Java
#!/var/www/horizon/.venv/bin/python # $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing Docutils XML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates Docutils-native XML from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='xml', description=description)
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Search &mdash; Paramiko documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/searchtools.js"></script> <link rel="top" title="Paramiko documentation" href="index.html" /> <script type="text/javascript"> jQuery(function() { Search.loadIndex("searchindex.js"); }); </script> <script type="text/javascript" id="searchindexloader"></script> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9"> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">Paramiko documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1 id="search-documentation">Search</h1> <div id="fallback" class="admonition warning"> <script type="text/javascript">$('#fallback').hide();</script> <p> Please activate JavaScript to enable the search functionality. </p> </div> <p> From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. </p> <form action="" method="get"> <input type="text" name="q" value="" /> <input type="submit" value="search" /> <span id="search-progress" style="padding-left: 10px"></span> </form> <div id="search-results"> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h1 class="logo"><a href="index.html">Paramiko</a></h1> <p class="blurb">A Python implementation of SSHv2.</p> <p> <iframe src="http://ghbtns.com/github-btn.html?user=paramiko&repo=paramiko&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe> </p> <p> <a href="https://travis-ci.org/paramiko/paramiko"> <img alt="https://secure.travis-ci.org/paramiko/paramiko.png?branch=master" src="https://secure.travis-ci.org/paramiko/paramiko.png?branch=master" > </a> </p> <h3>Navigation</h3> <ul> <li class="toctree-l1"><a class="reference internal" href="api/channel.html">Channel</a></li> <li class="toctree-l1"><a class="reference internal" href="api/client.html">Client</a></li> <li class="toctree-l1"><a class="reference internal" href="api/message.html">Message</a></li> <li class="toctree-l1"><a class="reference internal" href="api/packet.html">Packetizer</a></li> <li class="toctree-l1"><a class="reference internal" href="api/transport.html">Transport</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="api/agent.html">SSH Agents</a></li> <li class="toctree-l1"><a class="reference internal" href="api/hostkeys.html">Host keys / <tt class="docutils literal"><span class="pre">known_hosts</span></tt> files</a></li> <li class="toctree-l1"><a class="reference internal" href="api/keys.html">Key handling</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="api/config.html">Configuration</a></li> <li class="toctree-l1"><a class="reference internal" href="api/proxy.html"><tt class="docutils literal"><span class="pre">ProxyCommand</span></tt> support</a></li> <li class="toctree-l1"><a class="reference internal" href="api/server.html">Server implementation</a></li> <li class="toctree-l1"><a class="reference internal" href="api/sftp.html">SFTP</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="api/buffered_pipe.html">Buffered pipes</a></li> <li class="toctree-l1"><a class="reference internal" href="api/file.html">Buffered files</a></li> <li class="toctree-l1"><a class="reference internal" href="api/pipe.html">Cross-platform pipe implementations</a></li> <li class="toctree-l1"><a class="reference internal" href="api/ssh_exception.html">Exceptions</a></li> </ul> <hr /> <ul> <li class="toctree-l1"><a href="http://www.paramiko.org">Main website</a></li> </ul> <h3>Donate</h3> <p> Consider supporting the authors on <a href="https://www.gittip.com/">Gittip</a>: <iframe style="border: 0; margin: 5px 0 -5px 0; padding: 0;" src="https://www.gittip.com/bitprophet/widget.html" width="48pt" height="20pt"></iframe> </p> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2014 Jeff Forcier. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.2.2</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.6.0</a> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-18486793-2']); _gaq.push(['_setDomainName', 'none']); _gaq.push(['_setAllowLinker', true]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
Java
<?xml version="1.0" encoding="UTF-8"?> <html xmlns:extrep="http://www.sun.com/japex/extendedTestSuiteReport" xmlns:rep="http://www.sun.com/japex/testSuiteReport" xmlns="http://www.w3.org/1999/xhtml"> <link href="report.css" type="text/css" rel="stylesheet"/> <body> <table border="0" cellpadding="2"> <tr> <td valign="middle" width="90"> <p> <a href="https://japex.dev.java.net"> <img src="small_japex.gif" align="middle" border="0"/> </a> </p> </td> <td valign="middle"> <h1>Japex Report: FI-serialize</h1> </td> </tr> </table> <h2>Global Parameters</h2> <ul> <li>chartType: barchart</li> <li>classPath: <table width=750><tr><td>japex/dist/jdsl/FastInfoset.jar; japex/dist/jdsl/activation.jar; japex/dist/jdsl/jaxb-api.jar; japex/dist/jdsl/jaxb-impl.jar; japex/dist/jdsl/jaxb-xjc.jar; japex/dist/jdsl/jaxb1-impl.jar; japex/dist/jdsl/jdsl.jar; japex/dist/jdsl/jsr173_api.jar; japex/dist/jdsl/resolver.jar; japex/dist/jdsl/sjsxp.jar; japex/dist/jdsl/xercesImpl.jar; japex/dist/jdsl/xml-apis.jar</td></tr></table></li> <li>configFile: serialize.xml</li> <li>dateTime: 23 Jan 2006/13:44:19 EST</li> <li>includeWarmupRun: false</li> <li>numberOfThreads: 1</li> <li>osArchitecture: x86</li> <li>osName: SunOS</li> <li>reportsDirectory: reports</li> <li>resultAxis: normal</li> <li>resultAxisX: normal</li> <li>resultUnit: ms</li> <li>resultUnitX: kbs</li> <li>runsPerDriver: 1</li> <li>runTime: 5</li> <li>version: 1.000</li> <li>vmInfo: Sun Microsystems Inc. 1.5.0_04-b05</li> <li>warmupTime: 5</li> </ul> <h2>Result Summary (ms)</h2> <table width="80%" border="1"> <thead> <tr> <th width="15%"> <b>driver</b> </th> <th> <b>resultAritMean</b> </th> <th> <b>resultHarmMean</b> </th> <th> <b>resultGeomMean</b> </th> <th> <b>driverClass</b> </th> </tr> </thead> <tbody> <tr> <td align="right">FastInfosetDOMDriver</td> <td align="right"> <nobr>10.702</nobr> </td> <td align="right"> <nobr>0.121</nobr> </td> <td align="right"> <nobr>0.963</nobr> </td> <td align="right"> <nobr>com.sun.japex.jdsl.xml.serialize.dom.FastInfosetDOMDriver</nobr> </td> </tr> <tr> <td align="right">FastInfosetDOM24IndexedContentDriver</td> <td align="right"> <nobr>10.978</nobr> </td> <td align="right"> <nobr>0.123</nobr> </td> <td align="right"> <nobr>0.979</nobr> </td> <td align="right"> <nobr>com.sun.japex.jdsl.xml.serialize.dom.FastInfosetDOMDriver</nobr> </td> </tr> <tr> <td align="right">FastInfosetDOMExtVocab24IndexedContentDriver</td> <td align="right"> <nobr>10.981</nobr> </td> <td align="right"> <nobr>0.064</nobr> </td> <td align="right"> <nobr>0.794</nobr> </td> <td align="right"> <nobr>com.sun.japex.jdsl.xml.serialize.dom.FastInfosetDOMDriver</nobr> </td> </tr> <tr> <td align="right">XercesDOMXercesXMLSerializerDriver</td> <td align="right"> <nobr>20.996</nobr> </td> <td align="right"> <nobr>0.178</nobr> </td> <td align="right"> <nobr>1.550</nobr> </td> <td align="right"> <nobr>com.sun.japex.jdsl.xml.serialize.dom.XercesDOMXercesXMLSerializerDriver</nobr> </td> </tr> </tbody> </table> <br/> <br/> <center> <img src="result.jpg"/> </center> <br/> <br/> <h2>Driver: FastInfosetDOMDriver</h2> <p> <ul> <li>jdsl.attributeValueSizeLimit: n/a</li> <li>jdsl.characterContentChunkSizeLimit: n/a</li> <li>jdsl.externalVocabulary: n/a</li> </ul> </p> <table width="80%" border="1"> <thead> <tr> <th> <b>testCase</b> </th> <th> <b>resultValue</b> </th> <th> <b>xmlfile</b> </th> </tr> </thead> <tbody> <tr> <td align="right">inv1.xml</td> <td align="right"> <nobr>0.119</nobr> </td> <td align="left"> <nobr>data/inv1.xml</nobr> </td> </tr> <tr> <td align="right">inv10.xml</td> <td align="right"> <nobr>0.246</nobr> </td> <td align="left"> <nobr>data/inv10.xml</nobr> </td> </tr> <tr> <td align="right">inv50.xml</td> <td align="right"> <nobr>0.828</nobr> </td> <td align="left"> <nobr>data/inv50.xml</nobr> </td> </tr> <tr> <td align="right">inv100.xml</td> <td align="right"> <nobr>1.556</nobr> </td> <td align="left"> <nobr>data/inv100.xml</nobr> </td> </tr> <tr> <td align="right">inv500.xml</td> <td align="right"> <nobr>10.087</nobr> </td> <td align="left"> <nobr>data/inv500.xml</nobr> </td> </tr> <tr> <td align="right">inv1000.xml</td> <td align="right"> <nobr>20.269</nobr> </td> <td align="left"> <nobr>data/inv1000.xml</nobr> </td> </tr> <tr> <td align="right">soap1.xml</td> <td align="right"> <nobr>0.025</nobr> </td> <td align="left"> <nobr>data/soap1.xml</nobr> </td> </tr> <tr> <td align="right">soap2.xml</td> <td align="right"> <nobr>0.027</nobr> </td> <td align="left"> <nobr>data/soap2.xml</nobr> </td> </tr> <tr> <td align="right">soap3.xml</td> <td align="right"> <nobr>0.028</nobr> </td> <td align="left"> <nobr>data/soap3.xml</nobr> </td> </tr> <tr> <td align="right">soap4.xml</td> <td align="right"> <nobr>3.133</nobr> </td> <td align="left"> <nobr>data/soap4.xml</nobr> </td> </tr> <tr> <td align="right">db10.xml</td> <td align="right"> <nobr>0.049</nobr> </td> <td align="left"> <nobr>data/db10.xml</nobr> </td> </tr> <tr> <td align="right">db50.xml</td> <td align="right"> <nobr>0.207</nobr> </td> <td align="left"> <nobr>data/db50.xml</nobr> </td> </tr> <tr> <td align="right">db100.xml</td> <td align="right"> <nobr>0.410</nobr> </td> <td align="left"> <nobr>data/db100.xml</nobr> </td> </tr> <tr> <td align="right">db500.xml</td> <td align="right"> <nobr>2.034</nobr> </td> <td align="left"> <nobr>data/db500.xml</nobr> </td> </tr> <tr> <td align="right">db1000.xml</td> <td align="right"> <nobr>5.473</nobr> </td> <td align="left"> <nobr>data/db1000.xml</nobr> </td> </tr> <tr> <td align="right">db10000.xml</td> <td align="right"> <nobr>60.034</nobr> </td> <td align="left"> <nobr>data/db10000.xml</nobr> </td> </tr> <tr> <td align="right">xsl1.xml</td> <td align="right"> <nobr>0.037</nobr> </td> <td align="left"> <nobr>data/xsl1.xml</nobr> </td> </tr> <tr> <td align="right">xsl2.xml</td> <td align="right"> <nobr>0.175</nobr> </td> <td align="left"> <nobr>data/xsl2.xml</nobr> </td> </tr> <tr> <td align="right">xsl3.xml</td> <td align="right"> <nobr>0.567</nobr> </td> <td align="left"> <nobr>data/xsl3.xml</nobr> </td> </tr> <tr> <td align="right">xsl4.xml</td> <td align="right"> <nobr>11.067</nobr> </td> <td align="left"> <nobr>data/xsl4.xml</nobr> </td> </tr> <tr> <td align="right">periodic.xml</td> <td align="right"> <nobr>1.925</nobr> </td> <td align="left"> <nobr>data/periodic.xml</nobr> </td> </tr> <tr> <td align="right">weblog.xml</td> <td align="right"> <nobr>68.896</nobr> </td> <td align="left"> <nobr>data/weblog.xml</nobr> </td> </tr> <tr> <td align="right">factbook.xml</td> <td align="right"> <nobr>58.955</nobr> </td> <td align="left"> <nobr>data/factbook.xml</nobr> </td> </tr> </tbody> </table> <br/> <h2>Driver: FastInfosetDOM24IndexedContentDriver</h2> <p> <ul> <li>jdsl.attributeValueSizeLimit: 24</li> <li>jdsl.characterContentChunkSizeLimit: 24</li> <li>jdsl.externalVocabulary: n/a</li> </ul> </p> <table width="80%" border="1"> <thead> <tr> <th> <b>testCase</b> </th> <th> <b>resultValue</b> </th> <th> <b>xmlfile</b> </th> </tr> </thead> <tbody> <tr> <td align="right">inv1.xml</td> <td align="right"> <nobr>0.123</nobr> </td> <td align="left"> <nobr>data/inv1.xml</nobr> </td> </tr> <tr> <td align="right">inv10.xml</td> <td align="right"> <nobr>0.247</nobr> </td> <td align="left"> <nobr>data/inv10.xml</nobr> </td> </tr> <tr> <td align="right">inv50.xml</td> <td align="right"> <nobr>0.801</nobr> </td> <td align="left"> <nobr>data/inv50.xml</nobr> </td> </tr> <tr> <td align="right">inv100.xml</td> <td align="right"> <nobr>1.511</nobr> </td> <td align="left"> <nobr>data/inv100.xml</nobr> </td> </tr> <tr> <td align="right">inv500.xml</td> <td align="right"> <nobr>9.842</nobr> </td> <td align="left"> <nobr>data/inv500.xml</nobr> </td> </tr> <tr> <td align="right">inv1000.xml</td> <td align="right"> <nobr>19.648</nobr> </td> <td align="left"> <nobr>data/inv1000.xml</nobr> </td> </tr> <tr> <td align="right">soap1.xml</td> <td align="right"> <nobr>0.024</nobr> </td> <td align="left"> <nobr>data/soap1.xml</nobr> </td> </tr> <tr> <td align="right">soap2.xml</td> <td align="right"> <nobr>0.028</nobr> </td> <td align="left"> <nobr>data/soap2.xml</nobr> </td> </tr> <tr> <td align="right">soap3.xml</td> <td align="right"> <nobr>0.029</nobr> </td> <td align="left"> <nobr>data/soap3.xml</nobr> </td> </tr> <tr> <td align="right">soap4.xml</td> <td align="right"> <nobr>3.164</nobr> </td> <td align="left"> <nobr>data/soap4.xml</nobr> </td> </tr> <tr> <td align="right">db10.xml</td> <td align="right"> <nobr>0.051</nobr> </td> <td align="left"> <nobr>data/db10.xml</nobr> </td> </tr> <tr> <td align="right">db50.xml</td> <td align="right"> <nobr>0.222</nobr> </td> <td align="left"> <nobr>data/db50.xml</nobr> </td> </tr> <tr> <td align="right">db100.xml</td> <td align="right"> <nobr>0.434</nobr> </td> <td align="left"> <nobr>data/db100.xml</nobr> </td> </tr> <tr> <td align="right">db500.xml</td> <td align="right"> <nobr>2.081</nobr> </td> <td align="left"> <nobr>data/db500.xml</nobr> </td> </tr> <tr> <td align="right">db1000.xml</td> <td align="right"> <nobr>5.551</nobr> </td> <td align="left"> <nobr>data/db1000.xml</nobr> </td> </tr> <tr> <td align="right">db10000.xml</td> <td align="right"> <nobr>57.967</nobr> </td> <td align="left"> <nobr>data/db10000.xml</nobr> </td> </tr> <tr> <td align="right">xsl1.xml</td> <td align="right"> <nobr>0.040</nobr> </td> <td align="left"> <nobr>data/xsl1.xml</nobr> </td> </tr> <tr> <td align="right">xsl2.xml</td> <td align="right"> <nobr>0.176</nobr> </td> <td align="left"> <nobr>data/xsl2.xml</nobr> </td> </tr> <tr> <td align="right">xsl3.xml</td> <td align="right"> <nobr>0.560</nobr> </td> <td align="left"> <nobr>data/xsl3.xml</nobr> </td> </tr> <tr> <td align="right">xsl4.xml</td> <td align="right"> <nobr>11.448</nobr> </td> <td align="left"> <nobr>data/xsl4.xml</nobr> </td> </tr> <tr> <td align="right">periodic.xml</td> <td align="right"> <nobr>2.043</nobr> </td> <td align="left"> <nobr>data/periodic.xml</nobr> </td> </tr> <tr> <td align="right">weblog.xml</td> <td align="right"> <nobr>71.351</nobr> </td> <td align="left"> <nobr>data/weblog.xml</nobr> </td> </tr> <tr> <td align="right">factbook.xml</td> <td align="right"> <nobr>65.148</nobr> </td> <td align="left"> <nobr>data/factbook.xml</nobr> </td> </tr> </tbody> </table> <br/> <h2>Driver: FastInfosetDOMExtVocab24IndexedContentDriver</h2> <p> <ul> <li>jdsl.attributeValueSizeLimit: 24</li> <li>jdsl.characterContentChunkSizeLimit: 24</li> <li>jdsl.externalVocabulary: true</li> </ul> </p> <table width="80%" border="1"> <thead> <tr> <th> <b>testCase</b> </th> <th> <b>resultValue</b> </th> <th> <b>xmlfile</b> </th> </tr> </thead> <tbody> <tr> <td align="right">inv1.xml</td> <td align="right"> <nobr>0.090</nobr> </td> <td align="left"> <nobr>data/inv1.xml</nobr> </td> </tr> <tr> <td align="right">inv10.xml</td> <td align="right"> <nobr>0.209</nobr> </td> <td align="left"> <nobr>data/inv10.xml</nobr> </td> </tr> <tr> <td align="right">inv50.xml</td> <td align="right"> <nobr>0.742</nobr> </td> <td align="left"> <nobr>data/inv50.xml</nobr> </td> </tr> <tr> <td align="right">inv100.xml</td> <td align="right"> <nobr>1.408</nobr> </td> <td align="left"> <nobr>data/inv100.xml</nobr> </td> </tr> <tr> <td align="right">inv500.xml</td> <td align="right"> <nobr>9.339</nobr> </td> <td align="left"> <nobr>data/inv500.xml</nobr> </td> </tr> <tr> <td align="right">inv1000.xml</td> <td align="right"> <nobr>19.285</nobr> </td> <td align="left"> <nobr>data/inv1000.xml</nobr> </td> </tr> <tr> <td align="right">soap1.xml</td> <td align="right"> <nobr>0.014</nobr> </td> <td align="left"> <nobr>data/soap1.xml</nobr> </td> </tr> <tr> <td align="right">soap2.xml</td> <td align="right"> <nobr>0.012</nobr> </td> <td align="left"> <nobr>data/soap2.xml</nobr> </td> </tr> <tr> <td align="right">soap3.xml</td> <td align="right"> <nobr>0.014</nobr> </td> <td align="left"> <nobr>data/soap3.xml</nobr> </td> </tr> <tr> <td align="right">soap4.xml</td> <td align="right"> <nobr>2.887</nobr> </td> <td align="left"> <nobr>data/soap4.xml</nobr> </td> </tr> <tr> <td align="right">db10.xml</td> <td align="right"> <nobr>0.043</nobr> </td> <td align="left"> <nobr>data/db10.xml</nobr> </td> </tr> <tr> <td align="right">db50.xml</td> <td align="right"> <nobr>0.201</nobr> </td> <td align="left"> <nobr>data/db50.xml</nobr> </td> </tr> <tr> <td align="right">db100.xml</td> <td align="right"> <nobr>0.401</nobr> </td> <td align="left"> <nobr>data/db100.xml</nobr> </td> </tr> <tr> <td align="right">db500.xml</td> <td align="right"> <nobr>1.952</nobr> </td> <td align="left"> <nobr>data/db500.xml</nobr> </td> </tr> <tr> <td align="right">db1000.xml</td> <td align="right"> <nobr>5.246</nobr> </td> <td align="left"> <nobr>data/db1000.xml</nobr> </td> </tr> <tr> <td align="right">db10000.xml</td> <td align="right"> <nobr>62.476</nobr> </td> <td align="left"> <nobr>data/db10000.xml</nobr> </td> </tr> <tr> <td align="right">xsl1.xml</td> <td align="right"> <nobr>0.014</nobr> </td> <td align="left"> <nobr>data/xsl1.xml</nobr> </td> </tr> <tr> <td align="right">xsl2.xml</td> <td align="right"> <nobr>0.139</nobr> </td> <td align="left"> <nobr>data/xsl2.xml</nobr> </td> </tr> <tr> <td align="right">xsl3.xml</td> <td align="right"> <nobr>0.513</nobr> </td> <td align="left"> <nobr>data/xsl3.xml</nobr> </td> </tr> <tr> <td align="right">xsl4.xml</td> <td align="right"> <nobr>11.289</nobr> </td> <td align="left"> <nobr>data/xsl4.xml</nobr> </td> </tr> <tr> <td align="right">periodic.xml</td> <td align="right"> <nobr>1.952</nobr> </td> <td align="left"> <nobr>data/periodic.xml</nobr> </td> </tr> <tr> <td align="right">weblog.xml</td> <td align="right"> <nobr>72.356</nobr> </td> <td align="left"> <nobr>data/weblog.xml</nobr> </td> </tr> <tr> <td align="right">factbook.xml</td> <td align="right"> <nobr>61.988</nobr> </td> <td align="left"> <nobr>data/factbook.xml</nobr> </td> </tr> </tbody> </table> <br/> <h2>Driver: XercesDOMXercesXMLSerializerDriver</h2> <p> <ul> <li>jdsl.attributeValueSizeLimit: n/a</li> <li>jdsl.characterContentChunkSizeLimit: n/a</li> <li>jdsl.externalVocabulary: n/a</li> </ul> </p> <table width="80%" border="1"> <thead> <tr> <th> <b>testCase</b> </th> <th> <b>resultValue</b> </th> <th> <b>xmlfile</b> </th> </tr> </thead> <tbody> <tr> <td align="right">inv1.xml</td> <td align="right"> <nobr>0.158</nobr> </td> <td align="left"> <nobr>data/inv1.xml</nobr> </td> </tr> <tr> <td align="right">inv10.xml</td> <td align="right"> <nobr>0.377</nobr> </td> <td align="left"> <nobr>data/inv10.xml</nobr> </td> </tr> <tr> <td align="right">inv50.xml</td> <td align="right"> <nobr>1.358</nobr> </td> <td align="left"> <nobr>data/inv50.xml</nobr> </td> </tr> <tr> <td align="right">inv100.xml</td> <td align="right"> <nobr>2.592</nobr> </td> <td align="left"> <nobr>data/inv100.xml</nobr> </td> </tr> <tr> <td align="right">inv500.xml</td> <td align="right"> <nobr>15.100</nobr> </td> <td align="left"> <nobr>data/inv500.xml</nobr> </td> </tr> <tr> <td align="right">inv1000.xml</td> <td align="right"> <nobr>30.568</nobr> </td> <td align="left"> <nobr>data/inv1000.xml</nobr> </td> </tr> <tr> <td align="right">soap1.xml</td> <td align="right"> <nobr>0.040</nobr> </td> <td align="left"> <nobr>data/soap1.xml</nobr> </td> </tr> <tr> <td align="right">soap2.xml</td> <td align="right"> <nobr>0.042</nobr> </td> <td align="left"> <nobr>data/soap2.xml</nobr> </td> </tr> <tr> <td align="right">soap3.xml</td> <td align="right"> <nobr>0.046</nobr> </td> <td align="left"> <nobr>data/soap3.xml</nobr> </td> </tr> <tr> <td align="right">soap4.xml</td> <td align="right"> <nobr>4.801</nobr> </td> <td align="left"> <nobr>data/soap4.xml</nobr> </td> </tr> <tr> <td align="right">db10.xml</td> <td align="right"> <nobr>0.078</nobr> </td> <td align="left"> <nobr>data/db10.xml</nobr> </td> </tr> <tr> <td align="right">db50.xml</td> <td align="right"> <nobr>0.329</nobr> </td> <td align="left"> <nobr>data/db50.xml</nobr> </td> </tr> <tr> <td align="right">db100.xml</td> <td align="right"> <nobr>0.647</nobr> </td> <td align="left"> <nobr>data/db100.xml</nobr> </td> </tr> <tr> <td align="right">db500.xml</td> <td align="right"> <nobr>3.180</nobr> </td> <td align="left"> <nobr>data/db500.xml</nobr> </td> </tr> <tr> <td align="right">db1000.xml</td> <td align="right"> <nobr>7.617</nobr> </td> <td align="left"> <nobr>data/db1000.xml</nobr> </td> </tr> <tr> <td align="right">db10000.xml</td> <td align="right"> <nobr>76.696</nobr> </td> <td align="left"> <nobr>data/db10000.xml</nobr> </td> </tr> <tr> <td align="right">xsl1.xml</td> <td align="right"> <nobr>0.038</nobr> </td> <td align="left"> <nobr>data/xsl1.xml</nobr> </td> </tr> <tr> <td align="right">xsl2.xml</td> <td align="right"> <nobr>0.285</nobr> </td> <td align="left"> <nobr>data/xsl2.xml</nobr> </td> </tr> <tr> <td align="right">xsl3.xml</td> <td align="right"> <nobr>0.988</nobr> </td> <td align="left"> <nobr>data/xsl3.xml</nobr> </td> </tr> <tr> <td align="right">xsl4.xml</td> <td align="right"> <nobr>19.432</nobr> </td> <td align="left"> <nobr>data/xsl4.xml</nobr> </td> </tr> <tr> <td align="right">periodic.xml</td> <td align="right"> <nobr>4.164</nobr> </td> <td align="left"> <nobr>data/periodic.xml</nobr> </td> </tr> <tr> <td align="right">weblog.xml</td> <td align="right"> <nobr>136.872</nobr> </td> <td align="left"> <nobr>data/weblog.xml</nobr> </td> </tr> <tr> <td align="right">factbook.xml</td> <td align="right"> <nobr>177.500</nobr> </td> <td align="left"> <nobr>data/factbook.xml</nobr> </td> </tr> </tbody> </table> <br/> <h2>Results Per Test</h2> <br/> <center> <img src="testcase0.jpg"/> </center> <br/> <br/> <center> <img src="testcase1.jpg"/> </center> <br/> <br/> <center> <img src="testcase2.jpg"/> </center> <br/> <br/> <center> <img src="testcase3.jpg"/> </center> <br/> <br/> <center> <img src="testcase4.jpg"/> </center> <br/> <br/> <br/> <small> <hr/> <font size="-2"> Generated using <a href="https://japex.dev.java.net">Japex</a> version 1.00</font> </small> </body> </html>
Java
/** * @author caspar - chengzhihang * @contact [email protected] * @date 2016/12/29 * @file admin/view-partial/main/order/widget/form/value-widget/TpNameText */ define([ 'zh/widget/text/ValidationTextBox', 'admin/services/enums/OrderPropertyEnum', "dojo/_base/declare" ], function (TextBox, OrderPropertyEnum, declare) { return declare('admin/view-partial/main/order/widget/form/value-widget/TpNameText', [TextBox], { label: OrderPropertyEnum.TpName.text, name: OrderPropertyEnum.TpName.id, placeHolder: OrderPropertyEnum.TpName.text, }); });
Java
/* * 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.logging.log4j.core.pattern; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.NullConfiguration; import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.util.DummyNanoClock; import org.apache.logging.log4j.core.util.SystemNanoClock; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.util.Strings; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * */ public class PatternParserTest { static String OUTPUT_FILE = "output/PatternParser"; static String WITNESS_FILE = "witness/PatternParser"; LoggerContext ctx = LoggerContext.getContext(); Logger root = ctx.getRootLogger(); private static String msgPattern = "%m%n"; private final String mdcMsgPattern1 = "%m : %X%n"; private final String mdcMsgPattern2 = "%m : %X{key1}%n"; private final String mdcMsgPattern3 = "%m : %X{key2}%n"; private final String mdcMsgPattern4 = "%m : %X{key3}%n"; private final String mdcMsgPattern5 = "%m : %X{key1},%X{key2},%X{key3}%n"; private static String badPattern = "[%d{yyyyMMdd HH:mm:ss,SSS] %-5p [%c{10}] - %m%n"; private static String customPattern = "[%d{yyyyMMdd HH:mm:ss,SSS}] %-5p [%-25.25c{1}:%-4L] - %m%n"; private static String patternTruncateFromEnd = "%d; %-5p %5.-5c %m%n"; private static String patternTruncateFromBeginning = "%d; %-5p %5.5c %m%n"; private static String nestedPatternHighlight = "%highlight{%d{dd MMM yyyy HH:mm:ss,SSS}{GMT+0} [%t] %-5level: %msg%n%throwable}"; private static final String KEY = "Converter"; private PatternParser parser; @Before public void setup() { parser = new PatternParser(KEY); } private void validateConverter(final List<PatternFormatter> formatter, final int index, final String name) { final PatternConverter pc = formatter.get(index).getConverter(); assertEquals("Incorrect converter " + pc.getName() + " at index " + index + " expected " + name, pc.getName(), name); } /** * Test the default pattern */ @Test public void defaultPattern() { final List<PatternFormatter> formatters = parser.parse(msgPattern); assertNotNull(formatters); assertTrue(formatters.size() == 2); validateConverter(formatters, 0, "Message"); validateConverter(formatters, 1, "Line Sep"); } /** * Test the custom pattern */ @Test public void testCustomPattern() { final List<PatternFormatter> formatters = parser.parse(customPattern); assertNotNull(formatters); final Map<String, String> mdc = new HashMap<>(); mdc.put("loginId", "Fred"); final Throwable t = new Throwable(); final StackTraceElement[] elements = t.getStackTrace(); final Log4jLogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("org.apache.logging.log4j.PatternParserTest") // .setMarker(MarkerManager.getMarker("TEST")) // .setLoggerFqcn(Logger.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world")) // .setContextMap(mdc) // .setThreadName("Thread1") // .setSource(elements[0]) .setTimeMillis(System.currentTimeMillis()).build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expected = "INFO [PatternParserTest :100 ] - Hello, world" + Strings.LINE_SEPARATOR; assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected)); } @Test public void testPatternTruncateFromBeginning() { final List<PatternFormatter> formatters = parser.parse(patternTruncateFromBeginning); assertNotNull(formatters); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("org.apache.logging.log4j.PatternParserTest") // .setLoggerFqcn(Logger.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world")) // .setThreadName("Thread1") // .setTimeMillis(System.currentTimeMillis()) // .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expected = "INFO rTest Hello, world" + Strings.LINE_SEPARATOR; assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected)); } @Test public void testPatternTruncateFromEnd() { final List<PatternFormatter> formatters = parser.parse(patternTruncateFromEnd); assertNotNull(formatters); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("org.apache.logging.log4j.PatternParserTest") // .setLoggerFqcn(Logger.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world")) // .setThreadName("Thread1") // .setTimeMillis(System.currentTimeMillis()) // .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expected = "INFO org.a Hello, world" + Strings.LINE_SEPARATOR; assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected)); } @Test public void testBadPattern() { final Calendar cal = Calendar.getInstance(); cal.set(2001, Calendar.FEBRUARY, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 789); final long timestamp = cal.getTimeInMillis(); final List<PatternFormatter> formatters = parser.parse(badPattern); assertNotNull(formatters); final Throwable t = new Throwable(); final StackTraceElement[] elements = t.getStackTrace(); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("a.b.c") // .setLoggerFqcn(Logger.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world")) // .setThreadName("Thread1") // .setSource(elements[0]) // .setTimeMillis(timestamp) // .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); // eats all characters until the closing '}' character final String expected = "[2001-02-03 04:05:06,789] - Hello, world"; assertTrue("Expected to start with: " + expected + ". Actual: " + str, str.startsWith(expected)); } @Test public void testNestedPatternHighlight() { testNestedPatternHighlight(Level.TRACE, "\u001B[30m"); testNestedPatternHighlight(Level.DEBUG, "\u001B[36m"); testNestedPatternHighlight(Level.INFO, "\u001B[32m"); testNestedPatternHighlight(Level.WARN, "\u001B[33m"); testNestedPatternHighlight(Level.ERROR, "\u001B[1;31m"); testNestedPatternHighlight(Level.FATAL, "\u001B[1;31m"); } private void testNestedPatternHighlight(final Level level, final String expectedStart) { final List<PatternFormatter> formatters = parser.parse(nestedPatternHighlight); assertNotNull(formatters); final Throwable t = new Throwable(); t.getStackTrace(); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("org.apache.logging.log4j.PatternParserTest") // .setMarker(MarkerManager.getMarker("TEST")) // .setLoggerFqcn(Logger.class.getName()) // .setLevel(level) // .setMessage(new SimpleMessage("Hello, world")) // .setThreadName("Thread1") // .setSource(/*stackTraceElement[0]*/ null) // .setTimeMillis(System.currentTimeMillis()) // .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expectedEnd = String.format("] %-5s: Hello, world%s\u001B[m", level, Strings.LINE_SEPARATOR); assertTrue("Expected to start with: " + expectedStart + ". Actual: " + str, str.startsWith(expectedStart)); assertTrue("Expected to end with: \"" + expectedEnd + "\". Actual: \"" + str, str.endsWith(expectedEnd)); } @Test public void testNanoPatternShort() { final List<PatternFormatter> formatters = parser.parse("%N"); assertNotNull(formatters); assertEquals(1, formatters.size()); assertTrue(formatters.get(0).getConverter() instanceof NanoTimePatternConverter); } @Test public void testNanoPatternLong() { final List<PatternFormatter> formatters = parser.parse("%nano"); assertNotNull(formatters); assertEquals(1, formatters.size()); assertTrue(formatters.get(0).getConverter() instanceof NanoTimePatternConverter); } @Test public void testThreadNamePattern() { testThreadNamePattern("%thread"); } @Test public void testThreadNameFullPattern() { testThreadNamePattern("%threadName"); } @Test public void testThreadIdFullPattern() { testThreadIdPattern("%threadId"); } @Test public void testThreadIdShortPattern1() { testThreadIdPattern("%tid"); } @Test public void testThreadIdShortPattern2() { testThreadIdPattern("%T"); } @Test public void testThreadPriorityShortPattern() { testThreadPriorityPattern("%tp"); } @Test public void testThreadPriorityFullPattern() { testThreadPriorityPattern("%threadPriority"); } private void testThreadIdPattern(final String pattern) { testFirstConverter(pattern, ThreadIdPatternConverter.class); } private void testThreadNamePattern(final String pattern) { testFirstConverter(pattern, ThreadNamePatternConverter.class); } private void testThreadPriorityPattern(final String pattern) { testFirstConverter(pattern, ThreadPriorityPatternConverter.class); } private void testFirstConverter(final String pattern, final Class<?> checkClass) { final List<PatternFormatter> formatters = parser.parse(pattern); assertNotNull(formatters); final String msg = formatters.toString(); assertEquals(msg, 1, formatters.size()); assertTrue(msg, checkClass.isInstance(formatters.get(0).getConverter())); } @Test public void testThreadNameShortPattern() { testThreadNamePattern("%t"); } @Test public void testNanoPatternShortChangesConfigurationNanoClock() { final Configuration config = new NullConfiguration(); assertTrue(config.getNanoClock() instanceof DummyNanoClock); final PatternParser pp = new PatternParser(config, KEY, null); assertTrue(config.getNanoClock() instanceof DummyNanoClock); pp.parse("%m"); assertTrue(config.getNanoClock() instanceof DummyNanoClock); pp.parse("%nano"); // this changes the config clock assertTrue(config.getNanoClock() instanceof SystemNanoClock); } @Test public void testNanoPatternLongChangesNanoClockFactoryMode() { final Configuration config = new NullConfiguration(); assertTrue(config.getNanoClock() instanceof DummyNanoClock); final PatternParser pp = new PatternParser(config, KEY, null); assertTrue(config.getNanoClock() instanceof DummyNanoClock); pp.parse("%m"); assertTrue(config.getNanoClock() instanceof DummyNanoClock); pp.parse("%N"); assertTrue(config.getNanoClock() instanceof SystemNanoClock); } }
Java
import logging import threading import time from ballast.discovery import ServerList from ballast.rule import Rule, RoundRobinRule from ballast.ping import ( Ping, SocketPing, PingStrategy, SerialPingStrategy ) class LoadBalancer(object): DEFAULT_PING_INTERVAL = 30 MAX_PING_TIME = 3 def __init__(self, server_list, rule=None, ping_strategy=None, ping=None, ping_on_start=True): assert isinstance(server_list, ServerList) assert rule is None or isinstance(rule, Rule) assert ping_strategy is None or isinstance(ping_strategy, PingStrategy) assert ping is None or isinstance(ping, Ping) # some locks for thread-safety self._lock = threading.Lock() self._server_lock = threading.Lock() self._rule = rule \ if rule is not None \ else RoundRobinRule() self._ping_strategy = ping_strategy \ if ping_strategy is not None \ else SerialPingStrategy() self._ping = ping \ if ping is not None \ else SocketPing() self.max_ping_time = self.MAX_PING_TIME self._ping_interval = self.DEFAULT_PING_INTERVAL self._server_list = server_list self._servers = set() self._stats = LoadBalancerStats() self._rule.load_balancer = self self._logger = logging.getLogger(self.__module__) # start our background worker # to periodically ping our servers self._ping_timer_running = False self._ping_timer = None if ping_on_start: self._start_ping_timer() @property def ping_interval(self): return self._ping_interval @ping_interval.setter def ping_interval(self, value): self._ping_interval = value if self._ping_timer_running: self._stop_ping_timer() self._start_ping_timer() @property def max_ping_time(self): if self._ping is None: return 0 return self._ping.max_ping_time @max_ping_time.setter def max_ping_time(self, value): if self._ping is not None: self._ping.max_ping_time = value @property def stats(self): return self._stats @property def servers(self): with self._server_lock: return set(self._servers) @property def reachable_servers(self): with self._server_lock: servers = set() for s in self._servers: if s.is_alive: servers.add(s) return servers def choose_server(self): # choose a server, will # throw if there are none server = self._rule.choose() return server def mark_server_down(self, server): self._logger.debug("Marking server down: %s", server) server._is_alive = False def ping(self, server=None): if server is None: self._ping_all_servers() else: is_alive = self._ping.is_alive(server) server._is_alive = is_alive def ping_async(self, server=None): if server is None: # self._ping_all_servers() t = threading.Thread(name='ballast-worker', target=self._ping_all_servers) t.daemon = True t.start() else: is_alive = self._ping.is_alive(server) server._is_alive = is_alive def _ping_all_servers(self): with self._server_lock: results = self._ping_strategy.ping( self._ping, self._server_list ) self._servers = set(results) def _start_ping_timer(self): with self._lock: if self._ping_timer_running: self._logger.debug("Background pinger already running") return self._ping_timer_running = True self._ping_timer = threading.Thread(name='ballast-worker', target=self._ping_loop) self._ping_timer.daemon = True self._ping_timer.start() def _stop_ping_timer(self): with self._lock: self._ping_timer_running = False self._ping_timer = None def _ping_loop(self): while self._ping_timer_running: try: self._ping_all_servers() except BaseException as e: self._logger.error("There was an error pinging servers: %s", e) time.sleep(self._ping_interval) class LoadBalancerStats(object): def get_server_stats(self, server): pass
Java
import os, re, csv # regular expressions for capturing the interesting quantities noise_pattern = 'noise: \[(.+)\]' res_pattern = '^([0-9.]+$)' search_dir = "output" results_file = '../results.csv' os.chdir( search_dir ) files = filter( os.path.isfile, os.listdir( '.' )) #files = [ os.path.join( search_dir, f ) for f in files ] # add path to each file files.sort( key=lambda x: os.path.getmtime( x )) results = [] for file in files: f = open( file ) contents = f.read() # noise matches = re.search( noise_pattern, contents, re.DOTALL ) try: noise = matches.group( 1 ) noise = noise.strip() noise = noise.split() except AttributeError: print "noise error 1: %s" % ( contents ) continue # rmse matches = re.search( res_pattern, contents, re.M ) try: res = matches.group( 1 ) except AttributeError: print "matches error 2: %s" % ( contents ) continue results.append( [ res ] + noise ) writer = csv.writer( open( results_file, 'wb' )) for result in results: writer.writerow( result )
Java
/* * 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.ignite.internal.visor.verify; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.apache.ignite.internal.processors.cache.verify.PartitionKey; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.visor.VisorDataTransferObject; import org.jetbrains.annotations.NotNull; /** * */ public class VisorValidateIndexesJobResult extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Results of indexes validation from node. */ private Map<PartitionKey, ValidateIndexesPartitionResult> partRes; /** Results of reverse indexes validation from node. */ private Map<String, ValidateIndexesPartitionResult> idxRes; /** Integrity check issues. */ private Collection<IndexIntegrityCheckIssue> integrityCheckFailures; /** * @param partRes Results of indexes validation from node. * @param idxRes Results of reverse indexes validation from node. * @param integrityCheckFailures Collection of indexes integrity check failures. */ public VisorValidateIndexesJobResult( @NotNull Map<PartitionKey, ValidateIndexesPartitionResult> partRes, @NotNull Map<String, ValidateIndexesPartitionResult> idxRes, @NotNull Collection<IndexIntegrityCheckIssue> integrityCheckFailures ) { this.partRes = partRes; this.idxRes = idxRes; this.integrityCheckFailures = integrityCheckFailures; } /** * For externalization only. */ public VisorValidateIndexesJobResult() { } /** {@inheritDoc} */ @Override public byte getProtocolVersion() { return V3; } /** * @return Results of indexes validation from node. */ public Map<PartitionKey, ValidateIndexesPartitionResult> partitionResult() { return partRes; } /** * @return Results of reverse indexes validation from node. */ public Map<String, ValidateIndexesPartitionResult> indexResult() { return idxRes == null ? Collections.emptyMap() : idxRes; } /** * @return Collection of failed integrity checks. */ public Collection<IndexIntegrityCheckIssue> integrityCheckFailures() { return integrityCheckFailures == null ? Collections.emptyList() : integrityCheckFailures; } /** * @return {@code true} If any indexes issues found on node, otherwise returns {@code false}. */ public boolean hasIssues() { return (integrityCheckFailures != null && !integrityCheckFailures.isEmpty()) || (partRes != null && partRes.entrySet().stream().anyMatch(e -> !e.getValue().issues().isEmpty())) || (idxRes != null && idxRes.entrySet().stream().anyMatch(e -> !e.getValue().issues().isEmpty())); } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeMap(out, partRes); U.writeMap(out, idxRes); U.writeCollection(out, integrityCheckFailures); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { partRes = U.readMap(in); if (protoVer >= V2) idxRes = U.readMap(in); if (protoVer >= V3) integrityCheckFailures = U.readCollection(in); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(VisorValidateIndexesJobResult.class, this); } }
Java
/* * (c) Copyright 2021 Micro Focus * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available 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 io.cloudslang.content.active_directory.entities; import java.util.List; public interface CreateUserInputInterface { String getHost(); String getDistinguishedName(); String getUserCommonName(); String getUserPassword(); String getSAMAccountName(); String getUsername(); String getPassword(); String getProtocol(); Boolean getTrustAllRoots(); String getTrustKeystore(); String getTrustPassword(); Boolean getEscapeChars(); String getTimeout(); String getProxyHost(); int getProxyPort(); String getProxyUsername(); String getProxyPassword(); String getX509HostnameVerifier(); String getTlsVersion(); List<String> getAllowedCiphers(); }
Java
/* Copyright 2019 The Vitess Authors. 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. */ /* This test makes sure encrypted transport over gRPC works. The security chains are setup the following way: * root CA * vttablet server CA * vttablet server instance cert/key * vttablet client CA * vttablet client 1 cert/key * vtgate server CA * vtgate server instance cert/key (common name is 'localhost') * vtgate client CA * vtgate client 1 cert/key * vtgate client 2 cert/key The following table shows all the checks we perform: process: will check its peer is signed by: for link: vttablet vttablet client CA vtgate -> vttablet vtgate vttablet server CA vtgate -> vttablet vtgate vtgate client CA client -> vtgate client vtgate server CA client -> vtgate Additionally, we have the following constraints: - the client certificate common name is used as immediate caller ID by vtgate, and forwarded to vttablet. This allows us to use table ACLs on the vttablet side. - the vtgate server certificate common name is set to 'localhost' so it matches the hostname dialed by the vtgate clients. This is not a requirement for the go client, that can set its expected server name. However, the python gRPC client doesn't have the ability to set the server name, so they must match. - the python client needs to have the full chain for the server validation (that is 'vtgate server CA' + 'root CA'). A go client doesn't. So we read both below when using the python client, but we only pass the intermediate cert to the go clients (for vtgate -> vttablet link). */ package encryptedtransport import ( "flag" "fmt" "io/ioutil" "os" "os/exec" "path" "testing" "vitess.io/vitess/go/test/endtoend/encryption" "vitess.io/vitess/go/vt/proto/vtrpc" "vitess.io/vitess/go/vt/vterrors" "context" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "vitess.io/vitess/go/test/endtoend/cluster" "vitess.io/vitess/go/vt/grpcclient" "vitess.io/vitess/go/vt/log" querypb "vitess.io/vitess/go/vt/proto/query" vtgatepb "vitess.io/vitess/go/vt/proto/vtgate" vtgateservicepb "vitess.io/vitess/go/vt/proto/vtgateservice" ) var ( clusterInstance *cluster.LocalProcessCluster createVtInsertTest = `create table vt_insert_test ( id bigint auto_increment, msg varchar(64), keyspace_id bigint(20) unsigned NOT NULL, primary key (id) ) Engine = InnoDB` keyspace = "test_keyspace" hostname = "localhost" shardName = "0" cell = "zone1" certDirectory string grpcCert = "" grpcKey = "" grpcCa = "" grpcName = "" ) func TestSecureTransport(t *testing.T) { defer cluster.PanicHandler(t) flag.Parse() // initialize cluster _, err := clusterSetUp(t) require.Nil(t, err, "setup failed") masterTablet := *clusterInstance.Keyspaces[0].Shards[0].Vttablets[0] replicaTablet := *clusterInstance.Keyspaces[0].Shards[0].Vttablets[1] // creating table_acl_config.json file tableACLConfigJSON := path.Join(certDirectory, "table_acl_config.json") f, err := os.Create(tableACLConfigJSON) require.NoError(t, err) _, err = f.WriteString(`{ "table_groups": [ { "table_names_or_prefixes": ["vt_insert_test"], "readers": ["vtgate client 1"], "writers": ["vtgate client 1"], "admins": ["vtgate client 1"] } ] }`) require.NoError(t, err) err = f.Close() require.NoError(t, err) // start the tablets for _, tablet := range []cluster.Vttablet{masterTablet, replicaTablet} { tablet.VttabletProcess.ExtraArgs = append(tablet.VttabletProcess.ExtraArgs, "-table-acl-config", tableACLConfigJSON, "-queryserver-config-strict-table-acl") tablet.VttabletProcess.ExtraArgs = append(tablet.VttabletProcess.ExtraArgs, serverExtraArguments("vttablet-server-instance", "vttablet-client")...) err = tablet.VttabletProcess.Setup() require.NoError(t, err) } // setup replication var vtctlClientArgs []string vtctlClientTmArgs := append(vtctlClientArgs, tmclientExtraArgs("vttablet-client-1")...) // Reparenting vtctlClientArgs = append(vtctlClientTmArgs, "InitShardMaster", "-force", "test_keyspace/0", masterTablet.Alias) err = clusterInstance.VtctlProcess.ExecuteCommand(vtctlClientArgs...) require.NoError(t, err) // Apply schema var vtctlApplySchemaArgs = append(vtctlClientTmArgs, "ApplySchema", "-sql", createVtInsertTest, "test_keyspace") err = clusterInstance.VtctlProcess.ExecuteCommand(vtctlApplySchemaArgs...) require.NoError(t, err) for _, tablet := range []cluster.Vttablet{masterTablet, replicaTablet} { var vtctlTabletArgs []string vtctlTabletArgs = append(vtctlTabletArgs, tmclientExtraArgs("vttablet-client-1")...) vtctlTabletArgs = append(vtctlTabletArgs, "RunHealthCheck", tablet.Alias) _, err = clusterInstance.VtctlProcess.ExecuteCommandWithOutput(vtctlTabletArgs...) require.NoError(t, err) } // start vtgate clusterInstance.VtGateExtraArgs = append(clusterInstance.VtGateExtraArgs, tabletConnExtraArgs("vttablet-client-1")...) clusterInstance.VtGateExtraArgs = append(clusterInstance.VtGateExtraArgs, serverExtraArguments("vtgate-server-instance", "vtgate-client")...) err = clusterInstance.StartVtgate() require.NoError(t, err) grpcAddress := fmt.Sprintf("%s:%d", "localhost", clusterInstance.VtgateProcess.GrpcPort) // 'vtgate client 1' is authorized to access vt_insert_test setCreds(t, "vtgate-client-1", "vtgate-server") ctx := context.Background() request := getRequest("select * from vt_insert_test") vc, err := getVitessClient(grpcAddress) require.NoError(t, err) qr, err := vc.Execute(ctx, request) require.NoError(t, err) err = vterrors.FromVTRPC(qr.Error) require.NoError(t, err) // 'vtgate client 2' is not authorized to access vt_insert_test setCreds(t, "vtgate-client-2", "vtgate-server") request = getRequest("select * from vt_insert_test") vc, err = getVitessClient(grpcAddress) require.NoError(t, err) qr, err = vc.Execute(ctx, request) require.NoError(t, err) err = vterrors.FromVTRPC(qr.Error) require.Error(t, err) assert.Contains(t, err.Error(), "table acl error") assert.Contains(t, err.Error(), "cannot run Select on table") // now restart vtgate in the mode where we don't use SSL // for client connections, but we copy effective caller id // into immediate caller id. clusterInstance.VtGateExtraArgs = []string{"-grpc_use_effective_callerid"} clusterInstance.VtGateExtraArgs = append(clusterInstance.VtGateExtraArgs, tabletConnExtraArgs("vttablet-client-1")...) err = clusterInstance.RestartVtgate() require.NoError(t, err) grpcAddress = fmt.Sprintf("%s:%d", "localhost", clusterInstance.VtgateProcess.GrpcPort) setSSLInfoEmpty() // get vitess client vc, err = getVitessClient(grpcAddress) require.NoError(t, err) // test with empty effective caller Id request = getRequest("select * from vt_insert_test") qr, err = vc.Execute(ctx, request) require.NoError(t, err) err = vterrors.FromVTRPC(qr.Error) require.Error(t, err) assert.Contains(t, err.Error(), "table acl error") assert.Contains(t, err.Error(), "cannot run Select on table") // 'vtgate client 1' is authorized to access vt_insert_test callerID := &vtrpc.CallerID{ Principal: "vtgate client 1", } request = getRequestWithCallerID(callerID, "select * from vt_insert_test") qr, err = vc.Execute(ctx, request) require.NoError(t, err) err = vterrors.FromVTRPC(qr.Error) require.NoError(t, err) // 'vtgate client 2' is not authorized to access vt_insert_test callerID = &vtrpc.CallerID{ Principal: "vtgate client 2", } request = getRequestWithCallerID(callerID, "select * from vt_insert_test") qr, err = vc.Execute(ctx, request) require.NoError(t, err) err = vterrors.FromVTRPC(qr.Error) require.Error(t, err) assert.Contains(t, err.Error(), "table acl error") assert.Contains(t, err.Error(), "cannot run Select on table") clusterInstance.Teardown() } func clusterSetUp(t *testing.T) (int, error) { var mysqlProcesses []*exec.Cmd clusterInstance = cluster.NewCluster(cell, hostname) // Start topo server if err := clusterInstance.StartTopo(); err != nil { return 1, err } // create all certs log.Info("Creating certificates") certDirectory = path.Join(clusterInstance.TmpDirectory, "certs") _ = encryption.CreateDirectory(certDirectory, 0700) err := encryption.ExecuteVttlstestCommand("-root", certDirectory, "CreateCA") require.NoError(t, err) err = createSignedCert("ca", "01", "vttablet-server", "vttablet server CA") require.NoError(t, err) err = createSignedCert("ca", "02", "vttablet-client", "vttablet client CA") require.NoError(t, err) err = createSignedCert("ca", "03", "vtgate-server", "vtgate server CA") require.NoError(t, err) err = createSignedCert("ca", "04", "vtgate-client", "vtgate client CA") require.NoError(t, err) err = createSignedCert("vttablet-server", "01", "vttablet-server-instance", "vttablet server instance") require.NoError(t, err) err = createSignedCert("vttablet-client", "01", "vttablet-client-1", "vttablet client 1") require.NoError(t, err) err = createSignedCert("vtgate-server", "01", "vtgate-server-instance", "localhost") require.NoError(t, err) err = createSignedCert("vtgate-client", "01", "vtgate-client-1", "vtgate client 1") require.NoError(t, err) err = createSignedCert("vtgate-client", "02", "vtgate-client-2", "vtgate client 2") require.NoError(t, err) for _, keyspaceStr := range []string{keyspace} { KeyspacePtr := &cluster.Keyspace{Name: keyspaceStr} keyspace := *KeyspacePtr if err := clusterInstance.VtctlProcess.CreateKeyspace(keyspace.Name); err != nil { return 1, err } shard := &cluster.Shard{ Name: shardName, } for i := 0; i < 2; i++ { // instantiate vttablet object with reserved ports tablet := clusterInstance.NewVttabletInstance("replica", 0, cell) // Start Mysqlctl process tablet.MysqlctlProcess = *cluster.MysqlCtlProcessInstance(tablet.TabletUID, tablet.MySQLPort, clusterInstance.TmpDirectory) proc, err := tablet.MysqlctlProcess.StartProcess() if err != nil { return 1, err } mysqlProcesses = append(mysqlProcesses, proc) // start vttablet process tablet.VttabletProcess = cluster.VttabletProcessInstance(tablet.HTTPPort, tablet.GrpcPort, tablet.TabletUID, clusterInstance.Cell, shardName, keyspace.Name, clusterInstance.VtctldProcess.Port, tablet.Type, clusterInstance.TopoProcess.Port, clusterInstance.Hostname, clusterInstance.TmpDirectory, clusterInstance.VtTabletExtraArgs, clusterInstance.EnableSemiSync) tablet.Alias = tablet.VttabletProcess.TabletPath shard.Vttablets = append(shard.Vttablets, tablet) } keyspace.Shards = append(keyspace.Shards, *shard) clusterInstance.Keyspaces = append(clusterInstance.Keyspaces, keyspace) } for _, proc := range mysqlProcesses { err := proc.Wait() if err != nil { return 1, err } } return 0, nil } func createSignedCert(ca string, serial string, name string, commonName string) error { log.Infof("Creating signed cert and key %s", commonName) tmpProcess := exec.Command( "vttlstest", "-root", certDirectory, "CreateSignedCert", "-parent", ca, "-serial", serial, "-common_name", commonName, name) return tmpProcess.Run() } func serverExtraArguments(name string, ca string) []string { args := []string{"-grpc_cert", certDirectory + "/" + name + "-cert.pem", "-grpc_key", certDirectory + "/" + name + "-key.pem", "-grpc_ca", certDirectory + "/" + ca + "-cert.pem"} return args } func tmclientExtraArgs(name string) []string { ca := "vttablet-server" var args = []string{"-tablet_manager_grpc_cert", certDirectory + "/" + name + "-cert.pem", "-tablet_manager_grpc_key", certDirectory + "/" + name + "-key.pem", "-tablet_manager_grpc_ca", certDirectory + "/" + ca + "-cert.pem", "-tablet_manager_grpc_server_name", "vttablet server instance"} return args } func tabletConnExtraArgs(name string) []string { ca := "vttablet-server" args := []string{"-tablet_grpc_cert", certDirectory + "/" + name + "-cert.pem", "-tablet_grpc_key", certDirectory + "/" + name + "-key.pem", "-tablet_grpc_ca", certDirectory + "/" + ca + "-cert.pem", "-tablet_grpc_server_name", "vttablet server instance"} return args } func getVitessClient(addr string) (vtgateservicepb.VitessClient, error) { opt, err := grpcclient.SecureDialOption(grpcCert, grpcKey, grpcCa, grpcName) if err != nil { return nil, err } cc, err := grpcclient.Dial(addr, grpcclient.FailFast(false), opt) if err != nil { return nil, err } c := vtgateservicepb.NewVitessClient(cc) return c, nil } func setCreds(t *testing.T, name string, ca string) { f1, err := os.Open(path.Join(certDirectory, "ca-cert.pem")) require.NoError(t, err) b1, err := ioutil.ReadAll(f1) require.NoError(t, err) f2, err := os.Open(path.Join(certDirectory, ca+"-cert.pem")) require.NoError(t, err) b2, err := ioutil.ReadAll(f2) require.NoError(t, err) caContent := append(b1, b2...) fileName := "ca-" + name + ".pem" caVtgateClient := path.Join(certDirectory, fileName) f, err := os.Create(caVtgateClient) require.NoError(t, err) _, err = f.Write(caContent) require.NoError(t, err) grpcCa = caVtgateClient grpcKey = path.Join(certDirectory, name+"-key.pem") grpcCert = path.Join(certDirectory, name+"-cert.pem") err = f.Close() require.NoError(t, err) err = f2.Close() require.NoError(t, err) err = f1.Close() require.NoError(t, err) } func setSSLInfoEmpty() { grpcCa = "" grpcCert = "" grpcKey = "" grpcName = "" } func getSession() *vtgatepb.Session { return &vtgatepb.Session{ TargetString: "test_keyspace:0@master", } } func getRequestWithCallerID(callerID *vtrpc.CallerID, sql string) *vtgatepb.ExecuteRequest { session := getSession() return &vtgatepb.ExecuteRequest{ CallerId: callerID, Session: session, Query: &querypb.BoundQuery{ Sql: sql, }, } } func getRequest(sql string) *vtgatepb.ExecuteRequest { session := getSession() return &vtgatepb.ExecuteRequest{ Session: session, Query: &querypb.BoundQuery{ Sql: sql, }, } }
Java
--- title: "DEFINED" layout: "function" isPage: "true" link: "/warpscript/functions" desc: "Check whether or not a symbol is defined" categoryTree: ["reference","functions"] oldPath: ["30-functions","30-logic-structures","15-function_DEFINED.html.md"] category: "reference" --- The `DEFINED` function checks whether or not a symbol is defined. WarpScript commands: 42 'foo' STORE // STORE value 42 under symbol 'foo' 'foo' DEFINED 'bar' DEFINED Stack: TOP: false 1: true {% raw %} <warp10-warpscript-widget backend="{{backend}}" exec-endpoint="{{execEndpoint}}">42 'foo' STORE 'foo' DEFINED 'bar' DEFINED </warp10-warpscript-widget> {% endraw %} ## Unit test ## {% raw %} <warp10-warpscript-widget backend="{{backend}}" exec-endpoint="{{execEndpoint}}">42 'foo' STORE 'foo' DEFINED 'bar' DEFINED false == ASSERT true == ASSERT 'unit test successful' </warp10-warpscript-widget> {% endraw %}
Java
import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code }
Java
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <p> */ package org.olat.presentation.group.area; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringEscapeUtils; import org.olat.data.group.BusinessGroup; import org.olat.data.group.area.BGArea; import org.olat.data.group.area.BGAreaDao; import org.olat.data.group.area.BGAreaDaoImpl; import org.olat.data.group.context.BGContext; import org.olat.data.group.context.BGContextDao; import org.olat.data.group.context.BGContextDaoImpl; import org.olat.lms.activitylogging.LoggingResourceable; import org.olat.lms.activitylogging.ThreadLocalUserActivityLogger; import org.olat.lms.group.BusinessGroupService; import org.olat.lms.group.GroupLoggingAction; import org.olat.presentation.framework.core.UserRequest; import org.olat.presentation.framework.core.components.Component; import org.olat.presentation.framework.core.components.choice.Choice; import org.olat.presentation.framework.core.components.tabbedpane.TabbedPane; import org.olat.presentation.framework.core.components.velocity.VelocityContainer; import org.olat.presentation.framework.core.control.Controller; import org.olat.presentation.framework.core.control.WindowControl; import org.olat.presentation.framework.core.control.controller.BasicController; import org.olat.presentation.framework.core.translator.PackageTranslator; import org.olat.presentation.framework.core.translator.PackageUtil; import org.olat.presentation.framework.core.translator.Translator; import org.olat.system.event.Event; import org.olat.system.spring.CoreSpringFactory; /** * Description:<BR> * This controller can be used to edit the business grou area metadata and associate business groups to the business group area. * <P> * Initial Date: Aug 30, 2004 * * @author gnaegi */ public class BGAreaEditController extends BasicController { private static final String PACKAGE = PackageUtil.getPackageName(BGAreaEditController.class); private static final String VELOCITY_ROOT = PackageUtil.getPackageVelocityRoot(PACKAGE); // helpers private final Translator trans; // GUI components private final TabbedPane tabbedPane; private VelocityContainer editVC, detailsTabVC, groupsTabVC; private BGAreaFormController areaController; private GroupsToAreaDataModel groupsDataModel; private Choice groupsChoice; // area, context and group references private BGArea area; private final BGContext bgContext; private List allGroups, inAreaGroups; // managers private final BGAreaDao areaManager; private final BGContextDao contextManager; /** * Constructor for the business group area edit controller * * @param ureq * The user request * @param wControl * The window control * @param area * The business group area */ public BGAreaEditController(final UserRequest ureq, final WindowControl wControl, final BGArea area) { super(ureq, wControl); this.trans = new PackageTranslator(PACKAGE, ureq.getLocale()); this.area = area; this.areaManager = BGAreaDaoImpl.getInstance(); this.bgContext = area.getGroupContext(); this.contextManager = BGContextDaoImpl.getInstance(); // tabbed pane tabbedPane = new TabbedPane("tabbedPane", ureq.getLocale()); tabbedPane.addListener(this); // details tab initAndAddDetailsTab(ureq, wControl); // groups tab initAndAddGroupsTab(); // initialize main view initEditVC(); putInitialPanel(this.editVC); } /** * initialize the main velocity wrapper container */ private void initEditVC() { editVC = new VelocityContainer("edit", VELOCITY_ROOT + "/edit.html", trans, this); editVC.put("tabbedpane", tabbedPane); editVC.contextPut("title", trans.translate("area.edit.title", new String[] { StringEscapeUtils.escapeHtml(this.area.getName()).toString() })); } /** * initialize the area details tab */ private void initAndAddDetailsTab(final UserRequest ureq, final WindowControl wControl) { this.detailsTabVC = new VelocityContainer("detailstab", VELOCITY_ROOT + "/detailstab.html", this.trans, this); // TODO:pb: refactor BGControllerFactory.create..AreaController to be // usefull here if (this.areaController != null) { removeAsListenerAndDispose(this.areaController); } this.areaController = new BGAreaFormController(ureq, wControl, this.area, false); listenTo(this.areaController); this.detailsTabVC.put("areaForm", this.areaController.getInitialComponent()); this.tabbedPane.addTab(this.trans.translate("tab.details"), this.detailsTabVC); } /** * initalize the group to area association tab */ private void initAndAddGroupsTab() { groupsTabVC = new VelocityContainer("groupstab", VELOCITY_ROOT + "/groupstab.html", trans, this); tabbedPane.addTab(trans.translate("tab.groups"), groupsTabVC); this.allGroups = contextManager.getGroupsOfBGContext(this.bgContext); this.inAreaGroups = areaManager.findBusinessGroupsOfArea(this.area); this.groupsDataModel = new GroupsToAreaDataModel(this.allGroups, this.inAreaGroups); groupsChoice = new Choice("groupsChoice", trans); groupsChoice.setSubmitKey("submit"); groupsChoice.setCancelKey("cancel"); groupsChoice.setTableDataModel(groupsDataModel); groupsChoice.addListener(this); groupsTabVC.put(groupsChoice); groupsTabVC.contextPut("noGroupsFound", (allGroups.size() > 0 ? Boolean.FALSE : Boolean.TRUE)); } /** */ @Override protected void event(final UserRequest ureq, final Component source, final Event event) { if (source == this.groupsChoice) { if (event == Choice.EVNT_VALIDATION_OK) { doUpdateGroupAreaRelations(); // do logging if (this.inAreaGroups.size() == 0) { ThreadLocalUserActivityLogger.log(GroupLoggingAction.BGAREA_UPDATED_NOW_EMPTY, getClass()); } else { for (final Iterator it = inAreaGroups.iterator(); it.hasNext();) { final BusinessGroup aGroup = (BusinessGroup) it.next(); ThreadLocalUserActivityLogger.log(GroupLoggingAction.BGAREA_UPDATED_MEMBER_GROUP, getClass(), LoggingResourceable.wrap(aGroup)); } } } } } @Override protected void event(final UserRequest ureq, final Controller source, final Event event) { if (source == this.areaController) { if (event == Event.DONE_EVENT) { final BGArea updatedArea = doAreaUpdate(); if (updatedArea == null) { this.areaController.resetAreaName(); getWindowControl().setWarning(this.trans.translate("error.area.name.exists")); } else { this.area = updatedArea; this.editVC.contextPut("title", this.trans.translate("area.edit.title", new String[] { StringEscapeUtils.escapeHtml(this.area.getName()).toString() })); } } else if (event == Event.CANCELLED_EVENT) { // area might have been changed, reload from db this.area = this.areaManager.reloadArea(this.area); // TODO:pb: refactor BGControllerFactory.create..AreaController to be // usefull here if (this.areaController != null) { removeAsListenerAndDispose(this.areaController); } this.areaController = new BGAreaFormController(ureq, getWindowControl(), this.area, false); listenTo(this.areaController); this.detailsTabVC.put("areaForm", this.areaController.getInitialComponent()); } } } /** * Update a group area * * @return the updated area */ public BGArea doAreaUpdate() { this.area.setName(this.areaController.getAreaName()); this.area.setDescription(this.areaController.getAreaDescription()); return this.areaManager.updateBGArea(this.area); } /** * Update the groups associated to this area: remove and add groups */ private void doUpdateGroupAreaRelations() { BusinessGroupService businessGroupService = (BusinessGroupService) CoreSpringFactory.getBean(BusinessGroupService.class); // 1) add groups to area final List addedGroups = groupsChoice.getAddedRows(); Iterator iterator = addedGroups.iterator(); while (iterator.hasNext()) { final Integer position = (Integer) iterator.next(); BusinessGroup group = groupsDataModel.getGroup(position.intValue()); // refresh group to prevent stale object exception and context proxy // issues group = businessGroupService.loadBusinessGroup(group); // refresh group also in table model this.allGroups.set(position.intValue(), group); // add group now to area and update in area group list areaManager.addBGToBGArea(group, area); this.inAreaGroups.add(group); } // 2) remove groups from area final List removedGroups = groupsChoice.getRemovedRows(); iterator = removedGroups.iterator(); while (iterator.hasNext()) { final Integer position = (Integer) iterator.next(); final BusinessGroup group = groupsDataModel.getGroup(position.intValue()); areaManager.removeBGFromArea(group, area); this.inAreaGroups.remove(group); } } /** */ @Override protected void doDispose() { // don't dispose anything } }
Java
/* * 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.river.test.spec.javaspace.conformance; import java.util.logging.Level; // net.jini import net.jini.core.transaction.Transaction; // org.apache.river import org.apache.river.qa.harness.TestException; import org.apache.river.qa.harness.QAConfig; /** * TransactionWriteTakeIfExistsTest asserts that if the entry is written and * after that is taken by takeIfExists method within the non null * transaction, the entry will never be visible outside the transaction and * will not be added to the space when the transaction commits. * * @author Mikhail A. Markov */ public class TransactionWriteTakeIfExistsTest extends TransactionTest { /** * This method asserts that if the entry is written and * after that is taken by takeIfExists method within the non null * transaction, the entry will never be visible outside the transaction and * will not be added to the space when the transaction commits. * * <P>Notes:<BR>For more information see the JavaSpaces specification * section 3.1</P> */ public void run() throws Exception { SimpleEntry sampleEntry1 = new SimpleEntry("TestEntry #1", 1); SimpleEntry sampleEntry2 = new SimpleEntry("TestEntry #2", 2); SimpleEntry result; Transaction txn; // first check that space is empty if (!checkSpace(space)) { throw new TestException( "Space is not empty in the beginning."); } // create the non null transaction txn = getTransaction(); /* * write 1-st sample and 2-nd sample entries twice * to the space within the transaction */ space.write(sampleEntry1, txn, leaseForeverTime); space.write(sampleEntry1, txn, leaseForeverTime); space.write(sampleEntry2, txn, leaseForeverTime); space.write(sampleEntry2, txn, leaseForeverTime); /* * takeIfExists all written entries from the space * within the transaction */ space.takeIfExists(sampleEntry1, txn, checkTime); space.takeIfExists(sampleEntry1, txn, checkTime); space.takeIfExists(sampleEntry2, txn, checkTime); space.takeIfExists(sampleEntry2, txn, checkTime); // commit the transaction txnCommit(txn); // check that there are no entries in the space result = (SimpleEntry) space.read(null, null, checkTime); if (result != null) { throw new TestException( "there is " + result + " still available in the" + " space after transaction's committing" + " but null is expected."); } logDebugText("There are no entries in the space after" + " transaction's committing, as expected."); } }
Java
package org.hyperimage.connector.fedora3.ws; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.hyperimage.connector.fedora3.ws package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _AssetURN_QNAME = new QName("http://connector.ws.hyperimage.org/", "assetURN"); private final static QName _Token_QNAME = new QName("http://connector.ws.hyperimage.org/", "token"); private final static QName _GetAssetPreviewDataResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetPreviewDataResponse"); private final static QName _ParentURN_QNAME = new QName("http://connector.ws.hyperimage.org/", "parentURN"); private final static QName _Username_QNAME = new QName("http://connector.ws.hyperimage.org/", "username"); private final static QName _GetAssetData_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetData"); private final static QName _GetAssetPreviewData_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetPreviewData"); private final static QName _GetHierarchyLevelResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getHierarchyLevelResponse"); private final static QName _Authenticate_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "authenticate"); private final static QName _HIWSLoggedException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSLoggedException"); private final static QName _GetMetadataRecord_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getMetadataRecord"); private final static QName _HIWSNotBinaryException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSNotBinaryException"); private final static QName _Session_QNAME = new QName("http://connector.ws.hyperimage.org/", "session"); private final static QName _HIWSDCMetadataException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSDCMetadataException"); private final static QName _HIWSAuthException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSAuthException"); private final static QName _HIWSAssetNotFoundException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSAssetNotFoundException"); private final static QName _GetWSVersion_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getWSVersion"); private final static QName _GetMetadataRecordResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getMetadataRecordResponse"); private final static QName _HIWSUTF8EncodingException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSUTF8EncodingException"); private final static QName _GetWSVersionResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getWSVersionResponse"); private final static QName _GetReposInfo_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getReposInfo"); private final static QName _HIWSXMLParserException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSXMLParserException"); private final static QName _AuthenticateResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "authenticateResponse"); private final static QName _GetAssetDataResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetDataResponse"); private final static QName _GetHierarchyLevel_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getHierarchyLevel"); private final static QName _GetReposInfoResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getReposInfoResponse"); private final static QName _GetAssetPreviewDataResponseReturn_QNAME = new QName("", "return"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.hyperimage.connector.fedora3.ws * */ public ObjectFactory() { } /** * Create an instance of {@link HIWSDCMetadataException } * */ public HIWSDCMetadataException createHIWSDCMetadataException() { return new HIWSDCMetadataException(); } /** * Create an instance of {@link GetAssetDataResponse } * */ public GetAssetDataResponse createGetAssetDataResponse() { return new GetAssetDataResponse(); } /** * Create an instance of {@link HIWSAuthException } * */ public HIWSAuthException createHIWSAuthException() { return new HIWSAuthException(); } /** * Create an instance of {@link HIWSAssetNotFoundException } * */ public HIWSAssetNotFoundException createHIWSAssetNotFoundException() { return new HIWSAssetNotFoundException(); } /** * Create an instance of {@link HIWSNotBinaryException } * */ public HIWSNotBinaryException createHIWSNotBinaryException() { return new HIWSNotBinaryException(); } /** * Create an instance of {@link GetHierarchyLevelResponse } * */ public GetHierarchyLevelResponse createGetHierarchyLevelResponse() { return new GetHierarchyLevelResponse(); } /** * Create an instance of {@link Authenticate } * */ public Authenticate createAuthenticate() { return new Authenticate(); } /** * Create an instance of {@link HiHierarchyLevel } * */ public HiHierarchyLevel createHiHierarchyLevel() { return new HiHierarchyLevel(); } /** * Create an instance of {@link HIWSLoggedException } * */ public HIWSLoggedException createHIWSLoggedException() { return new HIWSLoggedException(); } /** * Create an instance of {@link GetHierarchyLevel } * */ public GetHierarchyLevel createGetHierarchyLevel() { return new GetHierarchyLevel(); } /** * Create an instance of {@link AuthenticateResponse } * */ public AuthenticateResponse createAuthenticateResponse() { return new AuthenticateResponse(); } /** * Create an instance of {@link GetReposInfoResponse } * */ public GetReposInfoResponse createGetReposInfoResponse() { return new GetReposInfoResponse(); } /** * Create an instance of {@link GetAssetPreviewDataResponse } * */ public GetAssetPreviewDataResponse createGetAssetPreviewDataResponse() { return new GetAssetPreviewDataResponse(); } /** * Create an instance of {@link GetWSVersion } * */ public GetWSVersion createGetWSVersion() { return new GetWSVersion(); } /** * Create an instance of {@link GetMetadataRecordResponse } * */ public GetMetadataRecordResponse createGetMetadataRecordResponse() { return new GetMetadataRecordResponse(); } /** * Create an instance of {@link HiMetadataRecord } * */ public HiMetadataRecord createHiMetadataRecord() { return new HiMetadataRecord(); } /** * Create an instance of {@link HiTypedDatastream } * */ public HiTypedDatastream createHiTypedDatastream() { return new HiTypedDatastream(); } /** * Create an instance of {@link HIWSXMLParserException } * */ public HIWSXMLParserException createHIWSXMLParserException() { return new HIWSXMLParserException(); } /** * Create an instance of {@link GetMetadataRecord } * */ public GetMetadataRecord createGetMetadataRecord() { return new GetMetadataRecord(); } /** * Create an instance of {@link GetAssetPreviewData } * */ public GetAssetPreviewData createGetAssetPreviewData() { return new GetAssetPreviewData(); } /** * Create an instance of {@link HIWSUTF8EncodingException } * */ public HIWSUTF8EncodingException createHIWSUTF8EncodingException() { return new HIWSUTF8EncodingException(); } /** * Create an instance of {@link GetReposInfo } * */ public GetReposInfo createGetReposInfo() { return new GetReposInfo(); } /** * Create an instance of {@link GetWSVersionResponse } * */ public GetWSVersionResponse createGetWSVersionResponse() { return new GetWSVersionResponse(); } /** * Create an instance of {@link GetAssetData } * */ public GetAssetData createGetAssetData() { return new GetAssetData(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "assetURN") public JAXBElement<String> createAssetURN(String value) { return new JAXBElement<String>(_AssetURN_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "token") public JAXBElement<String> createToken(String value) { return new JAXBElement<String>(_Token_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAssetPreviewDataResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetPreviewDataResponse") public JAXBElement<GetAssetPreviewDataResponse> createGetAssetPreviewDataResponse(GetAssetPreviewDataResponse value) { return new JAXBElement<GetAssetPreviewDataResponse>(_GetAssetPreviewDataResponse_QNAME, GetAssetPreviewDataResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "parentURN") public JAXBElement<String> createParentURN(String value) { return new JAXBElement<String>(_ParentURN_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "username") public JAXBElement<String> createUsername(String value) { return new JAXBElement<String>(_Username_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAssetData }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetData") public JAXBElement<GetAssetData> createGetAssetData(GetAssetData value) { return new JAXBElement<GetAssetData>(_GetAssetData_QNAME, GetAssetData.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAssetPreviewData }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetPreviewData") public JAXBElement<GetAssetPreviewData> createGetAssetPreviewData(GetAssetPreviewData value) { return new JAXBElement<GetAssetPreviewData>(_GetAssetPreviewData_QNAME, GetAssetPreviewData.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetHierarchyLevelResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getHierarchyLevelResponse") public JAXBElement<GetHierarchyLevelResponse> createGetHierarchyLevelResponse(GetHierarchyLevelResponse value) { return new JAXBElement<GetHierarchyLevelResponse>(_GetHierarchyLevelResponse_QNAME, GetHierarchyLevelResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Authenticate }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "authenticate") public JAXBElement<Authenticate> createAuthenticate(Authenticate value) { return new JAXBElement<Authenticate>(_Authenticate_QNAME, Authenticate.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSLoggedException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSLoggedException") public JAXBElement<HIWSLoggedException> createHIWSLoggedException(HIWSLoggedException value) { return new JAXBElement<HIWSLoggedException>(_HIWSLoggedException_QNAME, HIWSLoggedException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetMetadataRecord }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getMetadataRecord") public JAXBElement<GetMetadataRecord> createGetMetadataRecord(GetMetadataRecord value) { return new JAXBElement<GetMetadataRecord>(_GetMetadataRecord_QNAME, GetMetadataRecord.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSNotBinaryException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSNotBinaryException") public JAXBElement<HIWSNotBinaryException> createHIWSNotBinaryException(HIWSNotBinaryException value) { return new JAXBElement<HIWSNotBinaryException>(_HIWSNotBinaryException_QNAME, HIWSNotBinaryException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "session") public JAXBElement<String> createSession(String value) { return new JAXBElement<String>(_Session_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSDCMetadataException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSDCMetadataException") public JAXBElement<HIWSDCMetadataException> createHIWSDCMetadataException(HIWSDCMetadataException value) { return new JAXBElement<HIWSDCMetadataException>(_HIWSDCMetadataException_QNAME, HIWSDCMetadataException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSAuthException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSAuthException") public JAXBElement<HIWSAuthException> createHIWSAuthException(HIWSAuthException value) { return new JAXBElement<HIWSAuthException>(_HIWSAuthException_QNAME, HIWSAuthException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSAssetNotFoundException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSAssetNotFoundException") public JAXBElement<HIWSAssetNotFoundException> createHIWSAssetNotFoundException(HIWSAssetNotFoundException value) { return new JAXBElement<HIWSAssetNotFoundException>(_HIWSAssetNotFoundException_QNAME, HIWSAssetNotFoundException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetWSVersion }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getWSVersion") public JAXBElement<GetWSVersion> createGetWSVersion(GetWSVersion value) { return new JAXBElement<GetWSVersion>(_GetWSVersion_QNAME, GetWSVersion.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetMetadataRecordResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getMetadataRecordResponse") public JAXBElement<GetMetadataRecordResponse> createGetMetadataRecordResponse(GetMetadataRecordResponse value) { return new JAXBElement<GetMetadataRecordResponse>(_GetMetadataRecordResponse_QNAME, GetMetadataRecordResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSUTF8EncodingException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSUTF8EncodingException") public JAXBElement<HIWSUTF8EncodingException> createHIWSUTF8EncodingException(HIWSUTF8EncodingException value) { return new JAXBElement<HIWSUTF8EncodingException>(_HIWSUTF8EncodingException_QNAME, HIWSUTF8EncodingException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetWSVersionResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getWSVersionResponse") public JAXBElement<GetWSVersionResponse> createGetWSVersionResponse(GetWSVersionResponse value) { return new JAXBElement<GetWSVersionResponse>(_GetWSVersionResponse_QNAME, GetWSVersionResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetReposInfo }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getReposInfo") public JAXBElement<GetReposInfo> createGetReposInfo(GetReposInfo value) { return new JAXBElement<GetReposInfo>(_GetReposInfo_QNAME, GetReposInfo.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HIWSXMLParserException }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSXMLParserException") public JAXBElement<HIWSXMLParserException> createHIWSXMLParserException(HIWSXMLParserException value) { return new JAXBElement<HIWSXMLParserException>(_HIWSXMLParserException_QNAME, HIWSXMLParserException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AuthenticateResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "authenticateResponse") public JAXBElement<AuthenticateResponse> createAuthenticateResponse(AuthenticateResponse value) { return new JAXBElement<AuthenticateResponse>(_AuthenticateResponse_QNAME, AuthenticateResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAssetDataResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetDataResponse") public JAXBElement<GetAssetDataResponse> createGetAssetDataResponse(GetAssetDataResponse value) { return new JAXBElement<GetAssetDataResponse>(_GetAssetDataResponse_QNAME, GetAssetDataResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetHierarchyLevel }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getHierarchyLevel") public JAXBElement<GetHierarchyLevel> createGetHierarchyLevel(GetHierarchyLevel value) { return new JAXBElement<GetHierarchyLevel>(_GetHierarchyLevel_QNAME, GetHierarchyLevel.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetReposInfoResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getReposInfoResponse") public JAXBElement<GetReposInfoResponse> createGetReposInfoResponse(GetReposInfoResponse value) { return new JAXBElement<GetReposInfoResponse>(_GetReposInfoResponse_QNAME, GetReposInfoResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link byte[]}{@code >}} * */ @XmlElementDecl(namespace = "", name = "return", scope = GetAssetPreviewDataResponse.class) public JAXBElement<byte[]> createGetAssetPreviewDataResponseReturn(byte[] value) { return new JAXBElement<byte[]>(_GetAssetPreviewDataResponseReturn_QNAME, byte[].class, GetAssetPreviewDataResponse.class, ((byte[]) value)); } }
Java
# # Cookbook Name:: nxlog # Recipe:: default # # Copyright (C) 2014 Simon Detheridge # # 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. # include_recipe 'nxlog::default' nxlog_destination 'test_om_file' do file '/var/log/test.log' end nxlog_destination 'test_om_blocker' do output_module 'om_blocker' end nxlog_destination 'test_om_dbi' do output_module 'om_dbi' driver 'mysql' sql 'INSERT INTO log VALUES ($SyslogFacility, $SyslogSeverity, $Message)' options ['host 127.0.0.1', 'username foo', 'password bar', 'dbname nxlog'] end nxlog_destination 'test_om_exec' do output_module 'om_exec' command '/usr/bin/foo' args %w(bar baz) end nxlog_destination 'test_om_https' do output_module 'om_http' url 'https://example.org/foo' https_cert_file '%CERTDIR%/client-cert.pem' https_cert_key_file '%CERTDIR%/client-key.pem' https_ca_file '%CERTDIR%/ca.pem' https_allow_untrusted false end nxlog_destination 'test_om_http' do output_module 'om_http' url 'http://example.org/bar' end nxlog_destination 'test_om_null' do output_module 'om_null' end nxlog_destination 'test_om_ssl' do output_module 'om_ssl' port 1234 host 'foo.example.org' cert_file '%CERTDIR%/client-cert.pem' cert_key_file '%CERTDIR%/client-key.pem' ca_file '%CERTDIR%/ca.pem' allow_untrusted false output_type 'Binary' end nxlog_destination 'test_om_tcp' do output_module 'om_tcp' port 1234 host 'foo.example.org' end nxlog_destination 'test_om_udp' do output_module 'om_udp' port 1234 host 'foo.example.org' end nxlog_destination 'test_om_uds' do output_module 'om_uds' exec 'parse_syslog_bsd(); to_syslog_bsd();' uds '/dev/log' end
Java
/* 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.pig.backend.hadoop.hbase; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.ListIterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.mapreduce.TableInputFormat; import org.apache.hadoop.hbase.mapreduce.TableRecordReader; import org.apache.hadoop.hbase.mapreduce.TableSplit; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.InputSplit; public class HBaseTableInputFormat extends TableInputFormat { private static final Log LOG = LogFactory.getLog(HBaseTableInputFormat.class); protected final byte[] gt_; protected final byte[] gte_; protected final byte[] lt_; protected final byte[] lte_; public HBaseTableInputFormat() { this(-1, null, null, null, null); } protected HBaseTableInputFormat(long limit, byte[] gt, byte[] gte, byte[] lt, byte[] lte) { super(); setTableRecordReader(new HBaseTableRecordReader(limit)); gt_ = gt; gte_ = gte; lt_ = lt; lte_ = lte; } public static class HBaseTableIFBuilder { protected byte[] gt_; protected byte[] gte_; protected byte[] lt_; protected byte[] lte_; protected long limit_; protected Configuration conf_; public HBaseTableIFBuilder withGt(byte[] gt) { gt_ = gt; return this; } public HBaseTableIFBuilder withGte(byte[] gte) { gte_ = gte; return this; } public HBaseTableIFBuilder withLt(byte[] lt) { lt_ = lt; return this; } public HBaseTableIFBuilder withLte(byte[] lte) { lte_ = lte; return this; } public HBaseTableIFBuilder withLimit(long limit) { limit_ = limit; return this; } public HBaseTableIFBuilder withConf(Configuration conf) { conf_ = conf; return this; } public HBaseTableInputFormat build() { HBaseTableInputFormat inputFormat = new HBaseTableInputFormat(limit_, gt_, gte_, lt_, lte_); if (conf_ != null) inputFormat.setConf(conf_); return inputFormat; } } @Override public List<InputSplit> getSplits(org.apache.hadoop.mapreduce.JobContext context) throws IOException { List<InputSplit> splits = super.getSplits(context); ListIterator<InputSplit> splitIter = splits.listIterator(); while (splitIter.hasNext()) { TableSplit split = (TableSplit) splitIter.next(); byte[] startKey = split.getStartRow(); byte[] endKey = split.getEndRow(); // Skip if the region doesn't satisfy configured options. if ((skipRegion(CompareOp.LESS, startKey, lt_)) || (skipRegion(CompareOp.GREATER, endKey, gt_)) || (skipRegion(CompareOp.GREATER, endKey, gte_)) || (skipRegion(CompareOp.LESS_OR_EQUAL, startKey, lte_)) ) { splitIter.remove(); } } return splits; } private boolean skipRegion(CompareOp op, byte[] key, byte[] option ) throws IOException { if (key.length == 0 || option == null) return false; BinaryComparator comp = new BinaryComparator(option); RowFilter rowFilter = new RowFilter(op, comp); return rowFilter.filterRowKey(key, 0, key.length); } protected class HBaseTableRecordReader extends TableRecordReader { private long recordsSeen = 0; private final long limit_; private byte[] startRow_; private byte[] endRow_; private transient byte[] currRow_; private int maxRowLength; private BigInteger bigStart_; private BigInteger bigEnd_; private BigDecimal bigRange_; private transient float progressSoFar_ = 0; public HBaseTableRecordReader(long limit) { limit_ = limit; } @Override public void setScan(Scan scan) { super.setScan(scan); startRow_ = scan.getStartRow(); endRow_ = scan.getStopRow(); byte[] startPadded; byte[] endPadded; if (startRow_.length < endRow_.length) { startPadded = Bytes.padTail(startRow_, endRow_.length - startRow_.length); endPadded = endRow_; } else if (endRow_.length < startRow_.length) { startPadded = startRow_; endPadded = Bytes.padTail(endRow_, startRow_.length - endRow_.length); } else { startPadded = startRow_; endPadded = endRow_; } currRow_ = startRow_; byte [] prependHeader = {1, 0}; bigStart_ = new BigInteger(Bytes.add(prependHeader, startPadded)); bigEnd_ = new BigInteger(Bytes.add(prependHeader, endPadded)); bigRange_ = new BigDecimal(bigEnd_.subtract(bigStart_)); maxRowLength = endRow_.length > startRow_.length ? endRow_.length : startRow_.length; LOG.info("setScan with ranges: " + bigStart_ + " - " + bigEnd_ + " ( " + bigRange_ + ")"); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (limit_ > 0 && ++recordsSeen > limit_) { return false; } boolean hasMore = super.nextKeyValue(); if (hasMore) { currRow_ = getCurrentKey().get(); } return hasMore; } @Override public float getProgress() { if (currRow_ == null || currRow_.length == 0 || endRow_.length == 0 || endRow_ == HConstants.LAST_ROW) { return 0; } byte[] lastPadded = currRow_; if(maxRowLength > currRow_.length) { lastPadded = Bytes.padTail(currRow_, maxRowLength - currRow_.length); } byte [] prependHeader = {1, 0}; BigInteger bigLastRow = new BigInteger(Bytes.add(prependHeader, lastPadded)); if (bigLastRow.compareTo(bigEnd_) > 0) { return progressSoFar_; } BigDecimal processed = new BigDecimal(bigLastRow.subtract(bigStart_)); try { BigDecimal progress = processed.setScale(3).divide(bigRange_, BigDecimal.ROUND_HALF_DOWN); progressSoFar_ = progress.floatValue(); return progressSoFar_; } catch (java.lang.ArithmeticException e) { return 0; } } } }
Java
// Copyright (c) 2015 Alachisoft // // 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. namespace Alachisoft.NCache.Web.Command { internal sealed class CommandOptions { private CommandOptions() { } internal const string EXC_INITIAL = "EXCEPTION"; } }
Java
package app import ( "net/http" "time" "golang.org/x/net/context" "github.com/weaveworks/scope/probe/host" "github.com/weaveworks/scope/report" ) // Raw report handler func makeRawReportHandler(rep Reporter) CtxHandlerFunc { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) { report, err := rep.Report(ctx, time.Now()) if err != nil { respondWith(w, http.StatusInternalServerError, err) return } respondWith(w, http.StatusOK, report) } } type probeDesc struct { ID string `json:"id"` Hostname string `json:"hostname"` Version string `json:"version"` LastSeen time.Time `json:"lastSeen"` } // Probe handler func makeProbeHandler(rep Reporter) CtxHandlerFunc { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) { r.ParseForm() if _, sparse := r.Form["sparse"]; sparse { // if we have reports, we must have connected probes hasProbes, err := rep.HasReports(ctx, time.Now()) if err != nil { respondWith(w, http.StatusInternalServerError, err) } respondWith(w, http.StatusOK, hasProbes) return } rpt, err := rep.Report(ctx, time.Now()) if err != nil { respondWith(w, http.StatusInternalServerError, err) return } result := []probeDesc{} for _, n := range rpt.Host.Nodes { id, _ := n.Latest.Lookup(report.ControlProbeID) hostname, _ := n.Latest.Lookup(host.HostName) version, dt, _ := n.Latest.LookupEntry(host.ScopeVersion) result = append(result, probeDesc{ ID: id, Hostname: hostname, Version: version, LastSeen: dt, }) } respondWith(w, http.StatusOK, result) } }
Java
/** * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.internal.operators.maybe; import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.fuseable.HasUpstreamMaybeSource; import java.util.concurrent.atomic.AtomicReference; /** * Subscribes to the other source if the main source is empty. * * @param <T> the value type */ public final class MaybeSwitchIfEmptySingle<T> extends Single<T> implements HasUpstreamMaybeSource<T> { final MaybeSource<T> source; final SingleSource<? extends T> other; public MaybeSwitchIfEmptySingle(MaybeSource<T> source, SingleSource<? extends T> other) { this.source = source; this.other = other; } @Override public MaybeSource<T> source() { return source; } @Override protected void subscribeActual(SingleObserver<? super T> observer) { source.subscribe(new SwitchIfEmptyMaybeObserver<T>(observer, other)); } static final class SwitchIfEmptyMaybeObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { private static final long serialVersionUID = 4603919676453758899L; final SingleObserver<? super T> downstream; final SingleSource<? extends T> other; SwitchIfEmptyMaybeObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other) { this.downstream = actual; this.other = other; } @Override public void dispose() { DisposableHelper.dispose(this); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { downstream.onSuccess(value); } @Override public void onError(Throwable e) { downstream.onError(e); } @Override public void onComplete() { Disposable d = get(); if (d != DisposableHelper.DISPOSED) { if (compareAndSet(d, null)) { other.subscribe(new OtherSingleObserver<T>(downstream, this)); } } } static final class OtherSingleObserver<T> implements SingleObserver<T> { final SingleObserver<? super T> downstream; final AtomicReference<Disposable> parent; OtherSingleObserver(SingleObserver<? super T> actual, AtomicReference<Disposable> parent) { this.downstream = actual; this.parent = parent; } @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(parent, d); } @Override public void onSuccess(T value) { downstream.onSuccess(value); } @Override public void onError(Throwable e) { downstream.onError(e); } } } }
Java
/* * Copyright 2022 ThoughtWorks, Inc. * * 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 com.thoughtworks.go.plugin.configrepo.contract.material; import com.google.gson.JsonObject; import com.thoughtworks.go.plugin.configrepo.contract.AbstractCRTest; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class CRConfigMaterialTest extends AbstractCRTest<CRConfigMaterial> { private final CRConfigMaterial named; private final CRConfigMaterial namedDest; private final CRConfigMaterial materialWithIgnores; private final CRConfigMaterial invalidList; public CRConfigMaterialTest() { named = new CRConfigMaterial("primary", null,null); namedDest = new CRConfigMaterial("primary", "folder",null); List<String> patterns = new ArrayList<>(); patterns.add("externals"); patterns.add("tools"); materialWithIgnores = new CRConfigMaterial("primary", "folder",new CRFilter(patterns,false)); CRFilter badFilter = new CRFilter(patterns,false); badFilter.setIncludesNoCheck(patterns); invalidList = new CRConfigMaterial("primary", "folder",badFilter); } @Override public void addGoodExamples(Map<String, CRConfigMaterial> examples) { examples.put("namedExample", named); examples.put("namedDest", namedDest); examples.put("ignoreFilter", materialWithIgnores); } @Override public void addBadExamples(Map<String, CRConfigMaterial> examples) { examples.put("invalidList",invalidList); } @Test public void shouldAppendTypeFieldWhenSerializingMaterials() { CRMaterial value = named; JsonObject jsonObject = (JsonObject)gson.toJsonTree(value); assertThat(jsonObject.get("type").getAsString(), is(CRConfigMaterial.TYPE_NAME)); } @Test public void shouldHandlePolymorphismWhenDeserializing() { CRMaterial value = named; String json = gson.toJson(value); CRConfigMaterial deserializedValue = (CRConfigMaterial)gson.fromJson(json,CRMaterial.class); assertThat("Deserialized value should equal to value before serialization", deserializedValue,is(value)); } }
Java
# ------------------------------------------------------------- # # 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. # # ------------------------------------------------------------- # Autogenerated By : src/main/python/generator/generator.py # Autogenerated From : scripts/builtin/garch.dml from typing import Dict, Iterable from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar from systemds.script_building.dag import OutputType from systemds.utils.consts import VALID_INPUT_TYPES def garch(X: Matrix, kmax: int, momentum: float, start_stepsize: float, end_stepsize: float, start_vicinity: float, end_vicinity: float, sim_seed: int, verbose: bool): """ :param X: The input Matrix to apply Arima on. :param kmax: Number of iterations :param momentum: Momentum for momentum-gradient descent (set to 0 to deactivate) :param start_stepsize: Initial gradient-descent stepsize :param end_stepsize: gradient-descent stepsize at end (linear descent) :param start_vicinity: proportion of randomness of restart-location for gradient descent at beginning :param end_vicinity: same at end (linear decay) :param sim_seed: seed for simulation of process on fitted coefficients :param verbose: verbosity, comments during fitting :return: 'OperationNode' containing simulated garch(1,1) process on fitted coefficients & variances of simulated fitted process & constant term of fitted process & 1-st arch-coefficient of fitted process & 1-st garch-coefficient of fitted process & drawbacks: slow convergence of optimization (sort of simulated annealing/gradient descent) """ params_dict = {'X': X, 'kmax': kmax, 'momentum': momentum, 'start_stepsize': start_stepsize, 'end_stepsize': end_stepsize, 'start_vicinity': start_vicinity, 'end_vicinity': end_vicinity, 'sim_seed': sim_seed, 'verbose': verbose} vX_0 = Matrix(X.sds_context, '') vX_1 = Matrix(X.sds_context, '') vX_2 = Scalar(X.sds_context, '') vX_3 = Scalar(X.sds_context, '') vX_4 = Scalar(X.sds_context, '') output_nodes = [vX_0, vX_1, vX_2, vX_3, vX_4, ] op = MultiReturn(X.sds_context, 'garch', output_nodes, named_input_nodes=params_dict) vX_0._unnamed_input_nodes = [op] vX_1._unnamed_input_nodes = [op] vX_2._unnamed_input_nodes = [op] vX_3._unnamed_input_nodes = [op] vX_4._unnamed_input_nodes = [op] return op
Java
+++ Title = "Cancellation" Type = "event" Description = "Statement on what's next" +++ With a heavy heart, the organizers of Eindhoven would like to inform you that we have - at this time - decided to cancel devopsdays Eindhoven for 2020. We did not take this decision lightly, and we took a large number of variables into account. However, ultimately, the health and well-being of all of our attendees, speakers and organizers are our top priority. ### What does this mean for you? For our attendees that have already bought tickets for the events, we will - of course - be fully refunding your purchase. We will be issuing a full refund of the ticket purchase to the form of payment you used when initially purchased the ticket. Our Event Management Solution, Eventbrite, will send you a confirmation email of the cancellation & refund. Please note that the refund may take up to 14 days to process. ### What if the situation changes? When the current NL and global situation improves for the better in the months ahead, we will reassess the case, and if possible, put on an event later in the year. ### What's next Although this means no first devopsdays this year for Eindhoven, the organizers of Amsterdam and Eindhoven are busy thinking of ways to bend with the times and create an informative, vibrant, and exciting event online.
Java
package org.hl7.fhir.dstu3.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. 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 HL7 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 COPYRIGHT HOLDER 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. */ // Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0 import org.hl7.fhir.dstu3.model.EnumFactory; public class ObservationStatusEnumFactory implements EnumFactory<ObservationStatus> { public ObservationStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) return null; if ("registered".equals(codeString)) return ObservationStatus.REGISTERED; if ("preliminary".equals(codeString)) return ObservationStatus.PRELIMINARY; if ("final".equals(codeString)) return ObservationStatus.FINAL; if ("amended".equals(codeString)) return ObservationStatus.AMENDED; if ("cancelled".equals(codeString)) return ObservationStatus.CANCELLED; if ("entered-in-error".equals(codeString)) return ObservationStatus.ENTEREDINERROR; if ("unknown".equals(codeString)) return ObservationStatus.UNKNOWN; throw new IllegalArgumentException("Unknown ObservationStatus code '"+codeString+"'"); } public String toCode(ObservationStatus code) { if (code == ObservationStatus.REGISTERED) return "registered"; if (code == ObservationStatus.PRELIMINARY) return "preliminary"; if (code == ObservationStatus.FINAL) return "final"; if (code == ObservationStatus.AMENDED) return "amended"; if (code == ObservationStatus.CANCELLED) return "cancelled"; if (code == ObservationStatus.ENTEREDINERROR) return "entered-in-error"; if (code == ObservationStatus.UNKNOWN) return "unknown"; return "?"; } public String toSystem(ObservationStatus code) { return code.getSystem(); } }
Java
/* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.examples.nqueens.app; import java.io.File; import org.junit.Test; import org.optaplanner.benchmark.api.PlannerBenchmarkException; import org.optaplanner.benchmark.api.PlannerBenchmarkFactory; import org.optaplanner.benchmark.config.PlannerBenchmarkConfig; import org.optaplanner.examples.common.app.PlannerBenchmarkTest; public class BrokenNQueensBenchmarkTest extends PlannerBenchmarkTest { @Override protected String createBenchmarkConfigResource() { return "org/optaplanner/examples/nqueens/benchmark/nqueensBenchmarkConfig.xml"; } @Override protected PlannerBenchmarkFactory buildPlannerBenchmarkFactory(File unsolvedDataFile) { PlannerBenchmarkFactory benchmarkFactory = super.buildPlannerBenchmarkFactory(unsolvedDataFile); PlannerBenchmarkConfig benchmarkConfig = benchmarkFactory.getPlannerBenchmarkConfig(); benchmarkConfig.setWarmUpSecondsSpentLimit(0L); benchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getTerminationConfig() .setStepCountLimit(-100); // Intentionally crash the solver return benchmarkFactory; } // ************************************************************************ // Tests // ************************************************************************ @Test(timeout = 100000, expected = PlannerBenchmarkException.class) public void benchmarkBroken8queens() { runBenchmarkTest(new File("data/nqueens/unsolved/8queens.xml")); } }
Java
# raptor-sdk The Raptor Java SDK is part of the raptor platform and used extensively in the codebase. It can be reused as a standalone library in external application for a direct integration to the exposed API - [Requirements](#requirements) - [Setup](#Setup) - [Authentication](#authentication) - [Inventory](#inventory) - [List devices](#list-devices) - [Create a device](#create-a-device) - [Update a device](#update-a-device) - [Load a device](#load-a-device) - [Search for devices](#search-for-devices) - [Events notifications](#events-notifications) - [Watch device events](#watch-device-events) - [Watch data events](#watch-data-events) - [Watch action events](#watch-device-action-events) - [Stream](#stream) - [Push data](#push-data) - [Pull data](#pull-data) - [Last update](#last-update) - [Drop data](#drop-data) - [Search for data](#search-for-data) - [Search by time](#search-by-time) - [Search by numeric range](#search-by-numeric-range) - [Search by distance](#search-by-distance) - [Search by bounding box](#search-by-bounding-box) - [Action](#action) - [Set status](#set-status) - [Get status](#get-status) - [Invoke an action](#invoke-an-action) - [Profile](#profile) - [Set a value](#set-a-value) - [Get a value](#get-a-value) - [Get all values](#get-all-values) - [Tree](#tree) - [Create a node](#create-a-node) - [Create a device node](#create-a-device-node) - [List trees](#list-trees) - [Delete a node](#delete-a-node) - [Admin](#admin) ## Requirements - Java 8 or higher - Maven ## Setup Import in your project the `raptor-sdk` maven package. ## Authentication Let's start by initializing a raptor client instance ```java // login with username and password Raptor raptor = new Raptor("http://raptor.local", "admin", "admin") // alternatively, login with a token // Raptor raptor = new Raptor("http://raptor.local", "..token..") // login and retrieve a token AuthClient.LoginState loginInfo = raptor.Auth().login(); log.debug("Welcome {} (token: {})", loginInfo.user.getUsername(), loginInfo.token); // close the session and drop the login token raptor.Auth().logout(); ``` ## Inventory The inventory API store device definitions ### List devices List devices owned by a user ```java List<Device> list = raptor.Inventory().list(); log.debug("found {} devices", list.size()); ``` ### Create a device Create a new device definition ```java Device dev = new Device(); dev.name("test device") .description("info about"); dev.properties().put("active", true); dev.properties().put("cost", 15000L); dev.properties().put("version", "4.0.0"); dev.validate(); raptor.Inventory().create(dev); log.debug("Device created {}", dev.id()); ``` ### Update a device Update a device definition ```java // Create a data stream named ambient with a channel temperature of type number Stream s = dev.addStream("ambient", "temperature", "number"); //Add further channels of different types s.addChannel("info", "text") s.addChannel("alarm", "boolean") // add an action Action a = dev.addAction("light-control"); raptor.Inventory().update(dev); log.debug("Device updated: \n {}", dev.toJSON()); ``` ### Load a device Load a device definition ```java Device dev1 = raptor.Inventory().load(dev.id()); log.debug("Device loaded: \n {}", dev.toJSON()); ``` ### Search for devices Search for device definitions ```java DeviceQuery q = new DeviceQuery(); // all devices which name contains `test` q.name.contains("test"); // and properties.version equals to 4.0.0 q.properties.has("version", "4.0.0"); log.debug("Searching for {}", q.toJSON().toString()); List<Device> results = raptor.Inventory().search(q); log.debug("Results found {}", results.stream().map(d -> d.name()).collect(Collectors.toList())); ``` ### Event notifications When a device receive data, an action is triggered or the definition changes events are emitted over an asynchronous MQTT channel. #### Watch device events Device events are notified when a device definition changes ```java raptor.Inventory().subscribe(dev, new DeviceCallback() { @Override public void callback(Device obj, DevicePayload message) { log.debug("Device event received {}", message.toString()); } }); ``` #### Watch data events Data events are generated when a stream is updated ```java raptor.Inventory().subscribe(dev, new DataCallback() { @Override public void callback(Stream stream, RecordSet record) { log.debug("dev: Data received {}", record.toJson()); } }); ``` #### Watch action events Action events are generated when an action is triggered or the status changes ```java raptor.Inventory().subscribe(dev, new ActionCallback() { @Override public void callback(Action action, ActionPayload payload) { log.debug("dev: Data received for {}: {}", payload.actionId, payload.data ); } }); ``` ## Stream The Stream API handles data push and retrieval ### Push data Send data based on a stream definition ```java Stream stream = dev.getStream("ambient") RecordSet record = new RecordSet(stream) .channel("temperature", 5) .channel("info", "cold") .channel("alarm", true) .location(new GeoJsonPoint(11, 45)) .timestamp(Instant.now()) ; raptor.Stream().push(record) ``` ### Pull data Retrieve data ```java // return 100 records from 10 int from = 10, size = 100; ResultSet results = raptor.Stream().pull(stream, from, size); ``` ### Last update Retrieve the last record sent based on the timestamp ```java ResultSet results = raptor.Stream().lastUpdate(stream); ``` ### Drop data Removed the data stored in a stream ```java raptor.Stream().delete(stream); ``` ### Search for data #### Search by time Search for a range in the data timestamp ```java Instant i = Instant.now() DataQuery q = new DataQuery() .timeRange( i.plus(500, ChronoUnit.MILLIS), i.plus(2500, ChronoUnit.MILLIS) ); log.debug("Searching {}", q.toJSON().toString()); ResultSet results = raptor.Stream().search(stream, q); ``` #### Search by numeric range Search for a range in a numeric field ```java DataQuery q = new DataQuery() .range("temperature", -10, 10); log.debug("Searching {}", q.toJSON().toString()); ResultSet results = raptor.Stream().search(stream, q); ``` #### Search by distance Search data by distance using the `location` field ```java DataQuery q = new DataQuery() .distance(new GeoJsonPoint(11.45, 45.11), 10000, Metrics.KILOMETERS); log.debug("Searching {}", q.toJSON().toString()); ResultSet results = raptor.Stream().search(stream, q); ``` #### Search by bounding box Search data within an area using the `location` field ```java DataQuery q = new DataQuery() .boundingBox(new GeoJsonPoint(12, 45), new GeoJsonPoint(10, 44))); log.debug("Searching {}", q.toJSON().toString()); ResultSet results = raptor.Stream().search(stream, q); ``` ## Action The Action API handles status and triggering of device defined actions ### Set status Store the current status of an action ```java Action a = dev.action("light-control"); ActionStatus status = raptor.Action() .setStatus(a, a.getStatus().status("on")); ``` ### Get status Get the current stored status of an action ```java Action a = dev.action("light-control"); ActionStatus status = raptor.Action() .getStatus(a); ``` ### Invoke an action Trigger an action on the remote device ```java Action a = dev.action("light-control"); ActionStatus status = raptor.Action() .invoke(a); ``` Set the status of an action ## Profile The Profile API handles a per-user key-value local store ### Set a value Set a value by key ```java ObjectNode json = r.Profile().newObjectNode(); json.put("test", "foo"); json.put("size", 1000L); json.put("valid", true); r.Profile().set("test1", json); ``` ### Get a value Get a value by key ```java JsonNode response = r.Profile().get("test1"); ``` ### Get all values Get all values ```java JsonNode response = r.Profile().get(); ``` ## Tree The Tree API handles hierarchical data structures ### Create a node Create a generic (type `group`) node tree ```java TreeNode node1 = TreeNode.create("Root1"); raptor.Tree().create(node1); TreeNode child1 = TreeNode.create("child1"); TreeNode child2 = TreeNode.create("child2"); raptor.Tree().add(node1, Arrays.asList(child1)); raptor.Tree().add(child1, Arrays.asList(child2)); ``` ### Create a device node Create a device references inside the tree. Events from that device will be propagated to the parent nodes up to the root ```java raptor.Tree().add(child2, dev); ``` ### List trees List all the trees available ```java List<TreeNode> list = raptor.Tree().list(); ``` ### Delete a node Delete a node, causing all the leaves to be point to the parent. In case of `device` node references, this will not remove the device ```java // drop child1 from previous example, child2 will be now direct children of Root1 raptor.Tree().remove( node1 //Root1 .children().get(0) // child1 ); ``` ## Admin Admin APIs allow the management of users, tokens and permissions For an up to date reference see the [tests](https://github.com/raptorbox/raptor/tree/master/raptor-sdk/src/test/java/org/createnet/raptor/sdk/admin) ## License Apache2 ``` Copyright FBK/CREATE-NET 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. ```
Java
/* * 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.accumulo.monitor.util.celltypes; import java.io.Serializable; import java.util.Comparator; public abstract class CellType<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = 1L; private boolean sortable = true; abstract public String alignment(); abstract public String format(Object obj); public final void setSortable(boolean sortable) { this.sortable = sortable; } public final boolean isSortable() { return sortable; } }
Java
package io.cattle.platform.process.dao.impl; import static io.cattle.platform.core.model.tables.AccountTable.*; import io.cattle.platform.core.model.Account; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.process.dao.AccountDao; public class AccountDaoImpl extends AbstractJooqDao implements AccountDao { @Override public Account findByUuid(String uuid) { return create() .selectFrom(ACCOUNT) .where(ACCOUNT.UUID.eq(uuid)) .fetchOne(); } }
Java
package net.ros.client.render; import com.google.common.collect.ImmutableList; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.ros.client.render.model.ModelCacheManager; import net.ros.client.render.model.obj.PipeOBJStates; import net.ros.client.render.model.obj.ROSOBJState; import net.ros.common.block.BlockPipeBase; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; import javax.vecmath.Matrix4f; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class ModelPipeInventory implements IBakedModel { private final Map<ROSOBJState, CompositeBakedModel> CACHE = new HashMap<>(); private final BlockPipeBase pipeBlock; public ModelPipeInventory(BlockPipeBase pipeBlock) { this.pipeBlock = pipeBlock; } @Nonnull @Override public List<BakedQuad> getQuads(IBlockState state, EnumFacing face, long rand) { return Collections.emptyList(); } private CompositeBakedModel getModel(ROSOBJState pipeState) { if (CACHE.containsKey(pipeState)) return CACHE.get(pipeState); else { CompositeBakedModel model = new CompositeBakedModel(ModelCacheManager.getPipeQuads(pipeBlock, pipeState), Minecraft.getMinecraft().getBlockRendererDispatcher() .getModelForState(pipeBlock.getDefaultState())); CACHE.put(pipeState, model); return model; } } @Nonnull @Override public ItemOverrideList getOverrides() { return itemHandler; } @Override public boolean isAmbientOcclusion() { return false; } @Override public boolean isGui3d() { return true; } @Override public boolean isBuiltInRenderer() { return false; } @Nonnull @Override public TextureAtlasSprite getParticleTexture() { return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/dirt"); } @Nonnull @Override public ItemCameraTransforms getItemCameraTransforms() { return ItemCameraTransforms.DEFAULT; } private static class CompositeBakedModel implements IBakedModel { private IBakedModel pipeModel; private final List<BakedQuad> genQuads; CompositeBakedModel(List<BakedQuad> pipeQuads, IBakedModel pipeModel) { this.pipeModel = pipeModel; ImmutableList.Builder<BakedQuad> genBuilder = ImmutableList.builder(); genBuilder.addAll(pipeQuads); genQuads = genBuilder.build(); } @Nonnull @Override public List<BakedQuad> getQuads(IBlockState state, EnumFacing face, long rand) { return face == null ? genQuads : Collections.emptyList(); } @Override public boolean isAmbientOcclusion() { return pipeModel.isAmbientOcclusion(); } @Override public boolean isGui3d() { return pipeModel.isGui3d(); } @Override public boolean isBuiltInRenderer() { return pipeModel.isBuiltInRenderer(); } @Nonnull @Override public TextureAtlasSprite getParticleTexture() { return pipeModel.getParticleTexture(); } @Nonnull @Override public ItemOverrideList getOverrides() { return ItemOverrideList.NONE; } @Override public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { return Pair.of(this, pipeModel.handlePerspective(cameraTransformType).getRight()); } } private final ItemOverrideList itemHandler = new ItemOverrideList(ImmutableList.of()) { @Nonnull @Override public IBakedModel handleItemState(@Nonnull IBakedModel model, ItemStack stack, World world, EntityLivingBase entity) { return ModelPipeInventory.this.getModel(PipeOBJStates.getVisibilityState( pipeBlock.getPipeType().getSize(), EnumFacing.WEST, EnumFacing.EAST)); } }; }
Java
package hulk.http.response import akka.http.scaladsl.model.HttpEntity.Strict import akka.http.scaladsl.model.{ContentType, ResponseEntity} import akka.util.ByteString /** * Created by reweber on 24/12/2015 */ case class HttpResponseBody(contentType: ContentType, data: ByteString) object HttpResponseBody { implicit private[hulk] def toResponseEntity(httpResponseBody: HttpResponseBody): ResponseEntity = { Strict(httpResponseBody.contentType, httpResponseBody.data) } }
Java
<?php declare(strict_types=1); namespace App\Radio; use App\Entity; use App\Environment; use App\Exception\Supervisor\AlreadyRunningException; use App\Exception\Supervisor\BadNameException; use App\Exception\Supervisor\NotRunningException; use App\Exception\SupervisorException; use Doctrine\ORM\EntityManagerInterface; use Psr\EventDispatcher\EventDispatcherInterface; use Psr\Log\LoggerInterface; use Supervisor\Exception\Fault; use Supervisor\Exception\SupervisorException as SupervisorLibException; use Supervisor\Process; use Supervisor\Supervisor; abstract class AbstractAdapter { public function __construct( protected Environment $environment, protected EntityManagerInterface $em, protected Supervisor $supervisor, protected EventDispatcherInterface $dispatcher, protected LoggerInterface $logger ) { } /** * Write configuration from Station object to the external service. * * @param Entity\Station $station * * @return bool Whether the newly written configuration differs from what was already on disk. */ public function write(Entity\Station $station): bool { $configPath = $this->getConfigurationPath($station); if (null === $configPath) { return false; } $currentConfig = (is_file($configPath)) ? file_get_contents($configPath) : null; $newConfig = $this->getCurrentConfiguration($station); file_put_contents($configPath, $newConfig); return 0 !== strcmp($currentConfig ?: '', $newConfig ?: ''); } /** * Generate the configuration for this adapter as it would exist with current database settings. * * @param Entity\Station $station * */ public function getCurrentConfiguration(Entity\Station $station): ?string { return null; } /** * Returns the main path where configuration data is stored for this adapter. * */ public function getConfigurationPath(Entity\Station $station): ?string { return null; } /** * Indicate if the adapter in question is installed on the server. */ public function isInstalled(): bool { return (null !== $this->getBinary()); } /** * Return the binary executable location for this item. * * @return string|null Returns either the path to the binary if it exists or null for no binary. */ public function getBinary(): ?string { return null; } /** * Check if the service is running. * * @param Entity\Station $station */ public function isRunning(Entity\Station $station): bool { if (!$this->hasCommand($station)) { return true; } $program_name = $this->getProgramName($station); try { $process = $this->supervisor->getProcess($program_name); return $process instanceof Process && $process->isRunning(); } catch (Fault\BadNameException) { return false; } } /** * Return a boolean indicating whether the adapter has an executable command associated with it. * * @param Entity\Station $station */ public function hasCommand(Entity\Station $station): bool { if ($this->environment->isTesting() || !$station->getIsEnabled()) { return false; } return ($this->getCommand($station) !== null); } /** * Return the shell command required to run the program. * * @param Entity\Station $station */ public function getCommand(Entity\Station $station): ?string { return null; } /** * Return the program's fully qualified supervisord name. * * @param Entity\Station $station */ abstract public function getProgramName(Entity\Station $station): string; /** * Restart the executable service. * * @param Entity\Station $station */ public function restart(Entity\Station $station): void { $this->stop($station); $this->start($station); } /** * @return bool Whether this adapter supports a non-destructive reload. */ public function supportsReload(): bool { return false; } /** * Execute a non-destructive reload if the adapter supports it. * * @param Entity\Station $station */ public function reload(Entity\Station $station): void { $this->restart($station); } /** * Stop the executable service. * * @param Entity\Station $station * * @throws SupervisorException * @throws NotRunningException */ public function stop(Entity\Station $station): void { if ($this->hasCommand($station)) { $program_name = $this->getProgramName($station); try { $this->supervisor->stopProcess($program_name); $this->logger->info( 'Adapter "' . static::class . '" stopped.', ['station_id' => $station->getId(), 'station_name' => $station->getName()] ); } catch (SupervisorLibException $e) { $this->handleSupervisorException($e, $program_name, $station); } } } /** * Start the executable service. * * @param Entity\Station $station * * @throws SupervisorException * @throws AlreadyRunningException */ public function start(Entity\Station $station): void { if ($this->hasCommand($station)) { $program_name = $this->getProgramName($station); try { $this->supervisor->startProcess($program_name); $this->logger->info( 'Adapter "' . static::class . '" started.', ['station_id' => $station->getId(), 'station_name' => $station->getName()] ); } catch (SupervisorLibException $e) { $this->handleSupervisorException($e, $program_name, $station); } } } /** * Internal handling of any Supervisor-related exception, to add richer data to it. * * @param SupervisorLibException $e * @param string $program_name * @param Entity\Station $station * * @throws AlreadyRunningException * @throws BadNameException * @throws NotRunningException * @throws SupervisorException */ protected function handleSupervisorException( SupervisorLibException $e, string $program_name, Entity\Station $station ): void { $class_parts = explode('\\', static::class); $class_name = array_pop($class_parts); if ($e instanceof Fault\BadNameException) { $e_headline = __('%s is not recognized as a service.', $class_name); $e_body = __('It may not be registered with Supervisor yet. Restarting broadcasting may help.'); $app_e = new BadNameException( $e_headline . '; ' . $e_body, $e->getCode(), $e ); } elseif ($e instanceof Fault\AlreadyStartedException) { $e_headline = __('%s cannot start', $class_name); $e_body = __('It is already running.'); $app_e = new AlreadyRunningException( $e_headline . '; ' . $e_body, $e->getCode(), $e ); } elseif ($e instanceof Fault\NotRunningException) { $e_headline = __('%s cannot stop', $class_name); $e_body = __('It is not running.'); $app_e = new NotRunningException( $e_headline . '; ' . $e_body, $e->getCode(), $e ); } else { $e_headline = __('%s encountered an error', $class_name); // Get more detailed information for more significant errors. $process_log = $this->supervisor->tailProcessStdoutLog($program_name, 0, 500); $process_log = array_values(array_filter(explode("\n", $process_log[0]))); $process_log = array_slice($process_log, -6); $e_body = (!empty($process_log)) ? implode('<br>', $process_log) : __('Check the log for details.'); $app_e = new SupervisorException($e_headline, $e->getCode(), $e); $app_e->addExtraData('supervisor_log', $process_log); $app_e->addExtraData('supervisor_process_info', $this->supervisor->getProcessInfo($program_name)); } $app_e->setFormattedMessage('<b>' . $e_headline . '</b><br>' . $e_body); $app_e->addLoggingContext('station_id', $station->getId()); $app_e->addLoggingContext('station_name', $station->getName()); throw $app_e; } /** * Return the path where logs are written to. * * @param Entity\Station $station */ public function getLogPath(Entity\Station $station): string { $config_dir = $station->getRadioConfigDir(); $class_parts = explode('\\', static::class); $class_name = array_pop($class_parts); return $config_dir . '/' . strtolower($class_name) . '.log'; } }
Java
--- datafolder: engine-cli datafile: docker_run title: docker run --- <!-- Sorry, but the contents of this page are automatically generated from Docker's source code. If you want to suggest a change to the text that appears here, you'll need to find the string by searching this repo: https://www.github.com/docker/docker --> {% include cli.md %}
Java
import React, { Component, Fragment } from 'react'; import { navigate } from '@reach/router'; import PropTypes from 'prop-types'; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; import { siteRoot, gettext, orgID } from '../../utils/constants'; import { seafileAPI } from '../../utils/seafile-api'; import { Utils } from '../../utils/utils'; import toaster from '../../components/toast'; import OrgGroupInfo from '../../models/org-group'; import MainPanelTopbar from './main-panel-topbar'; class Search extends React.Component { constructor(props) { super(props); this.state = { value: '' }; } handleInputChange = (e) => { this.setState({ value: e.target.value }); } handleKeyPress = (e) => { if (e.key == 'Enter') { e.preventDefault(); this.handleSubmit(); } } handleSubmit = () => { const value = this.state.value.trim(); if (!value) { return false; } this.props.submit(value); } render() { return ( <div className="input-icon"> <i className="d-flex input-icon-addon fas fa-search"></i> <input type="text" className="form-control search-input h-6 mr-1" style={{width: '15rem'}} placeholder={this.props.placeholder} value={this.state.value} onChange={this.handleInputChange} onKeyPress={this.handleKeyPress} autoComplete="off" /> </div> ); } } class OrgGroups extends Component { constructor(props) { super(props); this.state = { page: 1, pageNext: false, orgGroups: [], isItemFreezed: false }; } componentDidMount() { let page = this.state.page; this.initData(page); } initData = (page) => { seafileAPI.orgAdminListOrgGroups(orgID, page).then(res => { let orgGroups = res.data.groups.map(item => { return new OrgGroupInfo(item); }); this.setState({ orgGroups: orgGroups, pageNext: res.data.page_next, page: res.data.page, }); }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } onChangePageNum = (e, num) => { e.preventDefault(); let page = this.state.page; if (num == 1) { page = page + 1; } else { page = page - 1; } this.initData(page); } onFreezedItem = () => { this.setState({isItemFreezed: true}); } onUnfreezedItem = () => { this.setState({isItemFreezed: false}); } deleteGroupItem = (group) => { seafileAPI.orgAdminDeleteOrgGroup(orgID, group.id).then(res => { this.setState({ orgGroups: this.state.orgGroups.filter(item => item.id != group.id) }); let msg = gettext('Successfully deleted {name}'); msg = msg.replace('{name}', group.groupName); toaster.success(msg); }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } searchItems = (keyword) => { navigate(`${siteRoot}org/groupadmin/search-groups/?query=${encodeURIComponent(keyword)}`); } getSearch = () => { return <Search placeholder={gettext('Search groups by name')} submit={this.searchItems} />; } render() { let groups = this.state.orgGroups; return ( <Fragment> <MainPanelTopbar search={this.getSearch()}/> <div className="main-panel-center flex-row"> <div className="cur-view-container"> <div className="cur-view-path"> <h3 className="sf-heading">{gettext('All Groups')}</h3> </div> <div className="cur-view-content"> <table> <thead> <tr> <th width="30%">{gettext('Name')}</th> <th width="35%">{gettext('Creator')}</th> <th width="23%">{gettext('Created At')}</th> <th width="12%" className="text-center">{gettext('Operations')}</th> </tr> </thead> <tbody> {groups.map(item => { return ( <GroupItem key={item.id} group={item} isItemFreezed={this.state.isItemFreezed} onFreezedItem={this.onFreezedItem} onUnfreezedItem={this.onUnfreezedItem} deleteGroupItem={this.deleteGroupItem} /> ); })} </tbody> </table> <div className="paginator"> {this.state.page != 1 && <a href="#" onClick={(e) => this.onChangePageNum(e, -1)}>{gettext('Previous')}</a>} {(this.state.page != 1 && this.state.pageNext) && <span> | </span>} {this.state.pageNext && <a href="#" onClick={(e) => this.onChangePageNum(e, 1)}>{gettext('Next')}</a>} </div> </div> </div> </div> </Fragment> ); } } const GroupItemPropTypes = { group: PropTypes.object.isRequired, isItemFreezed: PropTypes.bool.isRequired, onFreezedItem: PropTypes.func.isRequired, onUnfreezedItem: PropTypes.func.isRequired, deleteGroupItem: PropTypes.func.isRequired, }; class GroupItem extends React.Component { constructor(props) { super(props); this.state = { highlight: false, showMenu: false, isItemMenuShow: false }; } onMouseEnter = () => { if (!this.props.isItemFreezed) { this.setState({ showMenu: true, highlight: true, }); } } onMouseLeave = () => { if (!this.props.isItemFreezed) { this.setState({ showMenu: false, highlight: false }); } } onDropdownToggleClick = (e) => { e.preventDefault(); this.toggleOperationMenu(e); } toggleOperationMenu = (e) => { e.stopPropagation(); this.setState( {isItemMenuShow: !this.state.isItemMenuShow }, () => { if (this.state.isItemMenuShow) { this.props.onFreezedItem(); } else { this.setState({ highlight: false, showMenu: false, }); this.props.onUnfreezedItem(); } } ); } toggleDelete = () => { this.props.deleteGroupItem(this.props.group); } renderGroupHref = (group) => { let groupInfoHref; if (group.creatorName == 'system admin') { groupInfoHref = siteRoot + 'org/departmentadmin/groups/' + group.id + '/'; } else { groupInfoHref = siteRoot + 'org/groupadmin/' + group.id + '/'; } return groupInfoHref; } renderGroupCreator = (group) => { let userInfoHref = siteRoot + 'org/useradmin/info/' + group.creatorEmail + '/'; if (group.creatorName == 'system admin') { return ( <td> -- </td> ); } else { return( <td> <a href={userInfoHref} className="font-weight-normal">{group.creatorName}</a> </td> ); } } render() { let { group } = this.props; let isOperationMenuShow = (group.creatorName != 'system admin') && this.state.showMenu; return ( <tr className={this.state.highlight ? 'tr-highlight' : ''} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}> <td> <a href={this.renderGroupHref(group)} className="font-weight-normal">{group.groupName}</a> </td> {this.renderGroupCreator(group)} <td>{group.ctime}</td> <td className="text-center cursor-pointer"> {isOperationMenuShow && <Dropdown isOpen={this.state.isItemMenuShow} toggle={this.toggleOperationMenu}> <DropdownToggle tag="a" className="attr-action-icon fas fa-ellipsis-v" title={gettext('More Operations')} data-toggle="dropdown" aria-expanded={this.state.isItemMenuShow} onClick={this.onDropdownToggleClick} /> <DropdownMenu> <DropdownItem onClick={this.toggleDelete}>{gettext('Delete')}</DropdownItem> </DropdownMenu> </Dropdown> } </td> </tr> ); } } GroupItem.propTypes = GroupItemPropTypes; export default OrgGroups;
Java
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.sessions; import com.intellij.testFramework.TestDataPath; import org.jetbrains.kotlin.test.JUnit3RunnerWithInners; import org.jetbrains.kotlin.test.KotlinTestUtils; import org.jetbrains.kotlin.test.TestMetadata; import org.junit.runner.RunWith; import java.io.File; import java.util.regex.Pattern; /** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */ @SuppressWarnings("all") @TestMetadata("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation") @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class) public class SessionsInvalidationTestGenerated extends AbstractSessionsInvalidationTest { private void runTest(String testDataFilePath) throws Exception { KotlinTestUtils.runTest(this::doTest, this, testDataFilePath); } public void testAllFilesPresentInSessionInvalidation() throws Exception { KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation"), Pattern.compile("^([^\\.]+)$"), null, false); } @TestMetadata("binaryTree") public void testBinaryTree() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTree/"); } @TestMetadata("binaryTreeNoInvalidated") public void testBinaryTreeNoInvalidated() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTreeNoInvalidated/"); } @TestMetadata("binaryTreeWithAdditionalEdge") public void testBinaryTreeWithAdditionalEdge() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTreeWithAdditionalEdge/"); } @TestMetadata("binaryTreeWithInvalidInRoot") public void testBinaryTreeWithInvalidInRoot() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTreeWithInvalidInRoot/"); } @TestMetadata("linear") public void testLinear() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/linear/"); } @TestMetadata("rhombus") public void testRhombus() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/rhombus/"); } @TestMetadata("rhombusWithTwoInvalid") public void testRhombusWithTwoInvalid() throws Exception { runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/rhombusWithTwoInvalid/"); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.github.jass2125.locadora.jpa; import javax.persistence.EntityManager; import javax.persistence.Persistence; /** * * @author Anderson Souza * @email [email protected] * @since 2015, Feb 9, 2016 */ public class EntityManagerJPA { private static EntityManager em; private EntityManagerJPA() { } public static EntityManager getEntityManager(){ if(em == null) { em = Persistence.createEntityManagerFactory("default").createEntityManager(); } return em; } }
Java
import {boolean, number, object, text, withKnobs} from '@storybook/addon-knobs'; import { BentoAccordion, BentoAccordionContent, BentoAccordionHeader, BentoAccordionSection, } from '#bento/components/bento-accordion/1.0/component'; import {BentoVideo} from '#bento/components/bento-video/1.0/component'; import * as Preact from '#preact'; import '#bento/components/bento-video/1.0/component.jss'; export default { title: 'Video', component: BentoVideo, decorators: [withKnobs], }; const VideoTagPlayer = ({i}) => { const group = `Player ${i + 1}`; const width = text('width', '640px', group); const height = text('height', '360px', group); const ariaLabel = text('aria-label', 'Video Player', group); const autoplay = boolean('autoplay', true, group); const controls = boolean('controls', true, group); const mediasession = boolean('mediasession', true, group); const noaudio = boolean('noaudio', false, group); const loop = boolean('loop', false, group); const poster = text( 'poster', 'https://amp.dev/static/inline-examples/images/kitten-playing.png', group ); const artist = text('artist', '', group); const album = text('album', '', group); const artwork = text('artwork', '', group); const title = text('title', '', group); const sources = object( 'sources', [ { src: 'https://amp.dev/static/inline-examples/videos/kitten-playing.webm', type: 'video/webm', }, { src: 'https://amp.dev/static/inline-examples/videos/kitten-playing.mp4', type: 'video/mp4', }, ], group ); return ( <BentoVideo component="video" aria-label={ariaLabel} autoplay={autoplay} controls={controls} mediasession={mediasession} noaudio={noaudio} loop={loop} poster={poster} artist={artist} album={album} artwork={artwork} title={title} style={{width, height}} sources={sources.map((props) => ( <source {...props}></source> ))} /> ); }; const Spacer = ({height}) => { return ( <div style={{ height, background: `linear-gradient(to bottom, #bbb, #bbb 10%, #fff 10%, #fff)`, backgroundSize: '100% 10px', }} ></div> ); }; export const Default = () => { const amount = number('Amount', 1, {}, 'Page'); const spacerHeight = text('Space', '80vh', 'Page'); const spaceAbove = boolean('Space above', false, 'Page'); const spaceBelow = boolean('Space below', false, 'Page'); const players = []; for (let i = 0; i < amount; i++) { players.push(<VideoTagPlayer key={i} i={i} />); if (i < amount - 1) { players.push(<Spacer height={spacerHeight} />); } } return ( <> {spaceAbove && <Spacer height={spacerHeight} />} {players} {spaceBelow && <Spacer height={spacerHeight} />} </> ); }; export const InsideAccordion = () => { const width = text('width', '320px'); const height = text('height', '180px'); return ( <BentoAccordion expandSingleSection> <BentoAccordionSection key={1} expanded> <BentoAccordionHeader> <h2>Controls</h2> </BentoAccordionHeader> <BentoAccordionContent> <BentoVideo component="video" controls={true} loop={true} style={{width, height}} src="https://amp.dev/static/inline-examples/videos/kitten-playing.mp4" poster="https://amp.dev/static/inline-examples/images/kitten-playing.png" /> </BentoAccordionContent> </BentoAccordionSection> <BentoAccordionSection key={2}> <BentoAccordionHeader> <h2>Autoplay</h2> </BentoAccordionHeader> <BentoAccordionContent> <BentoVideo component="video" autoplay={true} loop={true} style={{width, height}} src="https://amp.dev/static/inline-examples/videos/kitten-playing.mp4" poster="https://amp.dev/static/inline-examples/images/kitten-playing.png" sources={[ <source type="video/mp4" src="https://amp.dev/static/inline-examples/videos/kitten-playing.mp4" />, ]} /> </BentoAccordionContent> </BentoAccordionSection> </BentoAccordion> ); };
Java
/******************************************************************************* * Copyright 2012 Apigee Corporation * * 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.usergrid.persistence.query.tree; import org.antlr.runtime.Token; import org.usergrid.persistence.exceptions.PersistenceException; /** * @author tnine * */ public class ContainsOperand extends Operand { /** * @param property * @param literal */ public ContainsOperand(Token t) { super(t); } /* (non-Javadoc) * @see org.usergrid.persistence.query.tree.Operand#visit(org.usergrid.persistence.query.tree.QueryVisitor) */ @Override public void visit(QueryVisitor visitor) throws PersistenceException { visitor.visit(this); } public void setProperty(String name){ setChild(0, new Property(name)); } public void setValue(String value){ setChild(1, new StringLiteral(value)); } public Property getProperty(){ return (Property) this.children.get(0); } public StringLiteral getString(){ return (StringLiteral) this.children.get(1); } }
Java
# Upating charts and values.yaml The charts in the `manifests` directory are used in istioctl to generate an installation manifest. The configuration settings contained in values.yaml files and passed through the CLI are validated against a [schema](../../operator/pkg/apis/istio/v1alpha1/values_types.proto). Whenever making changes in the charts, it's important to follow the below steps. ## Step 0. Check that any schema change really belongs in values.yaml Is this a new parameter being added? If not, go to the next step. Dynamic, runtime config that is used to configure Istio components should go into the [MeshConfig API](https://github.com/istio/api/blob/master/mesh/v1alpha1/config.proto). Values.yaml is being deprecated and adding to it is discouraged. MeshConfig is the official API which follows API management practices and is dynamic (does not require component restarts). Exceptions to this rule are configuration items that affect K8s level settings (resources, mounts etc.) ## Step 1. Make changes in charts and values.yaml in `manifests` directory ## Step 2. Make corresponding values changes in [../profiles/default.yaml](../profiles/default.yaml) The values.yaml in `manifests` are only used for direct Helm based installations, which is being deprecated. If any values.yaml changes are being made, the same changes must be made in the `manifests/profiles/default.yaml` file, which must be in sync with the Helm values in `manifests`. ## Step 3. Update the validation schema Istioctl uses a [schema](../../operator/pkg/apis/istio/v1alpha1/values_types.proto) to validate the values. Any changes to the schema must be added here, otherwise istioctl users will see errors. Once the schema file is updated, run: ```bash $ make operator-proto ``` This will regenerate the Go structs used for schema validation. ## Step 4. Update the generated manifests Tests of istioctl use the auto-generated manifests to ensure that the istioctl binary has the correct version of the charts. These manifests can be found in [gen-istio.yaml](../charts/istio-control/istio-discovery/files/gen-istio.yaml). To regenerate the manifests, run: ```bash $ make gen ``` ## Step 5. Update golden files The new charts/values will likely produce different installation manifests. Unit tests that expect a certain command output will fail for this reason. To update the golden output files, run: ```bash $ make refresh-goldens ``` This will generate git diffs in the golden output files. Check that the changes are what you expect. ## Step 6. Create a PR using outputs from Steps 1 to 5 Your PR should pass all the checks if you followed these steps.
Java
/* * 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.directory.server.core.api.subtree; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.api.ldap.model.subtree.SubtreeSpecification; import org.apache.directory.server.core.api.event.Evaluator; import org.apache.directory.server.core.api.event.ExpressionEvaluator; /** * An evaluator used to determine if an entry is included in the collection * represented by a subtree specification. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class SubtreeEvaluator { /** A refinement filter evaluator */ private final Evaluator evaluator; /** * Creates a subtreeSpecification evaluatior which can be used to determine * if an entry is included within the collection of a subtree. * * @param schemaManager The server schemaManager */ public SubtreeEvaluator( SchemaManager schemaManager ) { evaluator = new ExpressionEvaluator( schemaManager ); } /** * Determines if an entry is selected by a subtree specification. * * @param subtree the subtree specification * @param apDn the distinguished name of the administrative point containing the subentry * @param entryDn the distinguished name of the candidate entry * @param entry The entry to evaluate * @return true if the entry is selected by the specification, false if it is not * @throws LdapException if errors are encountered while evaluating selection */ public boolean evaluate( SubtreeSpecification subtree, Dn apDn, Dn entryDn, Entry entry ) throws LdapException { /* ===================================================================== * NOTE: Regarding the overall approach, we try to narrow down the * possibilities by slowly pruning relative names off of the entryDn. * For example we check first if the entry is a descendant of the AP. * If so we use the relative name thereafter to calculate if it is * a descendant of the base. This means shorter names to compare and * less work to do while we continue to deduce inclusion by the subtree * specification. * ===================================================================== */ // First construct the subtree base, which is the concatenation of the // AP Dn and the subentry base Dn subentryBaseDn = apDn; subentryBaseDn = subentryBaseDn.add( subtree.getBase() ); if ( !entryDn.isDescendantOf( subentryBaseDn ) ) { // The entry Dn is not part of the subtree specification, get out return false; } /* * Evaluate based on minimum and maximum chop values. Here we simply * need to compare the distances respectively with the size of the * baseRelativeRdn. For the max distance entries with a baseRelativeRdn * size greater than the max distance are rejected. For the min distance * entries with a baseRelativeRdn size less than the minimum distance * are rejected. */ int entryRelativeDnSize = entryDn.size() - subentryBaseDn.size(); if ( ( subtree.getMaxBaseDistance() != SubtreeSpecification.UNBOUNDED_MAX ) && ( entryRelativeDnSize > subtree.getMaxBaseDistance() ) ) { return false; } if ( ( subtree.getMinBaseDistance() > 0 ) && ( entryRelativeDnSize < subtree.getMinBaseDistance() ) ) { return false; } /* * For specific exclusions we must iterate through the set and check * if the baseRelativeRdn is a descendant of the exclusion. The * isDescendant() function will return true if the compared names * are equal so for chopAfter exclusions we must check for equality * as well and reject if the relative names are equal. */ // Now, get the entry's relative part if ( !subtree.getChopBeforeExclusions().isEmpty() || !subtree.getChopAfterExclusions().isEmpty() ) { Dn entryRelativeDn = entryDn.getDescendantOf( apDn ).getDescendantOf( subtree.getBase() ); for ( Dn chopBeforeDn : subtree.getChopBeforeExclusions() ) { if ( entryRelativeDn.isDescendantOf( chopBeforeDn ) ) { return false; } } for ( Dn chopAfterDn : subtree.getChopAfterExclusions() ) { if ( entryRelativeDn.isDescendantOf( chopAfterDn ) && !chopAfterDn.equals( entryRelativeDn ) ) { return false; } } } /* * The last remaining step is to check and see if the refinement filter * selects the entry candidate based on objectClass attribute values. * To do this we invoke the refinement evaluator members evaluate() method. */ if ( subtree.getRefinement() != null ) { return evaluator.evaluate( subtree.getRefinement(), entryDn, entry ); } /* * If nothing has rejected the candidate entry and there is no refinement * filter then the entry is included in the collection represented by the * subtree specification so we return true. */ return true; } }
Java
namespace SmartyStreets { public class RequestEntityTooLargeException : SmartyException { public RequestEntityTooLargeException() { } public RequestEntityTooLargeException(string message) : base(message) { } } }
Java
## array.jl: Dense arrays typealias Vector{T} Array{T,1} typealias Matrix{T} Array{T,2} typealias VecOrMat{T} Union(Vector{T}, Matrix{T}) typealias DenseVector{T} DenseArray{T,1} typealias DenseMatrix{T} DenseArray{T,2} typealias DenseVecOrMat{T} Union(DenseVector{T}, DenseMatrix{T}) typealias StridedArray{T,N,A<:DenseArray} Union(DenseArray{T,N}, SubArray{T,N,A}) typealias StridedVector{T,A<:DenseArray} Union(DenseArray{T,1}, SubArray{T,1,A}) typealias StridedMatrix{T,A<:DenseArray} Union(DenseArray{T,2}, SubArray{T,2,A}) typealias StridedVecOrMat{T} Union(StridedVector{T}, StridedMatrix{T}) ## Basic functions ## size(a::Array) = arraysize(a) size(a::Array, d) = arraysize(a, d) size(a::Matrix) = (arraysize(a,1), arraysize(a,2)) length(a::Array) = arraylen(a) elsize{T}(a::Array{T}) = isbits(T) ? sizeof(T) : sizeof(Ptr) sizeof(a::Array) = elsize(a) * length(a) strides{T}(a::Array{T,1}) = (1,) strides{T}(a::Array{T,2}) = (1, size(a,1)) strides{T}(a::Array{T,3}) = (1, size(a,1), size(a,1)*size(a,2)) isassigned(a::Array, i::Int...) = isdefined(a, i...) ## copy ## function unsafe_copy!{T}(dest::Ptr{T}, src::Ptr{T}, N) ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Uint), dest, src, N*sizeof(T)) return dest end function unsafe_copy!{T}(dest::Array{T}, dsto, src::Array{T}, so, N) if isbits(T) unsafe_copy!(pointer(dest, dsto), pointer(src, so), N) else for i=0:N-1 @inbounds arrayset(dest, src[i+so], i+dsto) end end return dest end function copy!{T}(dest::Array{T}, dsto::Integer, src::Array{T}, so::Integer, N::Integer) if so+N-1 > length(src) || dsto+N-1 > length(dest) || dsto < 1 || so < 1 throw(BoundsError()) end unsafe_copy!(dest, dsto, src, so, N) end copy!{T}(dest::Array{T}, src::Array{T}) = copy!(dest, 1, src, 1, length(src)) function reinterpret{T,S}(::Type{T}, a::Array{S,1}) nel = int(div(length(a)*sizeof(S),sizeof(T))) # TODO: maybe check that remainder is zero? return reinterpret(T, a, (nel,)) end function reinterpret{T,S}(::Type{T}, a::Array{S}) if sizeof(S) != sizeof(T) error("result shape not specified") end reinterpret(T, a, size(a)) end function reinterpret{T,S,N}(::Type{T}, a::Array{S}, dims::NTuple{N,Int}) if !isbits(T) error("cannot reinterpret to type ", T) end if !isbits(S) error("cannot reinterpret Array of type ", S) end nel = div(length(a)*sizeof(S),sizeof(T)) if prod(dims) != nel throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(nel)")) end ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) end # reshaping to same # of dimensions function reshape{T,N}(a::Array{T,N}, dims::NTuple{N,Int}) if prod(dims) != length(a) throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) end if dims == size(a) return a end ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) end # reshaping to different # of dimensions function reshape{T,N}(a::Array{T}, dims::NTuple{N,Int}) if prod(dims) != length(a) throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) end ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) end ## Constructors ## similar(a::Array, T, dims::Dims) = Array(T, dims) similar{T}(a::Array{T,1}) = Array(T, size(a,1)) similar{T}(a::Array{T,2}) = Array(T, size(a,1), size(a,2)) similar{T}(a::Array{T,1}, dims::Dims) = Array(T, dims) similar{T}(a::Array{T,1}, m::Int) = Array(T, m) similar{T}(a::Array{T,1}, S) = Array(S, size(a,1)) similar{T}(a::Array{T,2}, dims::Dims) = Array(T, dims) similar{T}(a::Array{T,2}, m::Int) = Array(T, m) similar{T}(a::Array{T,2}, S) = Array(S, size(a,1), size(a,2)) # T[x...] constructs Array{T,1} function getindex(T::NonTupleType, vals...) a = Array(T,length(vals)) for i = 1:length(vals) a[i] = vals[i] end return a end getindex(T::(Type...)) = Array(T,0) # T[a:b] and T[a:s:b] also contruct typed ranges function getindex{T<:Number}(::Type{T}, r::Range) copy!(Array(T,length(r)), r) end function getindex{T<:Number}(::Type{T}, r1::Range, rs::Range...) a = Array(T,length(r1)+sum(length,rs)) o = 1 copy!(a, o, r1) o += length(r1) for r in rs copy!(a, o, r) o += length(r) end return a end function fill!{T<:Union(Int8,Uint8)}(a::Array{T}, x::Integer) ccall(:memset, Ptr{Void}, (Ptr{Void}, Int32, Csize_t), a, x, length(a)) return a end function fill!{T<:Union(Integer,FloatingPoint)}(a::Array{T}, x) # note: preserve -0.0 for floats if isbits(T) && T<:Integer && convert(T,x) == 0 ccall(:memset, Ptr{Void}, (Ptr{Void}, Int32, Csize_t), a,0,length(a)*sizeof(T)) else for i = 1:length(a) @inbounds a[i] = x end end return a end fill(v, dims::Dims) = fill!(Array(typeof(v), dims), v) fill(v, dims::Integer...) = fill!(Array(typeof(v), dims...), v) cell(dims::Integer...) = Array(Any, dims...) cell(dims::(Integer...)) = Array(Any, convert((Int...), dims)) for (fname, felt) in ((:zeros,:zero), (:ones,:one)) @eval begin ($fname)(T::Type, dims...) = fill!(Array(T, dims...), ($felt)(T)) ($fname)(dims...) = fill!(Array(Float64, dims...), ($felt)(Float64)) ($fname){T}(A::AbstractArray{T}) = fill!(similar(A), ($felt)(T)) end end function eye(T::Type, m::Integer, n::Integer) a = zeros(T,m,n) for i = 1:min(m,n) a[i,i] = one(T) end return a end eye(m::Integer, n::Integer) = eye(Float64, m, n) eye(T::Type, n::Integer) = eye(T, n, n) eye(n::Integer) = eye(Float64, n) eye{T}(x::AbstractMatrix{T}) = eye(T, size(x, 1), size(x, 2)) function one{T}(x::AbstractMatrix{T}) m,n = size(x) m==n || throw(DimensionMismatch("multiplicative identity defined only for square matrices")) eye(T, m) end linspace(start::Integer, stop::Integer, n::Integer) = linspace(float(start), float(stop), n) function linspace(start::Real, stop::Real, n::Integer) (start, stop) = promote(start, stop) T = typeof(start) a = Array(T, int(n)) if n == 1 a[1] = start return a end n -= 1 S = promote_type(T, Float64) for i=0:n a[i+1] = start*(convert(S, (n-i))/n) + stop*(convert(S, i)/n) end a end linspace(start::Real, stop::Real) = linspace(start, stop, 100) logspace(start::Real, stop::Real, n::Integer) = 10.^linspace(start, stop, n) logspace(start::Real, stop::Real) = logspace(start, stop, 50) ## Conversions ## convert{T,n}(::Type{Array{T}}, x::Array{T,n}) = x convert{T,n}(::Type{Array{T,n}}, x::Array{T,n}) = x convert{T,n,S}(::Type{Array{T}}, x::Array{S,n}) = convert(Array{T,n}, x) convert{T,n,S}(::Type{Array{T,n}}, x::Array{S,n}) = copy!(similar(x,T), x) function collect(T::Type, itr) if applicable(length, itr) # when length() isn't defined this branch might pollute the # type of the other. a = Array(T,length(itr)::Integer) i = 0 for x in itr a[i+=1] = x end else a = Array(T,0) for x in itr push!(a,x) end end return a end collect(itr) = collect(eltype(itr), itr) ## Indexing: getindex ## getindex(a::Array) = arrayref(a,1) getindex(A::Array, i0::Real) = arrayref(A,to_index(i0)) getindex(A::Array, i0::Real, i1::Real) = arrayref(A,to_index(i0),to_index(i1)) getindex(A::Array, i0::Real, i1::Real, i2::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4),to_index(i5)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real, I::Real...) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4),to_index(i5),to_index(I)...) # Fast copy using copy! for UnitRange function getindex(A::Array, I::UnitRange{Int}) lI = length(I) X = similar(A, lI) if lI > 0 copy!(X, 1, A, first(I), lI) end return X end function getindex{T<:Real}(A::Array, I::AbstractVector{T}) return [ A[i] for i in to_index(I) ] end function getindex{T<:Real}(A::Range, I::AbstractVector{T}) return [ A[i] for i in to_index(I) ] end function getindex(A::Range, I::AbstractVector{Bool}) checkbounds(A, I) return [ A[i] for i in to_index(I) ] end # logical indexing function getindex_bool_1d(A::Array, I::AbstractArray{Bool}) checkbounds(A, I) n = sum(I) out = similar(A, n) c = 1 for i = 1:length(I) if I[i] out[c] = A[i] c += 1 end end out end getindex(A::Vector, I::AbstractVector{Bool}) = getindex_bool_1d(A, I) getindex(A::Vector, I::AbstractArray{Bool}) = getindex_bool_1d(A, I) getindex(A::Array, I::AbstractVector{Bool}) = getindex_bool_1d(A, I) getindex(A::Array, I::AbstractArray{Bool}) = getindex_bool_1d(A, I) ## Indexing: setindex! ## setindex!{T}(A::Array{T}, x) = arrayset(A, convert(T,x), 1) setindex!{T}(A::Array{T}, x, i0::Real) = arrayset(A, convert(T,x), to_index(i0)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4), to_index(i5)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real, I::Real...) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4), to_index(i5), to_index(I)...) function setindex!{T<:Real}(A::Array, x, I::AbstractVector{T}) for i in I A[i] = x end return A end function setindex!{T}(A::Array{T}, X::Array{T}, I::UnitRange{Int}) if length(X) != length(I) throw_setindex_mismatch(X, (I,)) end copy!(A, first(I), X, 1, length(I)) return A end function setindex!{T<:Real}(A::Array, X::AbstractArray, I::AbstractVector{T}) if length(X) != length(I) throw_setindex_mismatch(X, (I,)) end count = 1 if is(X,A) X = copy(X) end for i in I A[i] = X[count] count += 1 end return A end # logical indexing function assign_bool_scalar_1d!(A::Array, x, I::AbstractArray{Bool}) checkbounds(A, I) for i = 1:length(I) if I[i] A[i] = x end end A end function assign_bool_vector_1d!(A::Array, X::AbstractArray, I::AbstractArray{Bool}) checkbounds(A, I) c = 1 for i = 1:length(I) if I[i] A[i] = X[c] c += 1 end end if length(X) != c-1 throw(DimensionMismatch("assigned $(length(X)) elements to length $(c-1) destination")) end A end setindex!(A::Array, X::AbstractArray, I::AbstractVector{Bool}) = assign_bool_vector_1d!(A, X, I) setindex!(A::Array, X::AbstractArray, I::AbstractArray{Bool}) = assign_bool_vector_1d!(A, X, I) setindex!(A::Array, x, I::AbstractVector{Bool}) = assign_bool_scalar_1d!(A, x, I) setindex!(A::Array, x, I::AbstractArray{Bool}) = assign_bool_scalar_1d!(A, x, I) # efficiently grow an array function _growat!(a::Vector, i::Integer, delta::Integer) n = length(a) if i < div(n,2) _growat_beg!(a, i, delta) else _growat_end!(a, i, delta) end return a end function _growat_beg!(a::Vector, i::Integer, delta::Integer) ccall(:jl_array_grow_beg, Void, (Any, Uint), a, delta) if i > 1 ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, 1), pointer(a, 1+delta), (i-1)*elsize(a)) end return a end function _growat_end!(a::Vector, i::Integer, delta::Integer) ccall(:jl_array_grow_end, Void, (Any, Uint), a, delta) n = length(a) if n >= i+delta ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, i+delta), pointer(a, i), (n-i-delta+1)*elsize(a)) end return a end # efficiently delete part of an array function _deleteat!(a::Vector, i::Integer, delta::Integer) n = length(a) last = i+delta-1 if i-1 < n-last _deleteat_beg!(a, i, delta) else _deleteat_end!(a, i, delta) end return a end function _deleteat_beg!(a::Vector, i::Integer, delta::Integer) if i > 1 ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, 1+delta), pointer(a, 1), (i-1)*elsize(a)) end ccall(:jl_array_del_beg, Void, (Any, Uint), a, delta) return a end function _deleteat_end!(a::Vector, i::Integer, delta::Integer) n = length(a) if n >= i+delta ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, i), pointer(a, i+delta), (n-i-delta+1)*elsize(a)) end ccall(:jl_array_del_end, Void, (Any, Uint), a, delta) return a end ## Dequeue functionality ## const _grow_none_errmsg = "[] cannot grow. Instead, initialize the array with \"T[]\", where T is the desired element type." function push!{T}(a::Array{T,1}, item) if is(T,None) error(_grow_none_errmsg) end # convert first so we don't grow the array if the assignment won't work item = convert(T, item) ccall(:jl_array_grow_end, Void, (Any, Uint), a, 1) a[end] = item return a end function push!(a::Array{Any,1}, item::ANY) ccall(:jl_array_grow_end, Void, (Any, Uint), a, 1) arrayset(a, item, length(a)) return a end function append!{T}(a::Array{T,1}, items::AbstractVector) if is(T,None) error(_grow_none_errmsg) end n = length(items) ccall(:jl_array_grow_end, Void, (Any, Uint), a, n) copy!(a, length(a)-n+1, items, 1, n) return a end function prepend!{T}(a::Array{T,1}, items::AbstractVector) if is(T,None) error(_grow_none_errmsg) end n = length(items) ccall(:jl_array_grow_beg, Void, (Any, Uint), a, n) if a === items copy!(a, 1, items, n+1, n) else copy!(a, 1, items, 1, n) end return a end function resize!(a::Vector, nl::Integer) l = length(a) if nl > l ccall(:jl_array_grow_end, Void, (Any, Uint), a, nl-l) else if nl < 0 throw(BoundsError()) end ccall(:jl_array_del_end, Void, (Any, Uint), a, l-nl) end return a end function sizehint(a::Vector, sz::Integer) ccall(:jl_array_sizehint, Void, (Any, Uint), a, sz) a end function pop!(a::Vector) if isempty(a) error("array must be non-empty") end item = a[end] ccall(:jl_array_del_end, Void, (Any, Uint), a, 1) return item end function unshift!{T}(a::Array{T,1}, item) if is(T,None) error(_grow_none_errmsg) end item = convert(T, item) ccall(:jl_array_grow_beg, Void, (Any, Uint), a, 1) a[1] = item return a end function shift!(a::Vector) if isempty(a) error("array must be non-empty") end item = a[1] ccall(:jl_array_del_beg, Void, (Any, Uint), a, 1) return item end function insert!{T}(a::Array{T,1}, i::Integer, item) 1 <= i <= length(a)+1 || throw(BoundsError()) i == length(a)+1 && return push!(a, item) item = convert(T, item) _growat!(a, i, 1) a[i] = item return a end function deleteat!(a::Vector, i::Integer) if !(1 <= i <= length(a)) throw(BoundsError()) end return _deleteat!(a, i, 1) end function deleteat!{T<:Integer}(a::Vector, r::UnitRange{T}) n = length(a) f = first(r) l = last(r) if !(1 <= f && l <= n) throw(BoundsError()) end return _deleteat!(a, f, length(r)) end function deleteat!(a::Vector, inds) n = length(a) s = start(inds) done(inds, s) && return a (p, s) = next(inds, s) q = p+1 while !done(inds, s) (i,s) = next(inds, s) if !(q <= i <= n) i < q && error("indices must be unique and sorted") throw(BoundsError()) end while q < i @inbounds a[p] = a[q] p += 1; q += 1 end q = i+1 end while q <= n @inbounds a[p] = a[q] p += 1; q += 1 end ccall(:jl_array_del_end, Void, (Any, Uint), a, n-p+1) return a end const _default_splice = [] function splice!(a::Vector, i::Integer, ins::AbstractArray=_default_splice) v = a[i] m = length(ins) if m == 0 _deleteat!(a, i, 1) elseif m == 1 a[i] = ins[1] else _growat!(a, i, m-1) for k = 1:m a[i+k-1] = ins[k] end end return v end function splice!{T<:Integer}(a::Vector, r::UnitRange{T}, ins::AbstractArray=_default_splice) v = a[r] m = length(ins) if m == 0 deleteat!(a, r) return v end n = length(a) f = first(r) l = last(r) d = length(r) if m < d delta = d - m if f-1 < n-l _deleteat_beg!(a, f, delta) else _deleteat_end!(a, l-delta+1, delta) end elseif m > d delta = m - d if f-1 < n-l _growat_beg!(a, f, delta) else _growat_end!(a, l+1, delta) end end for k = 1:m a[f+k-1] = ins[k] end return v end function empty!(a::Vector) ccall(:jl_array_del_end, Void, (Any, Uint), a, length(a)) return a end ## Unary operators ## function conj!{T<:Number}(A::AbstractArray{T}) for i=1:length(A) A[i] = conj(A[i]) end return A end for f in (:-, :~, :conj, :sign) @eval begin function ($f)(A::StridedArray) F = similar(A) for i=1:length(A) F[i] = ($f)(A[i]) end return F end end end (-)(A::StridedArray{Bool}) = reshape([ -A[i] for i=1:length(A) ], size(A)) real(A::StridedArray) = reshape([ real(x) for x in A ], size(A)) imag(A::StridedArray) = reshape([ imag(x) for x in A ], size(A)) real{T<:Real}(x::StridedArray{T}) = x imag{T<:Real}(x::StridedArray{T}) = zero(x) function !(A::StridedArray{Bool}) F = similar(A) for i=1:length(A) F[i] = !A[i] end return F end ## Binary arithmetic operators ## promote_array_type{Scalar, Arry}(::Type{Scalar}, ::Type{Arry}) = promote_type(Scalar, Arry) promote_array_type{S<:Real, A<:FloatingPoint}(::Type{S}, ::Type{A}) = A promote_array_type{S<:Union(Complex, Real), AT<:FloatingPoint}(::Type{S}, ::Type{Complex{AT}}) = Complex{AT} promote_array_type{S<:Integer, A<:Integer}(::Type{S}, ::Type{A}) = A promote_array_type{S<:Integer}(::Type{S}, ::Type{Bool}) = S ./{T<:Integer}(x::Integer, y::StridedArray{T}) = reshape([ x ./ y[i] for i=1:length(y) ], size(y)) ./{T<:Integer}(x::StridedArray{T}, y::Integer) = reshape([ x[i] ./ y for i=1:length(x) ], size(x)) ./{T<:Integer}(x::Integer, y::StridedArray{Complex{T}}) = reshape([ x ./ y[i] for i=1:length(y) ], size(y)) ./{T<:Integer}(x::StridedArray{Complex{T}}, y::Integer) = reshape([ x[i] ./ y for i=1:length(x) ], size(x)) ./{S<:Integer,T<:Integer}(x::Complex{S}, y::StridedArray{T}) = reshape([ x ./ y[i] for i=1:length(y) ], size(y)) ./{S<:Integer,T<:Integer}(x::StridedArray{S}, y::Complex{T}) = reshape([ x[i] ./ y for i=1:length(x) ], size(x)) # ^ is difficult, since negative exponents give a different type .^(x::Number, y::StridedArray) = reshape([ x ^ y[i] for i=1:length(y) ], size(y)) .^(x::StridedArray, y::Number ) = reshape([ x[i] ^ y for i=1:length(x) ], size(x)) for f in (:+, :-, :div, :mod, :&, :|, :$) @eval begin function ($f){S,T}(A::StridedArray{S}, B::StridedArray{T}) F = similar(A, promote_type(S,T), promote_shape(size(A),size(B))) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B[i]) end return F end # interaction with Ranges function ($f){S,T<:Real}(A::StridedArray{S}, B::Range{T}) F = similar(A, promote_type(S,T), promote_shape(size(A),size(B))) i = 1 for b in B @inbounds F[i] = ($f)(A[i], b) i += 1 end return F end function ($f){S<:Real,T}(A::Range{S}, B::StridedArray{T}) F = similar(B, promote_type(S,T), promote_shape(size(A),size(B))) i = 1 for a in A @inbounds F[i] = ($f)(a, B[i]) i += 1 end return F end end end for f in (:.+, :.-, :.*, :./, :.\, :.%, :div, :mod, :rem, :&, :|, :$) @eval begin function ($f){T}(A::Number, B::StridedArray{T}) F = similar(B, promote_array_type(typeof(A),T)) for i=1:length(B) @inbounds F[i] = ($f)(A, B[i]) end return F end function ($f){T}(A::StridedArray{T}, B::Number) F = similar(A, promote_array_type(typeof(B),T)) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B) end return F end end end # familiar aliases for broadcasting operations of array ± scalar (#7226): (+)(A::AbstractArray{Bool},x::Bool) = A .+ x (+)(x::Bool,A::AbstractArray{Bool}) = x .+ A (-)(A::AbstractArray{Bool},x::Bool) = A .- x (-)(x::Bool,A::AbstractArray{Bool}) = x .- A (+)(A::AbstractArray,x::Number) = A .+ x (+)(x::Number,A::AbstractArray) = x .+ A (-)(A::AbstractArray,x::Number) = A .- x (-)(x::Number,A::AbstractArray) = x .- A # functions that should give an Int result for Bool arrays for f in (:.+, :.-) @eval begin function ($f)(A::Bool, B::StridedArray{Bool}) F = similar(B, Int, size(B)) for i=1:length(B) @inbounds F[i] = ($f)(A, B[i]) end return F end function ($f)(A::StridedArray{Bool}, B::Bool) F = similar(A, Int, size(A)) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B) end return F end end end for f in (:+, :-) @eval begin function ($f)(A::StridedArray{Bool}, B::StridedArray{Bool}) F = similar(A, Int, promote_shape(size(A), size(B))) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B[i]) end return F end end end ## promotion to complex ## function complex{S<:Real,T<:Real}(A::Array{S}, B::Array{T}) if size(A) != size(B); throw(DimensionMismatch("")); end F = similar(A, typeof(complex(zero(S),zero(T)))) for i=1:length(A) @inbounds F[i] = complex(A[i], B[i]) end return F end function complex{T<:Real}(A::Real, B::Array{T}) F = similar(B, typeof(complex(A,zero(T)))) for i=1:length(B) @inbounds F[i] = complex(A, B[i]) end return F end function complex{T<:Real}(A::Array{T}, B::Real) F = similar(A, typeof(complex(zero(T),B))) for i=1:length(A) @inbounds F[i] = complex(A[i], B) end return F end # use memcmp for lexcmp on byte arrays function lexcmp(a::Array{Uint8,1}, b::Array{Uint8,1}) c = ccall(:memcmp, Int32, (Ptr{Uint8}, Ptr{Uint8}, Uint), a, b, min(length(a),length(b))) c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b)) end ## data movement ## function slicedim(A::Array, d::Integer, i::Integer) d_in = size(A) leading = d_in[1:(d-1)] d_out = tuple(leading..., 1, d_in[(d+1):end]...) M = prod(leading) N = length(A) stride = M * d_in[d] B = similar(A, d_out) index_offset = 1 + (i-1)*M l = 1 if M==1 for j=0:stride:(N-stride) B[l] = A[j + index_offset] l += 1 end else for j=0:stride:(N-stride) offs = j + index_offset for k=0:(M-1) B[l] = A[offs + k] l += 1 end end end return B end function flipdim{T}(A::Array{T}, d::Integer) nd = ndims(A) sd = d > nd ? 1 : size(A, d) if sd == 1 || isempty(A) return copy(A) end B = similar(A) nnd = 0 for i = 1:nd nnd += int(size(A,i)==1 || i==d) end if nnd==nd # flip along the only non-singleton dimension for i = 1:sd B[i] = A[sd+1-i] end return B end d_in = size(A) leading = d_in[1:(d-1)] M = prod(leading) N = length(A) stride = M * sd if M==1 for j = 0:stride:(N-stride) for i = 1:sd ri = sd+1-i B[j + ri] = A[j + i] end end else if isbits(T) && M>200 for i = 1:sd ri = sd+1-i for j=0:stride:(N-stride) offs = j + 1 + (i-1)*M boffs = j + 1 + (ri-1)*M copy!(B, boffs, A, offs, M) end end else for i = 1:sd ri = sd+1-i for j=0:stride:(N-stride) offs = j + 1 + (i-1)*M boffs = j + 1 + (ri-1)*M for k=0:(M-1) B[boffs + k] = A[offs + k] end end end end end return B end function rotl90(A::StridedMatrix) m,n = size(A) B = similar(A,(n,m)) for i=1:m, j=1:n B[n-j+1,i] = A[i,j] end return B end function rotr90(A::StridedMatrix) m,n = size(A) B = similar(A,(n,m)) for i=1:m, j=1:n B[j,m-i+1] = A[i,j] end return B end function rot180(A::StridedMatrix) m,n = size(A) B = similar(A) for i=1:m, j=1:n B[m-i+1,n-j+1] = A[i,j] end return B end function rotl90(A::AbstractMatrix, k::Integer) k = mod(k, 4) k == 1 ? rotl90(A) : k == 2 ? rot180(A) : k == 3 ? rotr90(A) : copy(A) end rotr90(A::AbstractMatrix, k::Integer) = rotl90(A,-k) rot180(A::AbstractMatrix, k::Integer) = mod(k, 2) == 1 ? rot180(A) : copy(A) # note: probably should be StridedVector or AbstractVector function reverse(A::AbstractVector, s=1, n=length(A)) B = similar(A) for i = 1:s-1 B[i] = A[i] end for i = s:n B[i] = A[n+s-i] end for i = n+1:length(A) B[i] = A[i] end B end reverse(v::StridedVector) = (n=length(v); [ v[n-i+1] for i=1:n ]) reverse(v::StridedVector, s, n=length(v)) = reverse!(copy(v), s, n) function reverse!(v::StridedVector, s=1, n=length(v)) r = n for i=s:div(s+n-1,2) v[i], v[r] = v[r], v[i] r -= 1 end v end function vcat{T}(arrays::Array{T,1}...) n = 0 for a in arrays n += length(a) end arr = Array(T, n) ptr = pointer(arr) offset = 0 if isbits(T) elsz = sizeof(T) else elsz = div(WORD_SIZE,8) end for a in arrays nba = length(a)*elsz ccall(:memcpy, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Uint), ptr+offset, a, nba) offset += nba end return arr end ## find ## # returns the index of the next non-zero element, or 0 if all zeros function findnext(A, start::Integer) for i = start:length(A) if A[i] != 0 return i end end return 0 end findfirst(A) = findnext(A,1) # returns the index of the next matching element function findnext(A, v, start::Integer) for i = start:length(A) if A[i] == v return i end end return 0 end findfirst(A,v) = findnext(A,v,1) # returns the index of the next element for which the function returns true function findnext(testf::Function, A, start::Integer) for i = start:length(A) if testf(A[i]) return i end end return 0 end findfirst(testf::Function, A) = findnext(testf, A, 1) function find(testf::Function, A::StridedArray) # use a dynamic-length array to store the indexes, then copy to a non-padded # array for the return tmpI = Array(Int, 0) for i = 1:length(A) if testf(A[i]) push!(tmpI, i) end end I = similar(A, Int, length(tmpI)) copy!(I, tmpI) I end function find(A::StridedArray) nnzA = countnz(A) I = similar(A, Int, nnzA) count = 1 for i=1:length(A) if A[i] != 0 I[count] = i count += 1 end end return I end find(x::Number) = x == 0 ? Array(Int,0) : [1] find(testf::Function, x) = find(testf(x)) findn(A::AbstractVector) = find(A) function findn(A::StridedMatrix) nnzA = countnz(A) I = similar(A, Int, nnzA) J = similar(A, Int, nnzA) count = 1 for j=1:size(A,2), i=1:size(A,1) if A[i,j] != 0 I[count] = i J[count] = j count += 1 end end return (I, J) end function findnz{T}(A::StridedMatrix{T}) nnzA = countnz(A) I = zeros(Int, nnzA) J = zeros(Int, nnzA) NZs = zeros(T, nnzA) count = 1 if nnzA > 0 for j=1:size(A,2), i=1:size(A,1) Aij = A[i,j] if Aij != 0 I[count] = i J[count] = j NZs[count] = Aij count += 1 end end end return (I, J, NZs) end function findmax(a) if isempty(a) error("array must be non-empty") end m = a[1] mi = 1 for i=2:length(a) ai = a[i] if ai > m || m!=m m = ai mi = i end end return (m, mi) end function findmin(a) if isempty(a) error("array must be non-empty") end m = a[1] mi = 1 for i=2:length(a) ai = a[i] if ai < m || m!=m m = ai mi = i end end return (m, mi) end indmax(a) = findmax(a)[2] indmin(a) = findmin(a)[2] # similar to Matlab's ismember # returns a vector containing the highest index in b for each value in a that is a member of b function indexin(a::AbstractArray, b::AbstractArray) bdict = Dict(b, 1:length(b)) [get(bdict, i, 0) for i in a] end # findin (the index of intersection) function findin(a, b::UnitRange) ind = Array(Int, 0) f = first(b) l = last(b) for i = 1:length(a) if f <= a[i] <= l push!(ind, i) end end ind end function findin(a, b) ind = Array(Int, 0) bset = union!(Set(), b) for i = 1:length(a) if in(a[i], bset) push!(ind, i) end end ind end # Copying subregions function indcopy(sz::Dims, I::Vector) n = length(I) s = sz[n] for i = n+1:length(sz) s *= sz[i] end dst = eltype(I)[findin(I[i], i < n ? (1:sz[i]) : (1:s)) for i = 1:n] src = eltype(I)[I[i][findin(I[i], i < n ? (1:sz[i]) : (1:s))] for i = 1:n] dst, src end function indcopy(sz::Dims, I::(RangeIndex...)) n = length(I) s = sz[n] for i = n+1:length(sz) s *= sz[i] end dst::typeof(I) = ntuple(n, i-> findin(I[i], i < n ? (1:sz[i]) : (1:s)))::typeof(I) src::typeof(I) = ntuple(n, i-> I[i][findin(I[i], i < n ? (1:sz[i]) : (1:s))])::typeof(I) dst, src end ## Filter ## # given a function returning a boolean and an array, return matching elements filter(f::Function, As::AbstractArray) = As[map(f, As)::AbstractArray{Bool}] function filter!(f::Function, a::Vector) insrt = 1 for curr = 1:length(a) if f(a[curr]) a[insrt] = a[curr] insrt += 1 end end deleteat!(a, insrt:length(a)) return a end function filter(f::Function, a::Vector) r = Array(eltype(a), 0) for i = 1:length(a) if f(a[i]) push!(r, a[i]) end end return r end ## Transpose ## const transposebaselength=64 function transpose!(B::StridedMatrix,A::StridedMatrix) m, n = size(A) size(B) == (n,m) || throw(DimensionMismatch("transpose")) if m*n<=4*transposebaselength @inbounds begin for j = 1:n for i = 1:m B[j,i] = transpose(A[i,j]) end end end else transposeblock!(B,A,m,n,0,0) end return B end function transposeblock!(B::StridedMatrix,A::StridedMatrix,m::Int,n::Int,offseti::Int,offsetj::Int) if m*n<=transposebaselength @inbounds begin for j = offsetj+(1:n) for i = offseti+(1:m) B[j,i] = transpose(A[i,j]) end end end elseif m>n newm=m>>1 transposeblock!(B,A,newm,n,offseti,offsetj) transposeblock!(B,A,m-newm,n,offseti+newm,offsetj) else newn=n>>1 transposeblock!(B,A,m,newn,offseti,offsetj) transposeblock!(B,A,m,n-newn,offseti,offsetj+newn) end return B end function ctranspose!(B::StridedMatrix,A::StridedMatrix) m, n = size(A) size(B) == (n,m) || throw(DimensionMismatch("transpose")) if m*n<=4*transposebaselength @inbounds begin for j = 1:n for i = 1:m B[j,i] = ctranspose(A[i,j]) end end end else ctransposeblock!(B,A,m,n,0,0) end return B end function ctransposeblock!(B::StridedMatrix,A::StridedMatrix,m::Int,n::Int,offseti::Int,offsetj::Int) if m*n<=transposebaselength @inbounds begin for j = offsetj+(1:n) for i = offseti+(1:m) B[j,i] = ctranspose(A[i,j]) end end end elseif m>n newm=m>>1 ctransposeblock!(B,A,newm,n,offseti,offsetj) ctransposeblock!(B,A,m-newm,n,offseti+newm,offsetj) else newn=n>>1 ctransposeblock!(B,A,m,newn,offseti,offsetj) ctransposeblock!(B,A,m,n-newn,offseti,offsetj+newn) end return B end function transpose(A::StridedMatrix) B = similar(A, size(A, 2), size(A, 1)) transpose!(B, A) end function ctranspose(A::StridedMatrix) B = similar(A, size(A, 2), size(A, 1)) ctranspose!(B, A) end ctranspose{T<:Real}(A::StridedVecOrMat{T}) = transpose(A) transpose(x::StridedVector) = [ transpose(x[j]) for i=1, j=1:size(x,1) ] ctranspose{T}(x::StridedVector{T}) = T[ ctranspose(x[j]) for i=1, j=1:size(x,1) ] # set-like operators for vectors # These are moderately efficient, preserve order, and remove dupes. function intersect(v1, vs...) ret = Array(eltype(v1),0) for v_elem in v1 inall = true for i = 1:length(vs) if !in(v_elem, vs[i]) inall=false; break end end if inall push!(ret, v_elem) end end ret end function union(vs...) ret = Array(promote_eltype(vs...),0) seen = Set() for v in vs for v_elem in v if !in(v_elem, seen) push!(ret, v_elem) push!(seen, v_elem) end end end ret end # setdiff only accepts two args function setdiff(a, b) args_type = promote_type(eltype(a), eltype(b)) bset = Set(b) ret = Array(args_type,0) seen = Set() for a_elem in a if !in(a_elem, seen) && !in(a_elem, bset) push!(ret, a_elem) push!(seen, a_elem) end end ret end # symdiff is associative, so a relatively clean # way to implement this is by using setdiff and union, and # recursing. Has the advantage of keeping order, too, but # not as fast as other methods that make a single pass and # store counts with a Dict. symdiff(a) = a symdiff(a, b) = union(setdiff(a,b), setdiff(b,a)) symdiff(a, b, rest...) = symdiff(a, symdiff(b, rest...)) _cumsum_type{T<:Number}(v::AbstractArray{T}) = typeof(+zero(T)) _cumsum_type(v) = typeof(v[1]+v[1]) for (f, fp, op) = ((:cumsum, :cumsum_pairwise, :+), (:cumprod, :cumprod_pairwise, :*) ) # in-place cumsum of c = s+v(i1:n), using pairwise summation as for sum @eval function ($fp)(v::AbstractVector, c::AbstractVector, s, i1, n) if n < 128 @inbounds c[i1] = ($op)(s, v[i1]) for i = i1+1:i1+n-1 @inbounds c[i] = $(op)(c[i-1], v[i]) end else n2 = div(n,2) ($fp)(v, c, s, i1, n2) ($fp)(v, c, c[(i1+n2)-1], i1+n2, n-n2) end end @eval function ($f)(v::AbstractVector) n = length(v) c = $(op===:+ ? (:(similar(v,_cumsum_type(v)))) : (:(similar(v)))) if n == 0; return c; end ($fp)(v, c, $(op==:+ ? :(zero(v[1])) : :(one(v[1]))), 1, n) return c end @eval ($f)(A::AbstractArray) = ($f)(A, 1) end for (f, op) = ((:cummin, :min), (:cummax, :max)) @eval function ($f)(v::AbstractVector) n = length(v) cur_val = v[1] res = similar(v, n) res[1] = cur_val for i in 2:n cur_val = ($op)(v[i], cur_val) res[i] = cur_val end return res end @eval function ($f)(A::StridedArray, axis::Integer) dimsA = size(A) ndimsA = ndims(A) axis_size = dimsA[axis] axis_stride = 1 for i = 1:(axis-1) axis_stride *= size(A,i) end if axis_size < 1 return A end B = similar(A) for i = 1:length(A) if div(i-1, axis_stride) % axis_size == 0 B[i] = A[i] else B[i] = ($op)(A[i], B[i-axis_stride]) end end return B end @eval ($f)(A::AbstractArray) = ($f)(A, 1) end
Java
/* * 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.logging.log4j.core.appender; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class SocketAppenderBuilderTest { /** * Tests https://issues.apache.org/jira/browse/LOG4J2-1620 */ @Test public void testDefaultImmediateFlush() { assertTrue(SocketAppender.newBuilder().isImmediateFlush(), "Regression of LOG4J2-1620: default value for immediateFlush should be true"); } }
Java
/* * 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.ignite.marshaller.jdk; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.util.io.GridByteArrayInputStream; import org.apache.ignite.internal.util.io.GridByteArrayOutputStream; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller; import org.jetbrains.annotations.Nullable; /** * Implementation of {@link org.apache.ignite.marshaller.Marshaller} based on JDK serialization mechanism. * <p> * <h1 class="header">Configuration</h1> * <h2 class="header">Mandatory</h2> * This marshaller has no mandatory configuration parameters. * <h2 class="header">Java Example</h2> * {@code JdkMarshaller} needs to be explicitly configured to override default {@link org.apache.ignite.marshaller.optimized.OptimizedMarshaller}. * <pre name="code" class="java"> * JdkMarshaller marshaller = new JdkMarshaller(); * * IgniteConfiguration cfg = new IgniteConfiguration(); * * // Override default marshaller. * cfg.setMarshaller(marshaller); * * // Starts grid. * G.start(cfg); * </pre> * <h2 class="header">Spring Example</h2> * JdkMarshaller can be configured from Spring XML configuration file: * <pre name="code" class="xml"> * &lt;bean id="grid.custom.cfg" class="org.apache.ignite.configuration.IgniteConfiguration" singleton="true"&gt; * ... * &lt;property name="marshaller"&gt; * &lt;bean class="org.apache.ignite.marshaller.jdk.JdkMarshaller"/&gt; * &lt;/property&gt; * ... * &lt;/bean&gt; * </pre> * <p> * <img src="http://ignite.apache.org/images/spring-small.png"> * <br> * For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a> */ public class JdkMarshaller extends AbstractNodeNameAwareMarshaller { /** {@inheritDoc} */ @Override protected void marshal0(@Nullable Object obj, OutputStream out) throws IgniteCheckedException { assert out != null; ObjectOutputStream objOut = null; try { objOut = new JdkMarshallerObjectOutputStream(new JdkMarshallerOutputStreamWrapper(out)); // Make sure that we serialize only task, without class loader. objOut.writeObject(obj); objOut.flush(); } catch (Exception e) { throw new IgniteCheckedException("Failed to serialize object: " + obj, e); } finally{ U.closeQuiet(objOut); } } /** {@inheritDoc} */ @Override protected byte[] marshal0(@Nullable Object obj) throws IgniteCheckedException { GridByteArrayOutputStream out = null; try { out = new GridByteArrayOutputStream(DFLT_BUFFER_SIZE); marshal(obj, out); return out.toByteArray(); } finally { U.close(out, null); } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Override protected <T> T unmarshal0(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException { assert in != null; if (clsLdr == null) clsLdr = getClass().getClassLoader(); ObjectInputStream objIn = null; try { objIn = new JdkMarshallerObjectInputStream(new JdkMarshallerInputStreamWrapper(in), clsLdr); return (T)objIn.readObject(); } catch (ClassNotFoundException e) { throw new IgniteCheckedException("Failed to find class with given class loader for unmarshalling " + "(make sure same versions of all classes are available on all nodes or enable peer-class-loading): " + clsLdr, e); } catch (Exception e) { throw new IgniteCheckedException("Failed to deserialize object with given class loader: " + clsLdr, e); } finally{ U.closeQuiet(objIn); } } /** {@inheritDoc} */ @Override protected <T> T unmarshal0(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException { GridByteArrayInputStream in = null; try { in = new GridByteArrayInputStream(arr, 0, arr.length); return unmarshal(in, clsLdr); } finally { U.close(in, null); } } /** {@inheritDoc} */ @Override public void onUndeploy(ClassLoader ldr) { // No-op. } /** {@inheritDoc} */ @Override public String toString() { return S.toString(JdkMarshaller.class, this); } }
Java
""" Tests for login and logout. """ import datetime from unittest.mock import patch import responses import quilt3 from .utils import QuiltTestCase class TestSession(QuiltTestCase): @patch('quilt3.session.open_url') @patch('quilt3.session.input', return_value='123456') @patch('quilt3.session.login_with_token') def test_login(self, mock_login_with_token, mock_input, mock_open_url): quilt3.login() url = quilt3.session.get_registry_url() mock_open_url.assert_called_with(f'{url}/login') mock_login_with_token.assert_called_with('123456') @patch('quilt3.session._save_auth') @patch('quilt3.session._save_credentials') def test_login_with_token(self, mock_save_credentials, mock_save_auth): url = quilt3.session.get_registry_url() mock_auth = dict( refresh_token='refresh-token', access_token='access-token', expires_at=123456789 ) self.requests_mock.add( responses.POST, f'{url}/api/token', json=mock_auth, status=200 ) self.requests_mock.add( responses.GET, f'{url}/api/auth/get_credentials', json=dict( AccessKeyId='access-key', SecretAccessKey='secret-key', SessionToken='session-token', Expiration="2019-05-28T23:58:07+00:00" ), status=200 ) quilt3.session.login_with_token('123456') mock_save_auth.assert_called_with({url: mock_auth}) mock_save_credentials.assert_called_with(dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time="2019-05-28T23:58:07+00:00" )) @patch('quilt3.session._save_credentials') @patch('quilt3.session._load_credentials') def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials): def format_date(date): return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat() # Test good credentials. future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1) mock_load_credentials.return_value = dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time=format_date(future_date) ) session = quilt3.session.create_botocore_session() credentials = session.get_credentials() assert credentials.access_key == 'access-key' assert credentials.secret_key == 'secret-key' assert credentials.token == 'session-token' mock_save_credentials.assert_not_called() # Test expired credentials. past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5) mock_load_credentials.return_value = dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time=format_date(past_date) ) url = quilt3.session.get_registry_url() self.requests_mock.add( responses.GET, f'{url}/api/auth/get_credentials', json=dict( AccessKeyId='access-key2', SecretAccessKey='secret-key2', SessionToken='session-token2', Expiration=format_date(future_date) ), status=200 ) session = quilt3.session.create_botocore_session() credentials = session.get_credentials() assert credentials.access_key == 'access-key2' assert credentials.secret_key == 'secret-key2' assert credentials.token == 'session-token2' mock_save_credentials.assert_called() def test_logged_in(self): registry_url = quilt3.session.get_registry_url() other_registry_url = registry_url + 'other' mock_auth = dict( refresh_token='refresh-token', access_token='access-token', expires_at=123456789, ) with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth: assert quilt3.logged_in() == 'https://example.com' mocked_load_auth.assert_called_once() with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth: assert quilt3.logged_in() is None mocked_load_auth.assert_called_once()
Java
package io.cattle.platform.configitem.server.model.impl; import java.io.IOException; import io.cattle.platform.configitem.server.model.RefreshableConfigItem; import io.cattle.platform.configitem.server.resource.ResourceRoot; import io.cattle.platform.configitem.version.ConfigItemStatusManager; public abstract class AbstractResourceRootConfigItem extends AbstractConfigItem implements RefreshableConfigItem { ResourceRoot resourceRoot; public AbstractResourceRootConfigItem(String name, ConfigItemStatusManager versionManager, ResourceRoot resourceRoot) { super(name, versionManager); this.resourceRoot = resourceRoot; } @Override public String getSourceRevision() { return resourceRoot.getSourceRevision(); } @Override public void refresh() throws IOException { resourceRoot.scan(); } public ResourceRoot getResourceRoot() { return resourceRoot; } }
Java
/* * 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.camel.util.json; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * JsonArray is a common non-thread safe data format for a collection of data. * The contents of a JsonArray are only validated as JSON values on * serialization. * * @see Jsoner * @since 2.0.0 */ public class JsonArray extends ArrayList<Object> implements Jsonable { /** * The serialization version this class is compatible with. This value * doesn't need to be incremented if and only if the only changes to occur * were updating comments, updating javadocs, adding new fields to the * class, changing the fields from static to non-static, or changing the * fields from transient to non transient. All other changes require this * number be incremented. */ private static final long serialVersionUID = 1L; /** Instantiates an empty JsonArray. */ public JsonArray() { } /** * Instantiate a new JsonArray using ArrayList's constructor of the same * type. * * @param collection represents the elements to produce the JsonArray with. */ public JsonArray(final Collection<?> collection) { super(collection); } /** * A convenience method that assumes every element of the JsonArray is * castable to T before adding it to a collection of Ts. * * @param <T> represents the type that all of the elements of the JsonArray * should be cast to and the type the collection will contain. * @param destination represents where all of the elements of the JsonArray * are added to after being cast to the generic type provided. * @throws ClassCastException if the unchecked cast of an element to T * fails. */ @SuppressWarnings("unchecked") public <T> void asCollection(final Collection<T> destination) { for (final Object o : this) { destination.add((T)o); } } /** * A convenience method that assumes there is a BigDecimal, Number, or * String at the given index. If a Number or String is there it is used to * construct a new BigDecimal. * * @param index representing where the value is expected to be at. * @return the value stored at the key or the default provided if the key * doesn't exist. * @throws ClassCastException if there was a value but didn't match the * assumed return types. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal. * @see BigDecimal * @see Number#doubleValue() */ public BigDecimal getBigDecimal(final int index) { Object returnable = this.get(index); if (returnable instanceof BigDecimal) { /* Success there was a BigDecimal. */ } else if (returnable instanceof Number) { /* A number can be used to construct a BigDecimal. */ returnable = new BigDecimal(returnable.toString()); } else if (returnable instanceof String) { /* A number can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return (BigDecimal)returnable; } /** * A convenience method that assumes there is a Boolean or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a boolean. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. */ public Boolean getBoolean(final int index) { Object returnable = this.get(index); if (returnable instanceof String) { returnable = Boolean.valueOf((String)returnable); } return (Boolean)returnable; } /** * A convenience method that assumes there is a Number or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a byte. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal or if the Number represents the double or float * Infinity or NaN. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Number */ public Byte getByte(final int index) { Object returnable = this.get(index); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return ((Number)returnable).byteValue(); } /** * A convenience method that assumes there is a Collection value at the * given index. * * @param <T> the kind of collection to expect at the index. Note unless * manually added, collection values will be a JsonArray. * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a Collection. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Collection */ @SuppressWarnings("unchecked") public <T extends Collection<?>> T getCollection(final int index) { /* * The unchecked warning is suppressed because there is no way of * guaranteeing at compile time the cast will work. */ return (T)this.get(index); } /** * A convenience method that assumes there is a Number or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a double. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal or if the Number represents the double or float * Infinity or NaN. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Number */ public Double getDouble(final int index) { Object returnable = this.get(index); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return ((Number)returnable).doubleValue(); } /** * A convenience method that assumes there is a String value at the given * index representing a fully qualified name in dot notation of an enum. * * @param index representing where the value is expected to be at. * @param <T> the Enum type the value at the index is expected to belong to. * @return the enum based on the string found at the index, or null if the * value at the index was null. * @throws ClassNotFoundException if the element was a String but the * declaring enum type couldn't be determined with it. * @throws ClassCastException if the element at the index was not a String * or if the fully qualified enum name is of the wrong type. * @throws IllegalArgumentException if an enum type was dynamically * determined but it doesn't define an enum with the dynamically * determined name. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Enum#valueOf(Class, String) */ @SuppressWarnings("unchecked") public <T extends Enum<T>> T getEnum(final int index) throws ClassNotFoundException { /* * Supressing the unchecked warning because the returnType is * dynamically identified and could lead to a ClassCastException when * returnType is cast to Class<T>, which is expected by the method's * contract. */ T returnable; final String element; final String[] splitValues; final int numberOfValues; final StringBuilder returnTypeName; final StringBuilder enumName; final Class<T> returnType; /* Make sure the element at the index is a String. */ element = this.getString(index); if (element == null) { return null; } /* Get the package, class, and enum names. */ splitValues = element.split("\\."); numberOfValues = splitValues.length; returnTypeName = new StringBuilder(); enumName = new StringBuilder(); for (int i = 0; i < numberOfValues; i++) { if (i == (numberOfValues - 1)) { /* * If it is the last split value then it should be the name of * the Enum since dots are not allowed in enum names. */ enumName.append(splitValues[i]); } else if (i == (numberOfValues - 2)) { /* * If it is the penultimate split value then it should be the * end of the package/enum type and not need a dot appended to * it. */ returnTypeName.append(splitValues[i]); } else { /* * Must be part of the package/enum type and will need a dot * appended to it since they got removed in the split. */ returnTypeName.append(splitValues[i]); returnTypeName.append("."); } } /* Use the package/class and enum names to get the Enum<T>. */ returnType = (Class<T>)Class.forName(returnTypeName.toString()); returnable = Enum.valueOf(returnType, enumName.toString()); return returnable; } /** * A convenience method that assumes there is a Number or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a float. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal or if the Number represents the double or float * Infinity or NaN. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Number */ public Float getFloat(final int index) { Object returnable = this.get(index); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return ((Number)returnable).floatValue(); } /** * A convenience method that assumes there is a Number or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a int. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal or if the Number represents the double or float * Infinity or NaN. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Number */ public Integer getInteger(final int index) { Object returnable = this.get(index); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return ((Number)returnable).intValue(); } /** * A convenience method that assumes there is a Number or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a long. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal or if the Number represents the double or float * Infinity or NaN. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Number */ public Long getLong(final int index) { Object returnable = this.get(index); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return ((Number)returnable).longValue(); } /** * A convenience method that assumes there is a Map value at the given * index. * * @param <T> the kind of map to expect at the index. Note unless manually * added, Map values will be a JsonObject. * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a Map. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Map */ @SuppressWarnings("unchecked") public <T extends Map<?, ?>> T getMap(final int index) { /* * The unchecked warning is suppressed because there is no way of * guaranteeing at compile time the cast will work. */ return (T)this.get(index); } /** * A convenience method that assumes there is a Number or String value at * the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a short. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws NumberFormatException if a String isn't a valid representation of * a BigDecimal or if the Number represents the double or float * Infinity or NaN. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. * @see Number */ public Short getShort(final int index) { Object returnable = this.get(index); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String)returnable); } return ((Number)returnable).shortValue(); } /** * A convenience method that assumes there is a Boolean, Number, or String * value at the given index. * * @param index represents where the value is expected to be at. * @return the value at the index provided cast to a String. * @throws ClassCastException if there was a value but didn't match the * assumed return type. * @throws IndexOutOfBoundsException if the index is outside of the range of * element indexes in the JsonArray. */ public String getString(final int index) { Object returnable = this.get(index); if (returnable instanceof Boolean) { returnable = returnable.toString(); } else if (returnable instanceof Number) { returnable = returnable.toString(); } return (String)returnable; } /* * (non-Javadoc) * @see org.apache.camel.util.json.Jsonable#asJsonString() */ @Override public String toJson() { final StringWriter writable = new StringWriter(); try { this.toJson(writable); } catch (final IOException caught) { /* See java.io.StringWriter. */ } return writable.toString(); } /* * (non-Javadoc) * @see org.apache.camel.util.json.Jsonable#toJsonString(java.io.Writer) */ @Override public void toJson(final Writer writable) throws IOException { boolean isFirstElement = true; final Iterator<Object> elements = this.iterator(); writable.write('['); while (elements.hasNext()) { if (isFirstElement) { isFirstElement = false; } else { writable.write(','); } writable.write(Jsoner.serialize(elements.next())); } writable.write(']'); } }
Java
/* * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.portlet.notice.util; import javax.portlet.PortletRequest; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @Component("usernameFinder") public final class UsernameFinder { @Value("${UsernameFinder.unauthenticatedUsername}") private String unauthenticatedUsername = "guest"; private Logger logger = LoggerFactory.getLogger(getClass()); /** * @deprecated Prefer interactions that are not based on the Portlet API */ @Deprecated public String findUsername(PortletRequest req) { return req.getRemoteUser() != null ? req.getRemoteUser() : unauthenticatedUsername; } /** * @since 4.0 */ public String findUsername(HttpServletRequest request) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); logger.trace("Processing the following Authentication object: {}", authentication); final String rslt = (String) authentication.getPrincipal(); logger.debug("Found username '{}' based on the contents of the SecurityContextHolder", rslt); // Identification based on Spring Security is required to access Servlet-based APIs if (rslt == null) { throw new SecurityException("User not identified"); } return rslt; } /** * @deprecated Prefer interactions that are not based on the Portlet API */ @Deprecated public boolean isAuthenticated(PortletRequest req) { return !findUsername(req).equalsIgnoreCase(unauthenticatedUsername); } public boolean isAuthenticated(HttpServletRequest request) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); logger.trace("Processing the following Authentication object: {}", authentication); return authentication != null && authentication.isAuthenticated(); } }
Java
import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'gothamads'; const ACCOUNTID_MACROS = '[account_id]'; const URL_ENDPOINT = `https://us-e-node1.gothamads.com/bid?pass=${ACCOUNTID_MACROS}&integration=prebidjs`; const NATIVE_ASSET_IDS = { 0: 'title', 2: 'icon', 3: 'image', 5: 'sponsoredBy', 4: 'body', 1: 'cta' }; const NATIVE_PARAMS = { title: { id: 0, name: 'title' }, icon: { id: 2, type: 1, name: 'img' }, image: { id: 3, type: 3, name: 'img' }, sponsoredBy: { id: 5, name: 'data', type: 1 }, body: { id: 4, name: 'data', type: 2 }, cta: { id: 1, type: 12, name: 'data' } }; const NATIVE_VERSION = '1.2'; export const spec = { code: BIDDER_CODE, supportedMediaTypes: [BANNER, VIDEO, NATIVE], /** * Determines whether or not the given bid request is valid. * * @param {object} bid The bid to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: (bid) => { return Boolean(bid.params.accountId) && Boolean(bid.params.placementId) }, /** * Make a server request from the list of BidRequests. * * @param {BidRequest[]} validBidRequests A non-empty list of valid bid requests that should be sent to the Server. * @return ServerRequest Info describing the request to the server. */ buildRequests: (validBidRequests, bidderRequest) => { if (validBidRequests && validBidRequests.length === 0) return [] let accuontId = validBidRequests[0].params.accountId; const endpointURL = URL_ENDPOINT.replace(ACCOUNTID_MACROS, accuontId); let winTop = window; let location; try { location = new URL(bidderRequest.refererInfo.referer) winTop = window.top; } catch (e) { location = winTop.location; utils.logMessage(e); }; let bids = []; for (let bidRequest of validBidRequests) { let impObject = prepareImpObject(bidRequest); let data = { id: bidRequest.bidId, test: config.getConfig('debug') ? 1 : 0, cur: ['USD'], device: { w: winTop.screen.width, h: winTop.screen.height, language: (navigator && navigator.language) ? navigator.language.indexOf('-') != -1 ? navigator.language.split('-')[0] : navigator.language : '', }, site: { page: location.pathname, host: location.host }, source: { tid: bidRequest.transactionId }, regs: { coppa: config.getConfig('coppa') === true ? 1 : 0, ext: {} }, tmax: bidRequest.timeout, imp: [impObject], }; if (bidRequest.gdprConsent && bidRequest.gdprConsent.gdprApplies) { utils.deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); utils.deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); } if (bidRequest.uspConsent !== undefined) { utils.deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); } bids.push(data) } return { method: 'POST', url: endpointURL, data: bids }; }, /** * Unpack the response from the server into a list of bids. * * @param {*} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: (serverResponse) => { if (!serverResponse || !serverResponse.body) return [] let GothamAdsResponse = serverResponse.body; let bids = []; for (let response of GothamAdsResponse) { let mediaType = response.seatbid[0].bid[0].ext && response.seatbid[0].bid[0].ext.mediaType ? response.seatbid[0].bid[0].ext.mediaType : BANNER; let bid = { requestId: response.id, cpm: response.seatbid[0].bid[0].price, width: response.seatbid[0].bid[0].w, height: response.seatbid[0].bid[0].h, ttl: response.ttl || 1200, currency: response.cur || 'USD', netRevenue: true, creativeId: response.seatbid[0].bid[0].crid, dealId: response.seatbid[0].bid[0].dealid, mediaType: mediaType }; bid.meta = {}; if (response.seatbid[0].bid[0].adomain && response.seatbid[0].bid[0].adomain.length > 0) { bid.meta.advertiserDomains = response.seatbid[0].bid[0].adomain; } switch (mediaType) { case VIDEO: bid.vastXml = response.seatbid[0].bid[0].adm; bid.vastUrl = response.seatbid[0].bid[0].ext.vastUrl; break; case NATIVE: bid.native = parseNative(response.seatbid[0].bid[0].adm); break; default: bid.ad = response.seatbid[0].bid[0].adm; } bids.push(bid); } return bids; }, }; /** * Determine type of request * * @param bidRequest * @param type * @returns {boolean} */ const checkRequestType = (bidRequest, type) => { return (typeof utils.deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); } const parseNative = admObject => { const { assets, link, imptrackers, jstracker } = admObject.native; const result = { clickUrl: link.url, clickTrackers: link.clicktrackers || undefined, impressionTrackers: imptrackers || undefined, javascriptTrackers: jstracker ? [jstracker] : undefined }; assets.forEach(asset => { const kind = NATIVE_ASSET_IDS[asset.id]; const content = kind && asset[NATIVE_PARAMS[kind].name]; if (content) { result[kind] = content.text || content.value || { url: content.url, width: content.w, height: content.h }; } }); return result; } const prepareImpObject = (bidRequest) => { let impObject = { id: bidRequest.transactionId, secure: 1, ext: { placementId: bidRequest.params.placementId } }; if (checkRequestType(bidRequest, BANNER)) { impObject.banner = addBannerParameters(bidRequest); } if (checkRequestType(bidRequest, VIDEO)) { impObject.video = addVideoParameters(bidRequest); } if (checkRequestType(bidRequest, NATIVE)) { impObject.native = { ver: NATIVE_VERSION, request: addNativeParameters(bidRequest) }; } return impObject }; const addNativeParameters = bidRequest => { let impObject = { id: bidRequest.transactionId, ver: NATIVE_VERSION, }; const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, }; if (props) { asset.id = props.id; let wmin, hmin; let aRatios = bidParams.aspect_ratios; if (aRatios && aRatios[0]) { aRatios = aRatios[0]; wmin = aRatios.min_width || 0; hmin = aRatios.ratio_height * wmin / aRatios.ratio_width | 0; } if (bidParams.sizes) { const sizes = flatten(bidParams.sizes); wmin = sizes[0]; hmin = sizes[1]; } asset[props.name] = {} if (bidParams.len) asset[props.name]['len'] = bidParams.len; if (props.type) asset[props.name]['type'] = props.type; if (wmin) asset[props.name]['wmin'] = wmin; if (hmin) asset[props.name]['hmin'] = hmin; return asset; } }).filter(Boolean); impObject.assets = assets; return impObject } const addBannerParameters = (bidRequest) => { let bannerObject = {}; const size = parseSizes(bidRequest, 'banner'); bannerObject.w = size[0]; bannerObject.h = size[1]; return bannerObject; }; const parseSizes = (bid, mediaType) => { let mediaTypes = bid.mediaTypes; if (mediaType === 'video') { let size = []; if (mediaTypes.video && mediaTypes.video.w && mediaTypes.video.h) { size = [ mediaTypes.video.w, mediaTypes.video.h ]; } else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { size = bid.mediaTypes.video.playerSize[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) { size = bid.sizes[0]; } return size; } let sizes = []; if (Array.isArray(mediaTypes.banner.sizes)) { sizes = mediaTypes.banner.sizes[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { sizes = bid.sizes } else { utils.logWarn('no sizes are setup or found'); } return sizes } const addVideoParameters = (bidRequest) => { let videoObj = {}; let supportParamsList = ['mimes', 'minduration', 'maxduration', 'protocols', 'startdelay', 'placement', 'skip', 'skipafter', 'minbitrate', 'maxbitrate', 'delivery', 'playbackmethod', 'api', 'linearity'] for (let param of supportParamsList) { if (bidRequest.mediaTypes.video[param] !== undefined) { videoObj[param] = bidRequest.mediaTypes.video[param]; } } const size = parseSizes(bidRequest, 'video'); videoObj.w = size[0]; videoObj.h = size[1]; return videoObj; } const flatten = arr => { return [].concat(...arr); } registerBidder(spec);
Java
<?php /** * @category SchumacherFM * @package SchumacherFM_FastIndexer * @copyright Copyright (c) http://www.schumacher.fm * @license see LICENSE.md file * @author Cyrill at Schumacher dot fm @SchumacherFM */ class SchumacherFM_FastIndexer_Model_Lock_Session extends SchumacherFM_FastIndexer_Model_Lock_Abstract implements SchumacherFM_FastIndexer_Model_Lock_LockInterface { const SESS_PREFIX = 'fastindexer_'; /** * @var Mage_Core_Model_Resource_Session */ protected $_session = null; /** * @return Mage_Core_Model_Resource_Session */ public function getSession() { if (null !== $this->_session) { return $this->_session; } $this->_session = Mage::getResourceSingleton('core/session'); return $this->_session; } /** * Lock process without blocking. * This method allow protect multiple process running and fast lock validation. * */ public function lock() { $this->getSession()->write(self::SESS_PREFIX . $this->getIndexerCode(), microtime(true)); } /** * Lock and block process. * If new instance of the process will try validate locking state * script will wait until process will be unlocked * */ public function lockAndBlock() { $this->lock(); } /** * Unlock process * * @return Mage_Index_Model_Process */ public function unlock() { $this->getSession()->destroy(self::SESS_PREFIX . $this->getIndexerCode()); } /** * Check if process is locked * * @return bool */ public function isLocked() { $startTime = (double)$this->getSession()->read(self::SESS_PREFIX . $this->getIndexerCode()); if ($startTime < 0.0001) { return false; } return $this->_isLockedByTtl($startTime); } }
Java
/* * 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.druid.indexing.input; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterators; import org.apache.druid.client.coordinator.CoordinatorClient; import org.apache.druid.data.input.AbstractInputSource; import org.apache.druid.data.input.InputFileAttribute; import org.apache.druid.data.input.InputFormat; import org.apache.druid.data.input.InputRowSchema; import org.apache.druid.data.input.InputSourceReader; import org.apache.druid.data.input.InputSplit; import org.apache.druid.data.input.MaxSizeSplitHintSpec; import org.apache.druid.data.input.SegmentsSplitHintSpec; import org.apache.druid.data.input.SplitHintSpec; import org.apache.druid.data.input.impl.InputEntityIteratingReader; import org.apache.druid.data.input.impl.SplittableInputSource; import org.apache.druid.indexing.common.ReingestionTimelineUtils; import org.apache.druid.indexing.common.RetryPolicy; import org.apache.druid.indexing.common.RetryPolicyFactory; import org.apache.druid.indexing.common.SegmentLoaderFactory; import org.apache.druid.indexing.firehose.WindowedSegmentId; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.guava.Comparators; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.query.filter.DimFilter; import org.apache.druid.segment.IndexIO; import org.apache.druid.segment.loading.SegmentLoader; import org.apache.druid.timeline.DataSegment; import org.apache.druid.timeline.TimelineObjectHolder; import org.apache.druid.timeline.VersionedIntervalTimeline; import org.apache.druid.timeline.partition.PartitionChunk; import org.apache.druid.timeline.partition.PartitionHolder; import org.apache.druid.utils.Streams; import org.joda.time.Duration; import org.joda.time.Interval; import javax.annotation.Nullable; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Stream; public class DruidInputSource extends AbstractInputSource implements SplittableInputSource<List<WindowedSegmentId>> { private static final Logger LOG = new Logger(DruidInputSource.class); /** * A Comparator that orders {@link WindowedSegmentId} mainly by segmentId (which is important), and then by intervals * (which is arbitrary, and only here for totality of ordering). */ private static final Comparator<WindowedSegmentId> WINDOWED_SEGMENT_ID_COMPARATOR = Comparator.comparing(WindowedSegmentId::getSegmentId) .thenComparing(windowedSegmentId -> windowedSegmentId.getIntervals().size()) .thenComparing( (WindowedSegmentId a, WindowedSegmentId b) -> { // Same segmentId, same intervals list size. Compare each interval. int cmp = 0; for (int i = 0; i < a.getIntervals().size(); i++) { cmp = Comparators.intervalsByStartThenEnd() .compare(a.getIntervals().get(i), b.getIntervals().get(i)); if (cmp != 0) { return cmp; } } return cmp; } ); private final String dataSource; // Exactly one of interval and segmentIds should be non-null. Typically 'interval' is specified directly // by the user creating this firehose and 'segmentIds' is used for sub-tasks if it is split for parallel // batch ingestion. @Nullable private final Interval interval; @Nullable private final List<WindowedSegmentId> segmentIds; private final DimFilter dimFilter; private final List<String> dimensions; private final List<String> metrics; private final IndexIO indexIO; private final CoordinatorClient coordinatorClient; private final SegmentLoaderFactory segmentLoaderFactory; private final RetryPolicyFactory retryPolicyFactory; @JsonCreator public DruidInputSource( @JsonProperty("dataSource") final String dataSource, @JsonProperty("interval") @Nullable Interval interval, // Specifying "segments" is intended only for when this FirehoseFactory has split itself, // not for direct end user use. @JsonProperty("segments") @Nullable List<WindowedSegmentId> segmentIds, @JsonProperty("filter") DimFilter dimFilter, @Nullable @JsonProperty("dimensions") List<String> dimensions, @Nullable @JsonProperty("metrics") List<String> metrics, @JacksonInject IndexIO indexIO, @JacksonInject CoordinatorClient coordinatorClient, @JacksonInject SegmentLoaderFactory segmentLoaderFactory, @JacksonInject RetryPolicyFactory retryPolicyFactory ) { Preconditions.checkNotNull(dataSource, "dataSource"); if ((interval == null && segmentIds == null) || (interval != null && segmentIds != null)) { throw new IAE("Specify exactly one of 'interval' and 'segments'"); } this.dataSource = dataSource; this.interval = interval; this.segmentIds = segmentIds; this.dimFilter = dimFilter; this.dimensions = dimensions; this.metrics = metrics; this.indexIO = Preconditions.checkNotNull(indexIO, "null IndexIO"); this.coordinatorClient = Preconditions.checkNotNull(coordinatorClient, "null CoordinatorClient"); this.segmentLoaderFactory = Preconditions.checkNotNull(segmentLoaderFactory, "null SegmentLoaderFactory"); this.retryPolicyFactory = Preconditions.checkNotNull(retryPolicyFactory, "null RetryPolicyFactory"); } @JsonProperty public String getDataSource() { return dataSource; } @Nullable @JsonProperty public Interval getInterval() { return interval; } @Nullable @JsonProperty("segments") @JsonInclude(Include.NON_NULL) public List<WindowedSegmentId> getSegmentIds() { return segmentIds; } @JsonProperty("filter") public DimFilter getDimFilter() { return dimFilter; } @JsonProperty public List<String> getDimensions() { return dimensions; } @JsonProperty public List<String> getMetrics() { return metrics; } @Override protected InputSourceReader fixedFormatReader(InputRowSchema inputRowSchema, @Nullable File temporaryDirectory) { final SegmentLoader segmentLoader = segmentLoaderFactory.manufacturate(temporaryDirectory); final List<TimelineObjectHolder<String, DataSegment>> timeline = createTimeline(); final Iterator<DruidSegmentInputEntity> entityIterator = FluentIterable .from(timeline) .transformAndConcat(holder -> { //noinspection ConstantConditions final PartitionHolder<DataSegment> partitionHolder = holder.getObject(); //noinspection ConstantConditions return FluentIterable .from(partitionHolder) .transform(chunk -> new DruidSegmentInputEntity(segmentLoader, chunk.getObject(), holder.getInterval())); }).iterator(); final List<String> effectiveDimensions = ReingestionTimelineUtils.getDimensionsToReingest( dimensions, inputRowSchema.getDimensionsSpec(), timeline ); List<String> effectiveMetrics; if (metrics == null) { effectiveMetrics = ReingestionTimelineUtils.getUniqueMetrics(timeline); } else { effectiveMetrics = metrics; } final DruidSegmentInputFormat inputFormat = new DruidSegmentInputFormat( indexIO, dimFilter, effectiveDimensions, effectiveMetrics ); return new InputEntityIteratingReader( inputRowSchema, inputFormat, entityIterator, temporaryDirectory ); } private List<TimelineObjectHolder<String, DataSegment>> createTimeline() { if (interval == null) { return getTimelineForSegmentIds(coordinatorClient, dataSource, segmentIds); } else { return getTimelineForInterval(coordinatorClient, retryPolicyFactory, dataSource, interval); } } @Override public Stream<InputSplit<List<WindowedSegmentId>>> createSplits( InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec ) { // segmentIds is supposed to be specified by the supervisor task during the parallel indexing. // If it's not null, segments are already split by the supervisor task and further split won't happen. if (segmentIds == null) { return Streams.sequentialStreamFrom( createSplits( coordinatorClient, retryPolicyFactory, dataSource, interval, splitHintSpec == null ? SplittableInputSource.DEFAULT_SPLIT_HINT_SPEC : splitHintSpec ) ); } else { return Stream.of(new InputSplit<>(segmentIds)); } } @Override public int estimateNumSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec) { // segmentIds is supposed to be specified by the supervisor task during the parallel indexing. // If it's not null, segments are already split by the supervisor task and further split won't happen. if (segmentIds == null) { return Iterators.size( createSplits( coordinatorClient, retryPolicyFactory, dataSource, interval, splitHintSpec == null ? SplittableInputSource.DEFAULT_SPLIT_HINT_SPEC : splitHintSpec ) ); } else { return 1; } } @Override public SplittableInputSource<List<WindowedSegmentId>> withSplit(InputSplit<List<WindowedSegmentId>> split) { return new DruidInputSource( dataSource, null, split.get(), dimFilter, dimensions, metrics, indexIO, coordinatorClient, segmentLoaderFactory, retryPolicyFactory ); } @Override public boolean needsFormat() { return false; } public static Iterator<InputSplit<List<WindowedSegmentId>>> createSplits( CoordinatorClient coordinatorClient, RetryPolicyFactory retryPolicyFactory, String dataSource, Interval interval, SplitHintSpec splitHintSpec ) { final SplitHintSpec convertedSplitHintSpec; if (splitHintSpec instanceof SegmentsSplitHintSpec) { final SegmentsSplitHintSpec segmentsSplitHintSpec = (SegmentsSplitHintSpec) splitHintSpec; convertedSplitHintSpec = new MaxSizeSplitHintSpec( segmentsSplitHintSpec.getMaxInputSegmentBytesPerTask(), segmentsSplitHintSpec.getMaxNumSegments() ); } else { convertedSplitHintSpec = splitHintSpec; } final List<TimelineObjectHolder<String, DataSegment>> timelineSegments = getTimelineForInterval( coordinatorClient, retryPolicyFactory, dataSource, interval ); final Map<WindowedSegmentId, Long> segmentIdToSize = createWindowedSegmentIdFromTimeline(timelineSegments); //noinspection ConstantConditions return Iterators.transform( convertedSplitHintSpec.split( // segmentIdToSize is sorted by segment ID; useful for grouping up segments from the same time chunk into // the same input split. segmentIdToSize.keySet().iterator(), segmentId -> new InputFileAttribute( Preconditions.checkNotNull(segmentIdToSize.get(segmentId), "segment size for [%s]", segmentId) ) ), InputSplit::new ); } /** * Returns a map of {@link WindowedSegmentId} to size, sorted by {@link WindowedSegmentId#getSegmentId()}. */ private static SortedMap<WindowedSegmentId, Long> createWindowedSegmentIdFromTimeline( List<TimelineObjectHolder<String, DataSegment>> timelineHolders ) { Map<DataSegment, WindowedSegmentId> windowedSegmentIds = new HashMap<>(); for (TimelineObjectHolder<String, DataSegment> holder : timelineHolders) { for (PartitionChunk<DataSegment> chunk : holder.getObject()) { windowedSegmentIds.computeIfAbsent( chunk.getObject(), segment -> new WindowedSegmentId(segment.getId().toString(), new ArrayList<>()) ).addInterval(holder.getInterval()); } } // It is important to create this map after windowedSegmentIds is completely filled, because WindowedSegmentIds // can be updated while being constructed. (Intervals are added.) SortedMap<WindowedSegmentId, Long> segmentSizeMap = new TreeMap<>(WINDOWED_SEGMENT_ID_COMPARATOR); windowedSegmentIds.forEach((segment, segmentId) -> segmentSizeMap.put(segmentId, segment.getSize())); return segmentSizeMap; } public static List<TimelineObjectHolder<String, DataSegment>> getTimelineForInterval( CoordinatorClient coordinatorClient, RetryPolicyFactory retryPolicyFactory, String dataSource, Interval interval ) { Preconditions.checkNotNull(interval); // This call used to use the TaskActionClient, so for compatibility we use the same retry configuration // as TaskActionClient. final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy(); Collection<DataSegment> usedSegments; while (true) { try { usedSegments = coordinatorClient.fetchUsedSegmentsInDataSourceForIntervals( dataSource, Collections.singletonList(interval) ); break; } catch (Throwable e) { LOG.warn(e, "Exception getting database segments"); final Duration delay = retryPolicy.getAndIncrementRetryDelay(); if (delay == null) { throw e; } else { final long sleepTime = jitter(delay.getMillis()); LOG.info("Will try again in [%s].", new Duration(sleepTime).toString()); try { Thread.sleep(sleepTime); } catch (InterruptedException e2) { throw new RuntimeException(e2); } } } } return VersionedIntervalTimeline.forSegments(usedSegments).lookup(interval); } public static List<TimelineObjectHolder<String, DataSegment>> getTimelineForSegmentIds( CoordinatorClient coordinatorClient, String dataSource, List<WindowedSegmentId> segmentIds ) { final SortedMap<Interval, TimelineObjectHolder<String, DataSegment>> timeline = new TreeMap<>( Comparators.intervalsByStartThenEnd() ); for (WindowedSegmentId windowedSegmentId : Preconditions.checkNotNull(segmentIds, "segmentIds")) { final DataSegment segment = coordinatorClient.fetchUsedSegment( dataSource, windowedSegmentId.getSegmentId() ); for (Interval interval : windowedSegmentId.getIntervals()) { final TimelineObjectHolder<String, DataSegment> existingHolder = timeline.get(interval); if (existingHolder != null) { if (!existingHolder.getVersion().equals(segment.getVersion())) { throw new ISE("Timeline segments with the same interval should have the same version: " + "existing version[%s] vs new segment[%s]", existingHolder.getVersion(), segment); } existingHolder.getObject().add(segment.getShardSpec().createChunk(segment)); } else { timeline.put( interval, new TimelineObjectHolder<>( interval, segment.getInterval(), segment.getVersion(), new PartitionHolder<>(segment.getShardSpec().createChunk(segment)) ) ); } } } // Validate that none of the given windows overlaps (except for when multiple segments share exactly the // same interval). Interval lastInterval = null; for (Interval interval : timeline.keySet()) { if (lastInterval != null && interval.overlaps(lastInterval)) { throw new IAE( "Distinct intervals in input segments may not overlap: [%s] vs [%s]", lastInterval, interval ); } lastInterval = interval; } return new ArrayList<>(timeline.values()); } private static long jitter(long input) { final double jitter = ThreadLocalRandom.current().nextGaussian() * input / 4.0; long retval = input + (long) jitter; return retval < 0 ? 0 : retval; } }
Java
// // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #include "fuzzer_gc_guard.hpp" #include "fuzzer_input.hpp" #include <immer/heap/gc_heap.hpp> #include <immer/refcount/no_refcount_policy.hpp> #include <immer/set.hpp> #include <immer/algorithm.hpp> #include <array> using gc_memory = immer::memory_policy<immer::heap_policy<immer::gc_heap>, immer::no_refcount_policy, immer::default_lock_policy, immer::gc_transience_policy, false>; struct colliding_hash_t { std::size_t operator()(std::size_t x) const { return x & ~15; } }; extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { auto guard = fuzzer_gc_guard{}; constexpr auto var_count = 4; using set_t = immer::set<size_t, colliding_hash_t, std::equal_to<>, gc_memory>; auto vars = std::array<set_t, var_count>{}; auto is_valid_var = [&](auto idx) { return idx >= 0 && idx < var_count; }; return fuzzer_input{data, size}.run([&](auto& in) { enum ops { op_insert, op_erase, op_insert_move, op_erase_move, op_iterate }; auto src = read<char>(in, is_valid_var); auto dst = read<char>(in, is_valid_var); switch (read<char>(in)) { case op_insert: { auto value = read<size_t>(in); vars[dst] = vars[src].insert(value); break; } case op_erase: { auto value = read<size_t>(in); vars[dst] = vars[src].erase(value); break; } case op_insert_move: { auto value = read<size_t>(in); vars[dst] = std::move(vars[src]).insert(value); break; } case op_erase_move: { auto value = read<size_t>(in); vars[dst] = std::move(vars[src]).erase(value); break; } case op_iterate: { auto srcv = vars[src]; immer::for_each(srcv, [&](auto&& v) { vars[dst] = std::move(vars[dst]).insert(v); }); break; } default: break; }; return true; }); }
Java
#!/bin/sh curl -fsLO https://raw.githubusercontent.com/scijava/scijava-scripts/master/travis-build.sh bash travis-build.sh $encrypted_f76761764219_key $encrypted_f76761764219_iv && if [ ! -f release.properties ] then echo echo '== No release.properties; running integration tests ==' # Not a release -- also perform integration tests. mvn -Dinvoker.debug=true -Prun-its fi
Java
package pod import ( "fmt" "strings" lru "github.com/hashicorp/golang-lru" "github.com/rancher/norman/api/access" "github.com/rancher/norman/types" "github.com/rancher/norman/types/values" "github.com/rancher/rancher/pkg/controllers/managementagent/workload" "github.com/rancher/rancher/pkg/ref" schema "github.com/rancher/rancher/pkg/schemas/project.cattle.io/v3" "github.com/sirupsen/logrus" ) var ( ownerCache, _ = lru.New(100000) ) type key struct { SubContext string Namespace string Kind string Name string } type value struct { Kind string Name string } func getOwnerWithKind(apiContext *types.APIContext, namespace, ownerKind, name string) (string, string, error) { subContext := apiContext.SubContext["/v3/schemas/project"] if subContext == "" { subContext = apiContext.SubContext["/v3/schemas/cluster"] } if subContext == "" { logrus.Warnf("failed to find subcontext to lookup replicaSet owner") return "", "", nil } key := key{ SubContext: subContext, Namespace: namespace, Kind: strings.ToLower(ownerKind), Name: name, } val, ok := ownerCache.Get(key) if ok { value, _ := val.(value) return value.Kind, value.Name, nil } data := map[string]interface{}{} if err := access.ByID(apiContext, &schema.Version, ownerKind, ref.FromStrings(namespace, name), &data); err != nil { return "", "", err } kind, name := getOwner(data) if !workload.WorkloadKinds[kind] { kind = "" name = "" } ownerCache.Add(key, value{ Kind: kind, Name: name, }) return kind, name, nil } func getOwner(data map[string]interface{}) (string, string) { ownerReferences, ok := values.GetSlice(data, "ownerReferences") if !ok { return "", "" } for _, ownerReference := range ownerReferences { controller, _ := ownerReference["controller"].(bool) if !controller { continue } kind, _ := ownerReference["kind"].(string) name, _ := ownerReference["name"].(string) return kind, name } return "", "" } func SaveOwner(apiContext *types.APIContext, kind, name string, data map[string]interface{}) { parentKind, parentName := getOwner(data) namespace, _ := data["namespaceId"].(string) subContext := apiContext.SubContext["/v3/schemas/project"] if subContext == "" { subContext = apiContext.SubContext["/v3/schemas/cluster"] } if subContext == "" { return } key := key{ SubContext: subContext, Namespace: namespace, Kind: strings.ToLower(kind), Name: name, } ownerCache.Add(key, value{ Kind: parentKind, Name: parentName, }) } func resolveWorkloadID(apiContext *types.APIContext, data map[string]interface{}) string { kind, name := getOwner(data) if kind == "" || !workload.WorkloadKinds[kind] { return "" } namespace, _ := data["namespaceId"].(string) if ownerKind := strings.ToLower(kind); ownerKind == workload.ReplicaSetType || ownerKind == workload.JobType { k, n, err := getOwnerWithKind(apiContext, namespace, ownerKind, name) if err != nil { return "" } if k != "" { kind, name = k, n } } return strings.ToLower(fmt.Sprintf("%s:%s:%s", kind, namespace, name)) }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (9-Debian) on Thu Sep 28 23:13:23 GMT 2017 --> <title>Uses of Interface dollar.internal.runtime.script.api.HasKeyword (dollar-script 0.4.5195 API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="date" content="2017-09-28"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> <script type="text/javascript" src="../../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface dollar.internal.runtime.script.api.HasKeyword (dollar-script 0.4.5195 API)"; } } catch(err) { } //--> var pathtoroot = "../../../../../../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?dollar/internal/runtime/script/api/class-use/HasKeyword.html" target="_top">Frames</a></li> <li><a href="HasKeyword.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><span>SEARCH:&nbsp;</span> <input type="text" id="search" value=" " disabled="disabled"> <input type="reset" id="reset" value=" " disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> <div class="header"> <h2 title="Uses of Interface dollar.internal.runtime.script.api.HasKeyword" class="title">Uses of Interface<br>dollar.internal.runtime.script.api.HasKeyword</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">HasKeyword</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="#dollar.internal.runtime.script.parser">dollar.internal.runtime.script.parser</a></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="dollar.internal.runtime.script.parser"> <!-- --> </a> <h3>Uses of <a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">HasKeyword</a> in <a href="../../../../../../dollar/internal/runtime/script/parser/package-summary.html">dollar.internal.runtime.script.parser</a></h3> <table class="useSummary" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../dollar/internal/runtime/script/parser/package-summary.html">dollar.internal.runtime.script.parser</a> that implement <a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">HasKeyword</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../../dollar/internal/runtime/script/parser/KeywordDef.html" title="class in dollar.internal.runtime.script.parser">KeywordDef</a></span></code></th> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../../dollar/internal/runtime/script/parser/Op.html" title="class in dollar.internal.runtime.script.parser">Op</a></span></code></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?dollar/internal/runtime/script/api/class-use/HasKeyword.html" target="_top">Frames</a></li> <li><a href="HasKeyword.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017. All rights reserved.</small></p> </body> </html>
Java
import java.io.File; import java.io.FilenameFilter; class A { { new java.io.File("aaa").list(new FilenameFilter() { public boolean accept(File dir, String name) { <selection>return false; //To change body of implemented methods use File | Settings | File Templates.</selection> } }); } }
Java
// // YWUserTool.h // YiWobao // // Created by 刘毕涛 on 16/5/6. // Copyright © 2016年 浙江蚁窝投资管理有限公司. All rights reserved. // #import <Foundation/Foundation.h> @class YWUser; @interface YWUserTool : NSObject + (void)saveAccount:(YWUser *)account; + (YWUser *)account; + (void)quit; @end
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_23) on Fri Nov 23 14:03:50 GMT 2012 --> <TITLE> Uses of Class org.apache.nutch.crawl.CrawlDbMerger (apache-nutch 1.6 API) </TITLE> <META NAME="date" CONTENT="2012-11-23"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.nutch.crawl.CrawlDbMerger (apache-nutch 1.6 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/nutch/crawl/CrawlDbMerger.html" title="class in org.apache.nutch.crawl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/nutch/crawl//class-useCrawlDbMerger.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CrawlDbMerger.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.nutch.crawl.CrawlDbMerger</B></H2> </CENTER> No usage of org.apache.nutch.crawl.CrawlDbMerger <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/nutch/crawl/CrawlDbMerger.html" title="class in org.apache.nutch.crawl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/nutch/crawl//class-useCrawlDbMerger.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CrawlDbMerger.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2012 The Apache Software Foundation </BODY> </HTML>
Java
/* * 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.camel.processor.interceptor; import org.apache.camel.CamelExecutionException; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.RouteDefinition; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; public class AdviceWithLambdaTest extends ContextTestSupport { @Test public void testNoAdvised() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testAdvised() throws Exception { AdviceWithRouteBuilder.adviceWith(context, null, a -> { a.interceptSendToEndpoint("mock:foo").skipSendToOriginalEndpoint().to("log:foo").to("mock:advised"); }); getMockEndpoint("mock:foo").expectedMessageCount(0); getMockEndpoint("mock:advised").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } // END SNIPPET: e1 @Test public void testAdvisedNoLog() throws Exception { AdviceWithRouteBuilder.adviceWith(context, null, false, a -> { a.weaveByToUri("mock:result").remove(); a.weaveAddLast().transform().constant("Bye World"); }); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(0); Object out = template.requestBody("direct:start", "Hello World"); assertEquals("Bye World", out); assertMockEndpointsSatisfied(); } @Test public void testAdvisedNoNewRoutesAllowed() throws Exception { try { AdviceWithRouteBuilder.adviceWith(context, 0, a -> { a.from("direct:bar").to("mock:bar"); a.interceptSendToEndpoint("mock:foo").skipSendToOriginalEndpoint().to("log:foo").to("mock:advised"); }); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { // expected } } @Test public void testAdvisedThrowException() throws Exception { AdviceWithRouteBuilder.adviceWith(context, "myRoute", a -> { a.interceptSendToEndpoint("mock:foo").to("mock:advised").throwException(new IllegalArgumentException("Damn")); }); getMockEndpoint("mock:foo").expectedMessageCount(0); getMockEndpoint("mock:advised").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(0); try { template.sendBody("direct:start", "Hello World"); fail("Should have thrown exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertEquals("Damn", e.getCause().getMessage()); } assertMockEndpointsSatisfied(); } @Test public void testAdvisedRouteDefinition() throws Exception { AdviceWithRouteBuilder.adviceWith(context, context.getRouteDefinitions().get(0), a -> { a.interceptSendToEndpoint("mock:foo").skipSendToOriginalEndpoint().to("log:foo").to("mock:advised"); }); getMockEndpoint("mock:foo").expectedMessageCount(0); getMockEndpoint("mock:advised").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testAdvisedEmptyRouteDefinition() throws Exception { try { AdviceWithRouteBuilder.adviceWith(context, new RouteDefinition(), a -> { a.interceptSendToEndpoint("mock:foo").skipSendToOriginalEndpoint().to("log:foo").to("mock:advised"); }); fail("Should throw exception"); } catch (IllegalArgumentException e) { // expected } } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").id("myRoute").to("mock:foo").to("mock:result"); } }; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_121) on Sun Jul 02 12:07:17 PDT 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.guacamole.net.event.AuthenticationSuccessEvent (guacamole-ext 0.9.13-incubating API)</title> <meta name="date" content="2017-07-02"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.guacamole.net.event.AuthenticationSuccessEvent (guacamole-ext 0.9.13-incubating API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/guacamole/net/event/AuthenticationSuccessEvent.html" title="class in org.apache.guacamole.net.event">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/guacamole/net/event/class-use/AuthenticationSuccessEvent.html" target="_top">Frames</a></li> <li><a href="AuthenticationSuccessEvent.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.guacamole.net.event.AuthenticationSuccessEvent" class="title">Uses of Class<br>org.apache.guacamole.net.event.AuthenticationSuccessEvent</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/guacamole/net/event/AuthenticationSuccessEvent.html" title="class in org.apache.guacamole.net.event">AuthenticationSuccessEvent</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.guacamole.net.event.listener">org.apache.guacamole.net.event.listener</a></td> <td class="colLast"> <div class="block">Provides classes for hooking into various events that take place as users log into and use the Guacamole web application.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.guacamole.net.event.listener"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/guacamole/net/event/AuthenticationSuccessEvent.html" title="class in org.apache.guacamole.net.event">AuthenticationSuccessEvent</a> in <a href="../../../../../../org/apache/guacamole/net/event/listener/package-summary.html">org.apache.guacamole.net.event.listener</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/guacamole/net/event/listener/package-summary.html">org.apache.guacamole.net.event.listener</a> with parameters of type <a href="../../../../../../org/apache/guacamole/net/event/AuthenticationSuccessEvent.html" title="class in org.apache.guacamole.net.event">AuthenticationSuccessEvent</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><span class="typeNameLabel">AuthenticationSuccessListener.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/guacamole/net/event/listener/AuthenticationSuccessListener.html#authenticationSucceeded-org.apache.guacamole.net.event.AuthenticationSuccessEvent-">authenticationSucceeded</a></span>(<a href="../../../../../../org/apache/guacamole/net/event/AuthenticationSuccessEvent.html" title="class in org.apache.guacamole.net.event">AuthenticationSuccessEvent</a>&nbsp;e)</code> <div class="block">Event hook which fires immediately after a user's authentication attempt succeeds.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/guacamole/net/event/AuthenticationSuccessEvent.html" title="class in org.apache.guacamole.net.event">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/guacamole/net/event/class-use/AuthenticationSuccessEvent.html" target="_top">Frames</a></li> <li><a href="AuthenticationSuccessEvent.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017. All rights reserved.</small></p> <!-- Google Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75289145-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
Java
/* * Copyright (C) 2008 The Android Open Source Project * * 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 com.android.launcher3; import android.content.ContentValues; import android.content.Context; import com.android.launcher3.compat.UserHandleCompat; import java.util.ArrayList; /** * Represents a folder containing shortcuts or apps. */ public class FolderInfo extends ItemInfo { public static final int NO_FLAGS = 0x00000000; /** * The folder is locked in sorted mode */ public static final int FLAG_ITEMS_SORTED = 0x00000001; /** * It is a work folder */ public static final int FLAG_WORK_FOLDER = 0x00000002; /** * The multi-page animation has run for this folder */ public static final int FLAG_MULTI_PAGE_ANIMATION = 0x00000004; /** * Whether this folder has been opened */ public boolean opened; public int options; /** * The apps and shortcuts */ public ArrayList<ShortcutInfo> contents = new ArrayList<ShortcutInfo>(); ArrayList<FolderListener> listeners = new ArrayList<FolderListener>(); public FolderInfo() { itemType = LauncherSettings.Favorites.ITEM_TYPE_FOLDER; user = UserHandleCompat.myUserHandle(); } /** * Add an app or shortcut * * @param item */ public void add(ShortcutInfo item, boolean animate) { contents.add(item); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onAdd(item); } itemsChanged(animate); } /** * Remove an app or shortcut. Does not change the DB. * * @param item */ public void remove(ShortcutInfo item, boolean animate) { contents.remove(item); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onRemove(item); } itemsChanged(animate); } public void setTitle(CharSequence title) { this.title = title; for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onTitleChanged(title); } } @Override void onAddToDatabase(Context context, ContentValues values) { super.onAddToDatabase(context, values); values.put(LauncherSettings.Favorites.TITLE, title.toString()); values.put(LauncherSettings.Favorites.OPTIONS, options); } public void addListener(FolderListener listener) { listeners.add(listener); } public void removeListener(FolderListener listener) { listeners.remove(listener); } public void itemsChanged(boolean animate) { for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onItemsChanged(animate); } } public interface FolderListener { public void onAdd(ShortcutInfo item); public void onRemove(ShortcutInfo item); public void onTitleChanged(CharSequence title); public void onItemsChanged(boolean animate); } public boolean hasOption(int optionFlag) { return (options & optionFlag) != 0; } /** * @param option flag to set or clear * @param isEnabled whether to set or clear the flag * @param context if not null, save changes to the db. */ public void setOption(int option, boolean isEnabled, Context context) { int oldOptions = options; if (isEnabled) { options |= option; } else { options &= ~option; } if (context != null && oldOptions != options) { LauncherModel.updateItemInDatabase(context, this); } } }
Java