repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
DrXyzzy/cocalc | src/packages/frontend/billing/util.tsx | 1909 | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { React, Rendered } from "../app-framework";
import { Icon } from "../components/icon";
import { PROJECT_UPGRADES } from "@cocalc/util/schema";
import { Tip } from "../components/tip";
import { Space } from "../components/space";
import { round1, plural } from "@cocalc/util/misc";
import { stripe_amount } from "@cocalc/util/misc";
import { Plan } from "./types";
export function powered_by_stripe(): Rendered {
return (
<span>
Powered by{" "}
<a
href="https://stripe.com/"
rel="noopener"
target="_blank"
style={{ top: "7px", position: "relative", fontSize: "23pt" }}
>
<Icon name="cc-stripe" />
</a>
</span>
);
}
export function render_project_quota(name: string, value: number): Rendered {
const data = PROJECT_UPGRADES.params[name];
if (data == null) {
throw Error(`unknown quota ${name}`);
}
let amount: number = value * data.pricing_factor;
let unit: string = data.pricing_unit;
if (unit === "day" && amount < 2) {
amount = 24 * amount;
unit = "hour";
}
return (
<div key={name} style={{ marginBottom: "5px", marginLeft: "10px" }}>
<Tip title={data.display} tip={data.desc}>
<span style={{ fontWeight: "bold", color: "#666" }}>
{round1(amount)} {plural(amount, unit)}
</span>
<Space />
<span style={{ color: "#999" }}>{data.display}</span>
</Tip>
</div>
);
}
export function render_amount(amount: number, currency: string) {
return (
<div style={{ float: "right" }}>{stripe_amount(amount, currency)}</div>
);
}
export function plan_interval(plan: Plan): string {
const n: number = plan.interval_count;
return `${plan.interval_count} ${plural(n, plan.interval)}`;
}
| agpl-3.0 |
vimsvarcode/elmis | modules/odk-api/src/main/java/org/openlmis/odkapi/repository/mapper/ODKAccountMapper.java | 2245 | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
/**
* Created with IntelliJ IDEA.
* User: Messay Yohannes <[email protected]>
* To change this template use File | Settings | File Templates.
*/
package org.openlmis.odkapi.repository.mapper;
import org.apache.ibatis.annotations.Select;
import org.openlmis.odkapi.domain.ODKAccount;
import org.springframework.stereotype.Repository;
@Repository
public interface ODKAccountMapper
{
@Select("SELECT * FROM odk_account where id = #{id}")
public ODKAccount getODKAccountById(Long id);
@Select("SELECT * FROM odk_account where deviceId = #{deviceId}")
public ODKAccount getODKAccountByDeviceId(String deviceId);
@Select("SELECT * FROM odk_account where SIMSerial = #{simSerial}")
public ODKAccount getODKAccountBySIMSerial(String simSerial);
@Select("SELECT * FROM odk_account where phoneNumber = #{phoneNumber}")
public ODKAccount getODKAccountByPhoneNumber(String phoneNumber);
@Select("SELECT * FROM odk_account where subscriberId = #{subscriberId}")
public ODKAccount getODKAccountBySubscriberId(String subscriberId);
@Select("SELECT * FROM odk_account where ODKUserName = #{odkUserName}")
public ODKAccount getODKAccountByODKUserName(String odkUserName);
@Select("SELECT * FROM odk_account where ODKEmail = #{odkEMail}")
public ODKAccount getODKAccountByODKEmail(String odkEMail);
}
| agpl-3.0 |
jhausladen/esclide | cloud9/plugins-client/ext.embedded_debugger/embedded_debugger.js | 27258 | /**
* Debugger for Embedded Hardware for the Cloud9 IDE
*
* @author Jürgen Hausladen
* @copyright 2016, SAT, FH Technikum Wien
* @license AGPL <http://www.gnu.org/licenses/agpl.txt>
*/
define(function (require, exports, module) {
require("apf/elements/codeeditor");
var ide = require("core/ide");
var ext = require("core/ext");
var dock = require("ext/dockpanel/dockpanel");
var commands = require("ext/commands/commands");
var fs = require("ext/filesystem/filesystem");
var markup = require("text!ext/embedded_debugger/embedded_debugger.xml");
var rev = require("ext/revisions/revisions_util");
var sources = require("ext/debugger/sources");
var c9console = require("ext/console/console");
var editors = require("ext/editors/editors");
var path, row;
/* global dbInteractive txtCode dbg
* dbgVariable pgDebugNav tabDebug dgVars*/
module.exports = ext.register("ext/embedded_debugger/embedded_debugger", {
name: "Embedded Debug",
dev: "SAT",
type: ext.GENERAL,
alone: true,
offline: false,
autodisable: ext.ONLINE | ext.LOCAL,
markup: markup,
buttonClassName: "debug1",
deps: [fs],
nodesAll: [],
nodes: [],
handlers: [],
hook: function () {
var _self = this;
/* Resume HW */
commands.addCommand({
name: "embeddedresume",
hint: "resume the current paused process",
bindKey: { mac: "Shift-F8", win: "Ctrl-F8" },
exec: function () {
_self.embedded_resume();
}
});
/* Suspend HW */
commands.addCommand({
name: "embeddedsuspend",
hint: "suspend the current paused process",
bindKey: { mac: "Shift-F9", win: "Ctrl-F9" },
exec: function () {
_self.embedded_suspend();
}
});
/* Stepinto HW */
commands.addCommand({
name: "embeddedstepinto",
hint: "step into the function that is next on the execution stack",
bindKey: { mac: "Shift-F11", win: "Ctrl-F11" },
exec: function () {
_self.embedded_resume("in");
}
});
/* Stepover HW */
commands.addCommand({
name: "embeddedstepover",
hint: "step over the current expression on the execution stack",
bindKey: { mac: "Shift-F10", win: "Ctrl-F10" },
exec: function () {
_self.embedded_resume("next");
}
});
/* Stepout HW */
commands.addCommand({
name: "embeddedstepout",
hint: "step out of the current function scope",
bindKey: { mac: "Shift-F12", win: "Ctrl-F12" },
exec: function () {
_self.embedded_resume("out");
}
});
/* Stop HW */
commands.addCommand({
name: "embeddedstop",
hint: "stop the debugging process",
bindKey: { mac: "Shift-F7", win: "Ctrl-F7" },
exec: function () {
_self.embedded_stop(true);
}
});
var name = "ext/embedded_debugger/embedded_debugger";
/* Add Dock buttons */
dock.addDockable({
expanded: -1,
width: 300,
sections: [
{
height: 30,
width: 150,
minHeight: 30,
noflex: true,
draggable: false,
resizable: false,
skin: "dockwin_runbtns",
noTab: true,
position: 1,
buttons: [{
id: "btnEmbeddedRunCommands",
caption: "Run Commands",
"class": "btn-runcommands",
ext: [name, "pgEmbeddedDebugNav"],
draggable: false,
hidden: true
}]
},
{
width: 380,
height: 300,
flex: 3,
buttons: [
{ caption: "Variables", ext: [name, "dbgEmbeddedVariable"], hidden: true }
]
}
]
});
/* Register dock panels */
dock.register(name, "pgEmbeddedDebugNav", {
menu: "Debugger",
primary: {
backgroundImage: ide.staticPrefix + "/ext/main/style/images/debugicons.png",
defaultState: { x: -6, y: -265 },
activeState: { x: -6, y: -265 }
}
}, function (type) {
ext.initExtension(_self);
return pgEmbeddedDebugNav;
});
dock.register(name, "dbgEmbeddedVariable", {
menu: "Debugger/Variables",
primary: {
backgroundImage: ide.staticPrefix + "/ext/main/style/images/debugicons.png",
defaultState: { x: -8, y: -174 },
activeState: { x: -8, y: -174 }
}
}, function (type) {
ext.initExtension(_self);
return dbgEmbeddedVariable;
});
},
init: function (amlNode) {
var _self = this;
/* Send additional request for restoring the debug variables, as this plug-in may be loaded after
* the embedded developer plug-in which results in missing debug variable entries when the IDE
* is initially loaded */
var data = {
command: "firmware",
"operation": "recoverDebugVariables",
requireshandling: true
};
ide.send(data);
/* Event Listener for added/activated/deactivated Breakpoints (also updates on file save !!!) */
mdlDbgBreakpoints.addEventListener("update", function (e) {
customBreakpoints = new Array();
/* Get the breakpoints */
var breakpoints = _self.getBreakPoints();
/* loop through breakpoints to get the filename and line number of the bp */
for (var i = 0; i < breakpoints.length; i++) {
var bppathtemp = breakpoints[i].path.replace("/workspace/", "");
var bppath = bppathtemp.substring(0, bppathtemp.indexOf('/src/')) + "/";
if (bppath == require("ext/embedded_developer/embedded_developer").getDebugPath() && breakpoints[i].enabled == true) {
var breakpointproperty = new Object();
breakpointproperty.filename = breakpoints[i].path.replace(/^.*\/(?=[^\/]*$)/, "");
breakpointproperty.line = breakpoints[i].line;
customBreakpoints.push(breakpointproperty);
}
}
/* Send the updated breakpoints to our server plugin */
var data = {
command: "firmware",
"operation": "updateBreakpoints",
"breakpoints": customBreakpoints,
requireshandling: true
};
ide.send(data);
});
/* Register Event listener to restore debug marker when switching
* tabs during debugging */
ide.addEventListener("init.ext/editors/editors", function (e) {
ide.addEventListener("tab.afterswitch", function (e) {
/* Retrieve the path to the current open/displayed file */
var page = tabEditors.getPage();
var pathTemp;
if (page && page.$model && page.$doc.getNode().getAttribute("ignore") !== "1") {
var prefixRegex = new RegExp("^" + ide.davPrefix);
pathTemp = "/workspace" + page.$model.data.getAttribute("path").replace(prefixRegex, "");
}
/* If the current open file is equal to the currently debugged file
* restore the debug marker */
if (pathTemp == path) {
/* Remove debug marker */
var amlEditor = editors.currentEditor && editors.currentEditor.amlEditor;
var session = amlEditor && amlEditor.$editor.session;
if (!session)
return;
session.$stackMarker && _self.removeDebugMarker(session, "stack");
session.$stepMarker && _self.removeDebugMarker(session, "step");
setTimeout(function () {
/* Jump to file at specified line. We have to do this twice as
* cloud9 ignores the show command when file is already open and
* the cursor on the right position. Due to a bug the cursor is internally at
* the right position but not correctly displayed at the right position */
sources.show({
path: path,
row: row + 1,
column: 0
});
sources.show({
path: path,
row: row,
column: 0
});
setTimeout(function () {
/* Update debug marker */
_self.updateDebugMarker(path, row, 0);
}, 100);
}, 100);
}
});
});
/* EventListener for socket messages */
ide.addEventListener("socketMessage", function (e) {
/* Gets the result about the debug variables from the last session*/
if (e.message.type == "result" && e.message.subtype[0] == "loadVariables") {
/* Initialize model */
mdlEmbeddedDebug.load('<data>\
</data>');
var debugVars = e.message.subtype[1];
/* Loop through received variables */
for (var i = 0; i < debugVars.length; i++) {
if (debugVars[i] != "") mdlEmbeddedDebug.appendXml('<embeddedvars name="' + debugVars[i] + '" value="unknown"></embeddedvars>');
}
}
/* Receives error if something went wrong when adding the variables from the list*/
if (e.message.type == "result" && e.message.subtype == "writeFileError") {
c9console.log("<div class='item console_log' style='font-weight:bold;color:#ff0000'>" + apf.escapeXML("Failure writing debug variables!") + "</div>");
}
/* Returns a message when GDB is running */
if (e.message.type == "result" && e.message.subtype == "gdb-ready") {
c9console.log("<div class='item console_log' style='font-weight:bold;color:#00ff00'>" + apf.escapeXML("Debugger is ready!") + "</div>");
}
/* Returns a message when GDB is not running */
if (e.message.type == "result" && e.message.subtype == "gdb-not-running") {
c9console.log("<div class='item console_log' style='font-weight:bold;color:#ff0000'>" + apf.escapeXML("Debugger is not running!") + "<br />" + apf.escapeXML("Run C-Developer/Embedded Developer ==> Debug.") + "</div>");
_self.manageDebugcontrols(true, true, true, true, true);
}
/* Returns a message when the GDB exits */
if (e.message.type == "result" && e.message.subtype == "gdb-exited") {
c9console.log("<div class='item console_log' style='font-weight:bold;color:#ff0000'>" + apf.escapeXML("Debugger exited!") + "</div>");
_self.manageDebugcontrols(true, true, true, true, true);
_self.embedded_stop(false);
}
/* Firmware flashing successful */
if (e.message.type == "result" && e.message.subtype == "firmware-flashing-success") _self.embedded_stop(false);
/* Gets the result about the next line when stepping through the code */
if (e.message.type == "result" && e.message.subtype[0] == "atFileLine") {
/* Set visibility of debug controls */
_self.manageDebugcontrols(true, false, true, true, true);
/* Get the file and line */
var atFileLine = e.message.subtype[1].toString().trim();
/* Get the current debug directory to identify the right file */
atFileLine = require("ext/embedded_developer/embedded_developer").getDebugPath() + atFileLine;
path = "/workspace/" + atFileLine.substring(0, atFileLine.indexOf(":"));
row = parseInt(atFileLine.substring(atFileLine.indexOf(":") + 1)) - 1;
/* Remove debug marker */
var amlEditor = editors.currentEditor && editors.currentEditor.amlEditor;
var session = amlEditor && amlEditor.$editor.session;
if (!session)
return;
session.$stackMarker && _self.removeDebugMarker(session, "stack");
session.$stepMarker && _self.removeDebugMarker(session, "step");
setTimeout(function () {
/* Jump to file at specified line */
sources.show({
path: path,
row: row,
column: 0
});
setTimeout(function () {
/* Update debug marker */
_self.updateDebugMarker(path, row, 0);
}, 100);
}, 100);
}
/* Receives error if something went wrong when adding the variables from the list */
if (e.message.type == "result" && e.message.subtype == "finish-not-meaningful") {
/* Set visibility of debug controls */
_self.manageDebugcontrols(true, false, true, true, true);
c9console.log("<div class='item console_log' style='font-weight:bold;color:#ff0000'>" + apf.escapeXML("Step \"finish\" not meaningful in the outermost frame.") + "</div>");
}
/* Gets a message of the value of a certain variable */
if (e.message.type == "result" && e.message.subtype[0] == "variableValue") {
var variable = e.message.subtype[1].toString().trim();
/* Replace possible < and > signs, e.g., when using optimized compiler options */
variable = variable.replace(/[\<\>]/g, "");
/* Get the name */
var variablename = variable.substring(0, variable.indexOf("=") - 1);
/* Get the value and replace every "" with '', because it's not conform with xml */
var variablevalue = variable.substring(variable.indexOf("=") + 2);
variablevalue = variablevalue.replace(/"/g, '\'');
/* Get xml representation of the debug variables */
var xml = mdlEmbeddedDebug.getXml();
var varsxml = xml.getElementsByTagName("embeddedvars");
/* Initialize model */
mdlEmbeddedDebug.load('<data>\
</data>');
/* Loop through the xml entries and append the edited values to it (Refreshed whole xml entries) */
for (var i = 0; i < varsxml.length; i++) {
if (varsxml[i].getAttribute("name") == variablename) varsxml[i].setAttribute("value", variablevalue);
mdlEmbeddedDebug.appendXml('<embeddedvars name="' + varsxml[i].getAttribute("name") + '" value="' + varsxml[i].getAttribute("value") + '"></embeddedvars>');
}
}
});
},
/* Gets all the settled breakpoints (+1 because the IDE counts from line 0 internally) */
getBreakPoints: function (argument) {
return mdlDbgBreakpoints.queryNodes("breakpoint").map(function (bp) {
return {
path: bp.getAttribute("path") || "",
line: parseInt(bp.getAttribute("line"), 10) + 1,
column: parseInt(bp.getAttribute("column"), 10) || 0,
enabled: bp.getAttribute("enabled") == "true",
condition: bp.getAttribute("condition") || "",
ignoreCount: bp.getAttribute("ignoreCount") || 0
};
});
},
/* Manages the visibility of the debug navigation controls */
manageDebugcontrols: function (resume, suspend, stepover, stepinto, stepout) {
if (resume == false) btnEmbeddedResume.disable();
else btnEmbeddedResume.enable();
if (suspend == false) btnEmbeddedSuspend.disable();
else btnEmbeddedSuspend.enable();
if (stepover == false) btnEmbeddedStepOver.disable();
else btnEmbeddedStepOver.enable();
if (stepinto == false) btnEmbeddedStepInto.disable();
else btnEmbeddedStepInto.enable();
if (stepout == false) btnEmbeddedStepOut.disable();
else btnEmbeddedStepOut.enable();
},
activate: function () {
ext.initExtension(this);
this.nodes.each(function (item) {
if (item.show)
item.show();
});
},
deactivate: function () {
this.nodes.each(function (item) {
if (item.hide)
item.hide();
});
},
enable: function () {
if (!this.disabled) return;
this.nodesAll.each(function (item) {
item.setProperty("disabled", item.$lastDisabled !== undefined ? item.$lastDisabled : true);
delete item.$lastDisabled;
});
this.disabled = false;
},
disable: function () {
if (this.disabled) return;
/* stop debugging */
/* require('ext/runpanel/runpanel').stop(); */
this.deactivate();
/* loop from each item of the plugin and disable it */
this.nodesAll.each(function (item) {
if (!item.$lastDisabled)
item.$lastDisabled = item.disabled;
item.disable();
});
this.disabled = true;
},
destroy: function () {
commands.removeCommandsByName(
["embeddedresume", "embeddedstepinto", "embeddedstepover", "embeddedstepout"]);
this.nodes.each(function (item) {
dock.unregisterPage(item);
});
tabEmbeddedDebug.destroy(true, true);
this.$layoutItem.destroy(true, true);
this.$destroy();
},
/* Adds a marker to the editor at the line the debugger is halted */
addDebugMarker: function (session, type, row) {
var marker = session.addMarker(new Range(row, 0, row + 1, 0), "ace_" + type, "line", true);
session.addGutterDecoration(row, type);
session["$" + type + "Marker"] = { lineMarker: marker, row: row };
},
/* Removes the marker from the editor */
removeDebugMarker: function (session, type) {
var markerName = "$" + type + "Marker";
session.removeMarker(session[markerName].lineMarker);
session.removeGutterDecoration(session[markerName].row, type);
session[markerName] = null;
},
/* Updates the position of the debug marker */
updateDebugMarker: function (path, row, column) {
var amlEditor = editors.currentEditor && editors.currentEditor.amlEditor;
var session = amlEditor && amlEditor.$editor.session;
if (!session || !path || !row)
return;
session.$stackMarker && this.removeDebugMarker(session, "stack");
session.$stepMarker && this.removeDebugMarker(session, "step");
var editorPath = amlEditor.xmlRoot.getAttribute("path");
this.addDebugMarker(session, "step", row);
},
/* Resumes the HW */
embedded_resume: function (stepaction, stepcount, callback) {
var data;
/* Step into */
if (stepaction == "in") {
data = {
command: "firmware",
"operation": "stepinto",
requireshandling: true
};
ide.send(data);
this.manageDebugcontrols(false, true, false, false, false);
}
/* Step over*/
else if (stepaction == "next") {
data = {
command: "firmware",
"operation": "stepover",
requireshandling: true
};
ide.send(data);
this.manageDebugcontrols(false, true, false, false, false);
}
/* Step out */
else if (stepaction == "out") {
data = {
command: "firmware",
"operation": "stepout",
requireshandling: true
};
ide.send(data);
this.manageDebugcontrols(false, true, false, false, false);
}
/* Continue */
else {
data = {
command: "firmware",
"operation": "continue",
requireshandling: true
};
ide.send(data);
this.manageDebugcontrols(false, true, false, false, false);
}
},
/* Suspends the HW */
embedded_suspend: function () {
var data = {
command: "firmware",
"operation": "suspend",
requireshandling: true
};
ide.send(data);
this.manageDebugcontrols(true, false, true, true, true);
},
/* Stops the HW */
embedded_stop: function (fromUi) {
var data = {
command: "firmware",
"operation": "stop",
requireshandling: true
};
if (fromUi == true) {
data = {
command: "firmware",
"operation": "stop",
"fromui": fromUi,
requireshandling: true
};
}
ide.send(data);
data = {
command: "firmware",
"operation": "kill",
requireshandling: true
};
ide.send(data);
this.manageDebugcontrols(true, true, true, true, true);
require("ext/embedded_developer/embedded_developer").setDebuggerStopped();
/* Remove debug marker */
var amlEditor = editors.currentEditor && editors.currentEditor.amlEditor;
var session = amlEditor && amlEditor.$editor.session;
if (!session)
return;
session.$stackMarker && this.removeDebugMarker(session, "stack");
session.$stepMarker && this.removeDebugMarker(session, "step");
path = null;
},
/* Adds variables to the debug interface */
addEmbeddedDebugVariable: function () {
var xml = mdlEmbeddedDebug.getXml();
var vars = xml.getElementsByTagName("embeddedvars");
if (vars.length == 0){
/* Initialize model */
mdlEmbeddedDebug.load('<data>\
</data>');
}
/* Flag when an entry matches */
var matching = false;
for (var i = 0; i < vars.length; i++) {
/* Check for duplicate entries. */
if (vars[i].getAttribute("name") == tbAddDebugVariables.value.trim()) matching = true;
}
/* If there was no match, send the new variable to the server and append it to the current datagrid model */
if (tbAddDebugVariables.value.trim() != "" && matching == false) {
var data = {
command: "firmware",
"operation": "addDebugVariable",
"variablename": tbAddDebugVariables.value.trim(),
requireshandling: true
};
ide.send(data);
/* Append the variable to the model */
mdlEmbeddedDebug.appendXml('<embeddedvars name="' + tbAddDebugVariables.value.trim() + '" value="unknown"></embeddedvars>');
data = {
command: "firmware",
"operation": "saveDebugVariables",
"debugVariableToSave": tbAddDebugVariables.value.trim(),
requireshandling: true
};
ide.send(data);
}
},
/* Removes a variable from the view and the session file to not show anymore */
removeEmbeddedDebugVariable: function () {
mdlEmbeddedDebug.removeXml(dgEmbeddedVars.getSelection()[0]);
var data = {
command: "firmware",
"operation": "removeDebugVariables",
"debugVariableToDelete": dgEmbeddedVars.getSelection()[0].getAttribute("name"),
requireshandling: true
};
ide.send(data);
},
/* Removes all variables from the view */
removeEmbeddedDebugVariablesFromView: function () {
if(typeof dgEmbeddedVars != "undefined" && typeof mdlEmbeddedDebug != "undefined"){
dgEmbeddedVars.clear();
/* Initialize model */
mdlEmbeddedDebug.load('<data>\
</data>');
}
}
});
});
| agpl-3.0 |
juju/juju | upgrades/steps_2919.go | 445 | // Copyright 2021 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package upgrades
// stateStepsFor2919 returns upgrade steps for juju 2.9.19
func stateStepsFor2919() []Step {
return []Step{
&upgradeStep{
description: `migrate legacy cross model tokens`,
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return context.State().MigrateLegacyCrossModelTokens()
},
},
}
}
| agpl-3.0 |
renderpci/dedalo-4 | lib/pdfjs/lib/shared/compatibility.js | 4827 | /**
* @licstart The following is the entire license notice for the
* Javascript code in this page
*
* Copyright 2018 Mozilla Foundation
*
* 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.
*
* @licend The above is the entire license notice for the
* Javascript code in this page
*/
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var globalScope = require('./global_scope');
if (!globalScope._pdfjsCompatibilityChecked) {
globalScope._pdfjsCompatibilityChecked = true;
var isNodeJS = require('./is_node');
var hasDOM = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object';
(function checkNodeBtoa() {
if (globalScope.btoa || !isNodeJS()) {
return;
}
globalScope.btoa = function (chars) {
return Buffer.from(chars, 'binary').toString('base64');
};
})();
(function checkNodeAtob() {
if (globalScope.atob || !isNodeJS()) {
return;
}
globalScope.atob = function (input) {
return Buffer.from(input, 'base64').toString('binary');
};
})();
(function checkCurrentScript() {
if (!hasDOM) {
return;
}
if ('currentScript' in document) {
return;
}
Object.defineProperty(document, 'currentScript', {
get: function get() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
},
enumerable: true,
configurable: true
});
})();
(function checkChildNodeRemove() {
if (!hasDOM) {
return;
}
if (typeof Element.prototype.remove !== 'undefined') {
return;
}
Element.prototype.remove = function () {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
};
})();
(function checkDOMTokenListToggle() {
if (!hasDOM || isNodeJS()) {
return;
}
var div = document.createElement('div');
if (div.classList.toggle('test', 0) === false) {
return;
}
var originalDOMTokenListToggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function (token) {
if (arguments.length > 1) {
var force = !!arguments[1];
return this[force ? 'add' : 'remove'](token), force;
}
return originalDOMTokenListToggle(token);
};
})();
(function checkStringIncludes() {
if (String.prototype.includes) {
return;
}
require('core-js/fn/string/includes');
})();
(function checkArrayIncludes() {
if (Array.prototype.includes) {
return;
}
require('core-js/fn/array/includes');
})();
(function checkObjectAssign() {
if (Object.assign) {
return;
}
require('core-js/fn/object/assign');
})();
(function checkMathLog2() {
if (Math.log2) {
return;
}
Math.log2 = require('core-js/fn/math/log2');
})();
(function checkNumberIsNaN() {
if (Number.isNaN) {
return;
}
Number.isNaN = require('core-js/fn/number/is-nan');
})();
(function checkNumberIsInteger() {
if (Number.isInteger) {
return;
}
Number.isInteger = require('core-js/fn/number/is-integer');
})();
(function checkPromise() {
if (globalScope.Promise) {
return;
}
globalScope.Promise = require('core-js/fn/promise');
})();
(function checkWeakMap() {
if (globalScope.WeakMap) {
return;
}
globalScope.WeakMap = require('core-js/fn/weak-map');
})();
(function checkStringCodePointAt() {
if (String.codePointAt) {
return;
}
String.codePointAt = require('core-js/fn/string/code-point-at');
})();
(function checkStringFromCodePoint() {
if (String.fromCodePoint) {
return;
}
String.fromCodePoint = require('core-js/fn/string/from-code-point');
})();
(function checkSymbol() {
if (globalScope.Symbol) {
return;
}
require('core-js/es6/symbol');
})();
(function checkObjectValues() {
if (Object.values) {
return;
}
Object.values = require('core-js/fn/object/values');
})();
} | agpl-3.0 |
beast-dev/beast-mcmc | src/dr/evolution/datatype/HiddenNucleotides.java | 2685 | /*
* NewHiddenNucleotides.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evolution.datatype;
/**
* @author Marc A. Suchard
*/
public class HiddenNucleotides extends Nucleotides implements HiddenDataType {
public static final String DESCRIPTION = "hiddenNucleotide";
static final HiddenNucleotides NUCLEOTIDE_HIDDEN_1 = new HiddenNucleotides(1);
static final HiddenNucleotides NUCLEOTIDE_HIDDEN_2 = new HiddenNucleotides(2);
static final HiddenNucleotides NUCLEOTIDE_HIDDEN_3 = new HiddenNucleotides(3);
static final HiddenNucleotides NUCLEOTIDE_HIDDEN_4 = new HiddenNucleotides(4);
static final HiddenNucleotides NUCLEOTIDE_HIDDEN_8 = new HiddenNucleotides(8);
/**
* Private constructor - DEFAULT_INSTANCE provides the only instance
*/
private HiddenNucleotides(int hiddenClassCount) {
super();
this.hiddenClassCount = hiddenClassCount;
}
/**
* returns an array containing the non-ambiguous states that this state represents.
*/
public boolean[] getStateSet(int state) {
return HiddenDataType.Utils.getStateSet(state, stateCount, hiddenClassCount, Nucleotides.INSTANCE);
}
public String getCode(int state) {
return HiddenDataType.getCodeImpl(state, stateCount, super::getCode);
}
public String getCodeWithoutHiddenState(int state) {
return HiddenDataType.getCodeWithoutHiddenStateImpl(state, stateCount, super::getCode);
}
public int getStateCount() {
return stateCount * hiddenClassCount;
}
private int hiddenClassCount;
public int getHiddenClassCount() {
return hiddenClassCount;
}
public String getDescription() {
return DESCRIPTION + hiddenClassCount;
}
} | lgpl-2.1 |
iklim/essencia | src/main/resources/genericfaces/Record.ejs.js | 380 | var Record = function(objectId, className){
this.objectId = objectId;
this.className = className;
}
Record.prototype = {
toggleChild : function(element){
// Checks for display:[none|block], ignores visible:[true|false]
if($(element).parent().next().is(":visible")){
$(element).html("+");
}else{
$(element).html("-");
}
$(element).parent().next().toggle();
}
} | lgpl-2.1 |
sugchand/neoview-middle-box | src/nvrelay/relay_handler.py | 18264 | '''
Created on 10 Sep 2016
@author: sugesh
'''
#! /usr/bin/python3
# -*- coding: utf8 -*-
# The camera handler module for nv-middlebox.
#
__author__ = "Sugesh Chandran"
__copyright__ = "Copyright (C) The neoview team."
__license__ = "GNU Lesser General Public License"
__version__ = "1.0"
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from src.settings import NV_MID_BOX_CAM_STREAM_DIR
from src.nvdb.nvdb_manager import db_mgr_obj
from src.nv_logger import nv_logger
from src.nv_lib.nv_os_lib import nv_os_lib
from src.nv_lib.nv_sync_lib import GBL_NV_SYNC_OBJ
from src.settings import NV_CAM_VALID_FILE_SIZE_MB
from src.nv_lib.nv_time_lib import nv_time
from src.settings import NV_CAM_CONN_TIMEOUT
import queue
from src.nv_lib.ipc_data_obj import camera_data, enum_ipcOpCode
from src.nv_lib.nv_sync_lib import GBL_CONF_QUEUE
from src.nvdb.nvdb_manager import enum_camStatus
class relay_queue_mgr():
'''
Class to manage files to copy. It maintain one queue per camera stream.
'''
def __init__(self):
'''
Dictionary to hold the different queues. the dictionary will be looks
like
cam_stream_queue_dic = {
'camera1' : [queue1, camera_timer_obj]
'camera2' : [queue2, camera_timer_obj]
.....
}
the queues are holding the series of file-pairs. for eg:
queue1 = <[src1, dst1], [src2. dst2], ....>
camera_timer_obj is used to determine the liveness of camera. If a
camera generates invalid streams(less than valid size) continuously
for a period(NV_CAM_CONN_TIMEOUT), then the camera will move to
disconnected state.
'''
self.nv_log_handler = nv_logger(self.__class__.__name__).get_logger()
self.cam_stream_queue_dic = {}
def enqueue_file_pair(self, cam_name, src, dst):
if not cam_name in self.cam_stream_queue_dic:
# There is no queue for specific camera, create it.
rel_queue = queue.Queue()
cam_timeobj = nv_time(timeout=NV_CAM_CONN_TIMEOUT)
self.cam_stream_queue_dic[cam_name] = [rel_queue, cam_timeobj]
else:
[rel_queue,cam_timeobj] = self.cam_stream_queue_dic[cam_name]
rel_queue.put([src, dst])
def dequeue_file_pair(self, cam_name):
if not cam_name in self.cam_stream_queue_dic:
self.nv_log_handler.debug("Cannot dequeue from a non-existent queue"
": %s" % cam_name)
return [None, None]
[rel_queue,_] = self.cam_stream_queue_dic[cam_name]
if rel_queue.empty():
self.nv_log_handler.debug("Cannot dequeue from a empty queue")
return [None, None]
return rel_queue.get()
def dequeue_file_pair_with_timeout(self, cam_name):
'''
Function to return the file pair to copy from queue along with the
timeobj. The timeobj stores the last time a proper video stream is
generated.
@returns [[file-src, file-dst], timeobj]
'''
file_list = self.dequeue_file_pair(cam_name)
if all(x is None for x in file_list):
return[file_list, None]
[_, timeobj] = self.cam_stream_queue_dic[cam_name]
return[file_list, timeobj]
class relay_ftp_handler():
'''
the relay handler class to do the file copying from middlebox to webserver.
'''
MB_SIZE = 1000000 # Bytes #
NV_CAM_VALID_FILE_SIZE = NV_CAM_VALID_FILE_SIZE_MB * MB_SIZE
def __init__(self):
self.nv_log_handler = nv_logger(self.__class__.__name__).get_logger()
self.os_context = nv_os_lib()
self.websrv = None
self.sftp = None
self.queue_mgr = relay_queue_mgr()
def notify_camera_disconnect(self, cam_name):
'''
Function to move the camera to disconnected state.
'''
# Stop the livestreaming thread if its running.
cam_live = camera_data(op = enum_ipcOpCode.CONST_STOP_CAMERA_LIVESTREAM,
name = cam_name,
status = None,
# Everything else is None.
ip = None,
macAddr = None,
port = None,
time_len = None,
uname = None,
pwd = None,
desc = None
)
try:
GBL_CONF_QUEUE.enqueue_data(obj_len = 1,
obj_value = [cam_live])
self.nv_log_handler.info("Live streaming on camera %s is stopped",
cam_name)
except Exception as e:
self.nv_log_handler.error("Failed to stop live streaming in %s"
", exception : %s", e)
# Stop the camera stream first, before making it to disconnected.
cam_ipcStopData = camera_data(op = enum_ipcOpCode.CONST_STOP_CAMERA_STREAM_OP,
name = cam_name,
status = None,
# Everything else is None.
ip = None,
macAddr = None,
port = None,
time_len = None,
uname = None,
pwd = None,
desc = None
)
cam_ipcData = camera_data(op = enum_ipcOpCode.CONST_UPDATE_CAMERA_STATUS,
name = cam_name,
status = enum_camStatus.CONST_CAMERA_DISCONNECTED,
# Everything else is None.
ip = None,
macAddr = None,
port = None,
time_len = None,
uname = None,
pwd = None,
desc = None
)
try:
GBL_CONF_QUEUE.enqueue_data(obj_len = 1,
obj_value = [cam_ipcStopData])
GBL_CONF_QUEUE.enqueue_data(obj_len = 1, obj_value = [cam_ipcData])
self.nv_log_handler.info("Camera %s is disconnected", cam_name)
except Exception as e:
self.nv_log_handler.error("Failed to change the camera status"
"to disconnected state :, %s", e)
def is_file_to_copy_valid(self, file_path, cam_name, timeobj):
'''
Function to validate if the file_path is a corrupted file or not.
For now we assume if the file size is greater than 10MB its good to go,
though its not an right assumption.
'''
file_size = self.os_context.get_filesize_in_bytes(file_path)
if file_size < relay_ftp_handler.NV_CAM_VALID_FILE_SIZE:
# Validate when the last valid file is generated by the camera
# If its not in the timeout period, notify to move the camera to
# a disconnected state.
if timeobj.is_time_elpased():
self.notify_camera_disconnect(cam_name)
return False
# Update the time value if the filesize is valid.
timeobj.update_time()
return True
def enqeue_copy_file_list(self, cam_name, src, dst):
'''
NOTE :::
The assumption here is copying of file must be faster than getting a file
generated.
Relay agent trigger a copy operation for every file created by middle
box streaming thread. Copying a file immediately on creation causes data
loss/corruption as the file generation is not complete.
The enqueue mechanism take care of it by copying a file only after the
creation is complete. On creation files are enqueued and real copying is
happen only at the time of second file creation.
'''
[file_list, time_obj] = \
self.queue_mgr.dequeue_file_pair_with_timeout(cam_name)
[cp_src, cp_dst] = file_list
self.queue_mgr.enqueue_file_pair(cam_name, src, dst)
if cp_src is None or cp_dst is None:
return [None, None]
if not self.is_file_to_copy_valid(cp_src, cam_name, time_obj):
self.nv_log_handler.info("%s file size less than %dMB, "
"Not copying to webserver",
cp_src,
NV_CAM_VALID_FILE_SIZE_MB)
return [None, None]
return [cp_src, cp_dst]
def local_file_transfer(self, nv_cam_src, websrv):
try:
# Copy the file nv_cam_src to dst.
if not self.is_media_file(nv_cam_src):
self.nv_log_handler.error("%s is not a media file, Do not copy" % \
nv_cam_src)
return
if not self.websrv:
self.websrv = websrv
dst_path = websrv.video_path
# Get the absolute path directory name of the file.
cam_src_dir = self.os_context.get_dirname(nv_cam_src)
# Find the camera folder name in the absolute path.
cam_src_dir = self.os_context.get_last_filename(cam_src_dir)
dst_dir = self.os_context.join_dir(dst_path, cam_src_dir)
if not self.os_context.is_path_exists(dst_dir):
self.nv_log_handler.debug("Create the directory %s" % dst_dir)
self.os_context.make_dir(dst_dir)
file_pair = self.enqeue_copy_file_list(cam_src_dir, nv_cam_src, dst_dir)
cp_src = file_pair[0]
cp_dst = file_pair[1]
if cp_src is None or cp_dst is None:
return
self.nv_log_handler.debug("Copying file %s to %s"% \
(cp_src, cp_dst))
self.os_context.copy_file(cp_src, cp_dst)
except Exception as e:
self.nv_log_handler.debug("Failed to copy file to webserver %s", e)
def remote_file_transfer(self, nv_cam_src, websrv):
try:
# Copy the file remotely using scp/sftp.
if not self.is_media_file(nv_cam_src):
self.nv_log_handler.debug("%s is not a media file, Do not copy" % \
nv_cam_src)
return
if not self.websrv:
self.websrv = websrv
try:
self.sftp = self.os_context.get_remote_sftp_connection(
hostname = websrv.name,
username = websrv.uname,
pwd = websrv.pwd)
except Exception as e:
self.nv_log_handler.error("Failed to establish remote ssh "
"connection to webserver, copying failed %s", e)
self.sftp = None
return
if not self.sftp:
self.nv_log_handler.error("SFTP failed, cannot copy media.")
return
dst_path = websrv.video_path
# Get the absolute path directory name of the file.
cam_src_dir = self.os_context.get_dirname(nv_cam_src)
# Find the camera folder name in the absolute path.
cam_src_dir = self.os_context.get_last_filename(cam_src_dir)
dst_dir = self.os_context.join_dir(dst_path, cam_src_dir)
if not self.os_context.is_remote_path_exists(self.sftp, dst_dir):
self.nv_log_handler.debug("Create the remote directory %s" % dst_dir)
self.os_context.remote_make_dir(self.sftp, dir_name = dst_dir)
file_pair = self.enqeue_copy_file_list(cam_src_dir, nv_cam_src, dst_dir)
cp_src = file_pair[0]
cp_dst = file_pair[1]
if cp_src is None or cp_dst is None:
return
self.nv_log_handler.debug("Copying file %s to %s remotely"% \
(cp_src, cp_dst))
self.os_context.remote_copy_file(self.sftp,cp_src, cp_dst)
except Exception as e:
self.nv_log_handler.debug("Failed to remote copy file to webserver"
"%s", e)
def is_webserver_local(self, webserver):
'''
Check if the webserver deployed on the same machine.
Returns:
True : Middlebox and webserver on the same machine
False : Webserver deployed on a different machine
'''
if webserver.name == 'localhost':
return True
return False
def is_media_file(self, file_path):
'''
Check if the file is media
'''
file_ext = '.mp4'
return file_path.endswith(file_ext)
def kill_ftp_session(self):
self.os_context.close_remote_sftp_connection()
self.os_context.close_remote_host_connection()
self.nv_log_handler.debug("Closing the ftp session..")
pass
RELAY_MUTEX_NAME = "relay_watcher_mutex"
class relay_watcher(FileSystemEventHandler):
'''
The watcher notified when a file change event happened.
'''
def __init__(self):
self.nv_log_handler = nv_logger(self.__class__.__name__).get_logger()
self.websrv = None
self.ftp_obj = relay_ftp_handler()
self.is_relay_thread_killed = False # flag for tracking user kill.
def kill_relay_thread(self):
'''
Function to kill the relay thread gracefully. It waits until the thread
completes the current execution before initiate the kill.
'''
self.nv_log_handler.debug("Stopping the relay thread..")
self.is_relay_thread_killed = True
GBL_NV_SYNC_OBJ.mutex_lock(RELAY_MUTEX_NAME)
# Wait until current relay thread completes its processing.
try:
self.ftp_obj.kill_ftp_session()
except:
self.nv_log_handler.error("Failed to close the ftp session properly")
finally:
GBL_NV_SYNC_OBJ.mutex_unlock(RELAY_MUTEX_NAME)
def is_relay_thread_active(self):
'''
XXX :: Any relay thread operation must check/call this function
before doing any kind of operation. This function returns whether
the control thread/user issues a kill signal. The check must avoids
unnecessary long wait for the kill signal execution.
'''
return self.is_relay_thread_killed
def process(self, event):
"""
event.event_type
'modified' | 'created' | 'moved' | 'deleted'
event.is_directory
True | False
event.src_path
path/to/observed/file
"""
pass
# the file will be processed there
# print(event.src_path, event.event_type) # print now only for degug
#def on_modified(self, event):
# self.process(event)
def on_created(self, event):
'''
On a file creation, change the thread state to busy to avoid premature
thread close. Close the thread only when there is no event to be
handled.
'''
if(self.is_relay_thread_active()):
#Kill signal issued, nothing to do.
self.nv_log_handler.debug("Kill signal issued, no file copy")
return
GBL_NV_SYNC_OBJ.mutex_lock(RELAY_MUTEX_NAME)
try:
# Check if the webserver local, copy the file to a specified location
self.websrv = db_mgr_obj.get_webserver_record()
if not self.websrv:
self.nv_log_handler.error("Webserver is not configured")
return
is_local_wbs = self.ftp_obj.is_webserver_local(self.websrv)
if is_local_wbs:
cam_src_path = event.src_path
self.ftp_obj.local_file_transfer(cam_src_path, self.websrv)
else:
# The server is remote and need to do the scp over network
self.ftp_obj.remote_file_transfer(event.src_path, self.websrv)
except:
raise
finally:
# self.process(event)
GBL_NV_SYNC_OBJ.mutex_unlock(RELAY_MUTEX_NAME)
#def on_deleted(self,event):
# self.process(event)
#def on_any_event(self,event):
# self.process(event)
class relay_main():
'''
The relay main thread class for the file event handling.
NOTE :: THIS THREAD SHOULDNT HOLD ANY LOCK OR ENTER INTO CRITICAL SECTION
BY BLOCKING OTHER THREADS. ITS POSSIBLE THIS THREAD GET KILLED BY MAIN
THREAD ANYTIME. HOLDING A CRITICAL SECTION RESOURCE IN THIS MODULE LEADS
A DEAD LOCK.
'''
def __init__(self):
self.nv_log_handler = nv_logger(self.__class__.__name__).get_logger()
self.os_context = nv_os_lib()
self.watcher_obj = relay_watcher()
self.observer_obj = Observer()
def process_relay(self):
try:
if not self.os_context.is_path_exists(NV_MID_BOX_CAM_STREAM_DIR):
self.nv_log_handler.error("%s Directory not found",
NV_MID_BOX_CAM_STREAM_DIR)
raise FileNotFoundError
self.observer_obj.schedule(self.watcher_obj, NV_MID_BOX_CAM_STREAM_DIR,
recursive=True)
self.observer_obj.start()
except FileNotFoundError:
raise
except Exception as e:
raise e
def relay_stop(self):
self.watcher_obj.kill_relay_thread()
self.observer_obj.stop()
def relay_join(self):
if self.observer_obj.isAlive():
self.observer_obj.join()
| lgpl-2.1 |
TheHunter/WcfExtensions | WcfExtensions.net40/Properties/AssemblyInfo.cs | 1423 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WcfExtensions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The hunter company")]
[assembly: AssemblyProduct("WcfExtensions")]
[assembly: AssemblyCopyright("Licensed under LGPL")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bae0dee2-666d-45a8-bc9a-15a9b84433d3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.10")]
[assembly: AssemblyFileVersion("1.1.1.10")]
| lgpl-2.1 |
kevin-chen-hw/LDAE | com.huawei.soa.ldae/src/main/java/org/hibernate/procedure/ParameterStrategyException.java | 1299 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.procedure;
import org.hibernate.HibernateException;
/**
* @author Steve Ebersole
*/
public class ParameterStrategyException extends HibernateException {
public ParameterStrategyException(String message) {
super( message );
}
}
| lgpl-2.1 |
Foeskes/Stats-Detector-Mod | src/main/java/com/foeskes/statsdetector/item/ItemGunDetectorNeutral.java | 1653 | package com.foeskes.statsdetector.item;
import com.foeskes.statsdetector.StatsDetector;
import com.foeskes.statsdetector.projectiles.EntityDetectorRay2;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.world.World;
public class ItemGunDetectorNeutral extends Item {
public ItemGunDetectorNeutral() {
super();
this.setCreativeTab(StatsDetector.tab);
this.setRegistryName(StatsDetector.MODID, "detector_gun_neutral");
this.setMaxDamage(1200);
this.setUnlocalizedName("detector_gun_neu");
this.setMaxStackSize(1);
}
@Override
public boolean hasEffect(ItemStack stack) {
return true;
}
@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn,
EnumHand hand) {
EntityDetectorRay2 ray = new EntityDetectorRay2(worldIn, playerIn, false);
ray.setHeadingFromThrower(playerIn, playerIn.rotationPitch, playerIn.rotationYaw, 0.0F, 1.5F, 1.0F);
worldIn.playSound(playerIn, playerIn.getPosition(), SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.PLAYERS, 10, 2.1f);//Explosion
playerIn.getCooldownTracker().setCooldown(this, 20);
if (!worldIn.isRemote) {
worldIn.spawnEntityInWorld(ray);
}
return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand);
}
@Override
public EnumAction getItemUseAction(ItemStack stack) {
return EnumAction.BOW;
}
}
| lgpl-2.1 |
d-plaindoux/rapido | src/main/scala/smallibs/rapido/lang/syntax/parser.scala | 5462 | /*
* Copyright (C)2014 D. Plaindoux.
*
* This program 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, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package smallibs.rapido.lang.syntax
import scala.util.matching.Regex
import scala.util.parsing.combinator.{PackratParsers, JavaTokenParsers}
import smallibs.rapido.lang.ast._
object RapidoParser extends JavaTokenParsers with PackratParsers {
//
// Public behaviors
//
def specifications: PackratParser[List[Entity]] =
specification.*
def specification: PackratParser[Entity] =
positioned(typeSpecification | serviceSpecification | clientSpecification)
def typeSpecification: PackratParser[Entity] =
("type" ~> ident <~ "=") ~! extensible ^^ {
case n ~ t => TypeEntity(n, t)
}
def serviceSpecification: PackratParser[Entity] =
("service" ~> ident) ~ ("(" ~> repsep(identified, ",") <~ ")").? ~! path ~ ("{" ~> serviceDefinition.* <~ "}") ^^ {
case n ~ None ~ r ~ l => ServiceEntity(n, Route(n, Nil, r), l)
case n ~ Some(p) ~ r ~ l => ServiceEntity(n, Route(n, p, r), l)
}
def clientSpecification: PackratParser[Entity] =
("client" ~> ident) ~! ("provides" ~> repsep(ident, ",")) ^^ {
case n ~ l => ClientEntity(n, l)
}
//
// Internal behaviors
//
def routeParameter: PackratParser[(String, Type)] =
(ident <~ ":") ~! typeDefinition ^^ {
case n ~ t => (n, t)
}
def typeDefinition: PackratParser[Type] =
(atomic | array | extensible) ~ ("*" | "?").? ^^ {
case t ~ None => t
case t ~ Some("*") => TypeMultiple(t)
case t ~ Some("?") => TypeOptional(t)
}
private def directive(name: String): PackratParser[TypeRecord] =
name ~> "[" ~> identified <~ "]"
def serviceDefinition: PackratParser[Service] =
positioned((ident <~ ":") ~! (repsep(identified, ",") <~ "=>") ~ identified ~ ("or" ~> identified).? ~ ("=" ~> restAction) ~
path.? ~ directive("HEADER").? ~ directive("PARAMS").? ~ directive("BODY").? ^^ {
case name ~ in ~ out ~ err ~ action ~ path ~ header ~ param ~ body =>
Service(name, Action(action, path, param, body, header), ServiceType(in, out, err))
})
def restAction: PackratParser[Operation] =
("GET" | "POST" | "PUT" | "DELETE" | ident) ^^ {
case "GET" => GET
case "HEAD" => HEAD
case "POST" => POST
case "PUT" => PUT
case "DELETE" => DELETE
case name => UserDefine(name)
}
class Terminal(s: String) {
def produces(t: Type): PackratParser[Type] = s ^^ {
_ => t
}
}
object Terminal {
def apply(s: String): Terminal = new Terminal(s)
}
def number: PackratParser[Type] =
Terminal("int") produces TypeNumber
def string: PackratParser[Type] =
Terminal("string") produces TypeString
def boolean: PackratParser[Type] =
Terminal("bool") produces TypeBoolean
def identified: PackratParser[TypeRecord] =
ident ^^ {
TypeIdentifier
}
def attributeName: PackratParser[String] =
ident | ("\"" ~> regex(new Regex("[^\"]+")) <~ "\"") | ("'" ~> regex(new Regex("[^\']+")) <~ "'")
def getterSetter: PackratParser[Option[String] => Access] =
"@" ~ "get" ^^ {
_ => GetAccess
} | "@" ~ "set" ^^ {
_ => SetAccess
} | ("@" ~ "{" ~ (("set" ~ "," ~ "get") | ("get" ~ "," ~ "set")) ~ "}") ^^ {
_ => SetGetAccess
}
def attribute: PackratParser[(String, TypeAttribute)] =
((getterSetter ~ ("(" ~> ident <~ ")").?).? ~ attributeName <~ ":") ~! typeDefinition ^^ {
case None ~ i ~ t => (i, ConcreteTypeAttribute(None, t))
case Some(g ~ n) ~ i ~ t => (i, ConcreteTypeAttribute(Some(g(n)), t))
}
def virtual: PackratParser[(String, VirtualTypeAttribute)] =
("virtual" ~> attributeName) ~ ("=" ~> path) ^^ {
case i ~ p => (i, VirtualTypeAttribute(p))
}
def record: PackratParser[TypeRecord] =
"{" ~> repsep(virtual | attribute, (";" | ",").?) <~ "}" ^^ {
l => TypeObject(l.toMap)
}
def array: PackratParser[TypeMultiple] =
"[" ~> typeDefinition <~ "]" ^^ {
t => TypeMultiple(t)
}
def atomic: PackratParser[Type] =
number | string | boolean
def extensible: PackratParser[TypeRecord] =
(record | identified) ~ ("with" ~> extensible).* ^^ {
case t ~ l => l.foldLeft(t) {
TypeComposed
}
}
def path: PackratParser[Path] =
"[" ~> (variableEntry | staticEntry).+ <~ "]" ^^ {
case l => Path(for (e <- l if e != StaticLevel("")) yield e)
}
def staticEntry: PackratParser[PathEntry] =
regex(new Regex("[^<\\]]+")) ^^ {
StaticLevel
}
def variableEntry: PackratParser[PathEntry] =
"<" ~> repsep(regex(new Regex("[^.>]+")), ".") <~ ">" ^^ {
DynamicLevel
}
protected override val whiteSpace = """(\s|//.*|(?m)/\*(\*(?!/)|[^*])*\*/)+""".r
}
| lgpl-2.1 |
jkinner/ringside | social/vendor/shindig/includes/shindig/gadgets/ContainerConfig.php | 4539 | <?php
class ContainerConfig {
public $default_container = 'default';
public $container_key = 'gadgets.container';
private $config = array();
public function __construct($defaultContainer)
{
if (! empty($defaultContainer)) {
$this->loadContainers($defaultContainer);
}
}
private function loadContainers($containers)
{
if (! file_exists($containers) || ! is_dir($containers)) {
throw new Exception("Invalid container path");
}
foreach ( glob("$containers/*.js") as $file ) {
if (! is_readable($file)) {
throw new Exception("Could not read container config: $file");
}
if (is_dir($file)) {
// support recursive loading of sub directories
$this->loadContainers($file);
} else {
$this->loadFromFile($file);
}
}
}
private function loadFromFile($file)
{
$contents = file_get_contents($file);
// remove all comments (both /* */ and // style) because this confuses the json parser
// note: the json parser also crashes on trailing ,'s in records so please don't use them
$contents = preg_replace('/\/\/.*$/m', '', preg_replace('@/\\*(?:.|[\\n\\r])*?\\*/@', '', $contents));
$config = json_decode($contents, true);
if (! isset($config[$this->container_key][0])) {
throw new Exception("No gadgets.container value set for ");
}
$container = $config[$this->container_key][0];
$this->config[$container] = array();
foreach ( $config as $key => $val ) {
$this->config[$container][$key] = $val;
}
}
public function getConfig($container, $name)
{
$config = array();
if (isset($this->config[$container]) && isset($this->config[$container][$name])) {
$config = $this->config[$container][$name];
}
if ($container != $this->default_container && isset($this->config[$container][$name])) {
$config = $this->mergeConfig($this->config[$container][$name], $config);
}
return $config;
}
function array_merge_recursive2($array1, $array2)
{
$arrays = func_get_args();
$narrays = count($arrays);
// check arguments
// comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
for ($i = 0; $i < $narrays; $i ++) {
if (!is_array($arrays[$i])) {
// also array_merge_recursive returns nothing in this case
trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
return;
}
}
// the first array is in the output set in every case
$ret = $arrays[0];
// merege $ret with the remaining arrays
for ($i = 1; $i < $narrays; $i ++) {
foreach ($arrays[$i] as $key => $value) {
if (((string) $key) === ((string) intval($key))) { // integer or string as integer key - append
$ret[] = $value;
}
else { // string key - megre
if (is_array($value) && isset($ret[$key])) {
// if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
// in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
$ret[$key] = $this->array_merge_recursive2($ret[$key], $value);
}
else {
$ret[$key] = $value;
}
}
}
}
return $ret;
}
// Code sniplet borrowed from: http://nl.php.net/manual/en/function.array-merge-recursive.php#81409
// default array merge recursive doesn't overwrite values, but creates multiple elementents for that key,
// which is not what we want here, we want array_merge like behavior
private function mergeConfig() // $array1, $array2, etc
{
$arrays = func_get_args();
$narrays = count($arrays);
for($i = 0; $i < $narrays; $i ++) {
if (! is_array($arrays[$i])) {
trigger_error('Argument #' . ($i + 1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
return null;
}
}
$ret = $arrays[0];
for($i = 1; $i < $narrays; $i ++) {
foreach ( $arrays[$i] as $key => $value ) {
if (((string)$key) === ((string)intval($key))) { // integer or string as integer key - append
$ret[] = $value;
} else {
if (is_array($value) && isset($ret[$key])) {
$ret[$key] = $this->array_merge_recursive2($ret[$key], $value);
} else {
$ret[$key] = $value;
}
}
}
}
return $ret;
}
}
| lgpl-2.1 |
mbinette91/ConstructionLCA-IfcReader | IfcPlusPlus/src/ifcpp/IFC4/IfcPipeSegment.cpp | 6772 | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcGloballyUniqueId.h"
#include "include/IfcIdentifier.h"
#include "include/IfcLabel.h"
#include "include/IfcObjectPlacement.h"
#include "include/IfcOwnerHistory.h"
#include "include/IfcPipeSegment.h"
#include "include/IfcPipeSegmentTypeEnum.h"
#include "include/IfcProductRepresentation.h"
#include "include/IfcRelAggregates.h"
#include "include/IfcRelAssigns.h"
#include "include/IfcRelAssignsToProduct.h"
#include "include/IfcRelAssociates.h"
#include "include/IfcRelConnectsElements.h"
#include "include/IfcRelConnectsPortToElement.h"
#include "include/IfcRelConnectsWithRealizingElements.h"
#include "include/IfcRelContainedInSpatialStructure.h"
#include "include/IfcRelDeclares.h"
#include "include/IfcRelDefinesByObject.h"
#include "include/IfcRelDefinesByProperties.h"
#include "include/IfcRelDefinesByType.h"
#include "include/IfcRelFillsElement.h"
#include "include/IfcRelFlowControlElements.h"
#include "include/IfcRelInterferesElements.h"
#include "include/IfcRelNests.h"
#include "include/IfcRelProjectsElement.h"
#include "include/IfcRelReferencedInSpatialStructure.h"
#include "include/IfcRelSpaceBoundary.h"
#include "include/IfcRelVoidsElement.h"
#include "include/IfcText.h"
// ENTITY IfcPipeSegment
IfcPipeSegment::IfcPipeSegment() { m_entity_enum = IFCPIPESEGMENT; }
IfcPipeSegment::IfcPipeSegment( int id ) { m_id = id; m_entity_enum = IFCPIPESEGMENT; }
IfcPipeSegment::~IfcPipeSegment() {}
shared_ptr<IfcPPObject> IfcPipeSegment::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcPipeSegment> copy_self( new IfcPipeSegment() );
if( m_GlobalId )
{
if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( CreateCompressedGuidString22() ) ); }
else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }
}
if( m_OwnerHistory )
{
if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }
else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }
}
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }
if( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); }
if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); }
if( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); }
if( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcIdentifier>( m_Tag->getDeepCopy(options) ); }
if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcPipeSegmentTypeEnum>( m_PredefinedType->getDeepCopy(options) ); }
return copy_self;
}
void IfcPipeSegment::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCPIPESEGMENT" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_id; } else { stream << "*"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_id; } else { stream << "*"; }
stream << ",";
if( m_Representation ) { stream << "#" << m_Representation->m_id; } else { stream << "*"; }
stream << ",";
if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcPipeSegment::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcPipeSegment::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcPipeSegment, expecting 9, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0] );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::createObjectFromSTEP( args[2] );
m_Description = IfcText::createObjectFromSTEP( args[3] );
m_ObjectType = IfcLabel::createObjectFromSTEP( args[4] );
readEntityReference( args[5], m_ObjectPlacement, map );
readEntityReference( args[6], m_Representation, map );
m_Tag = IfcIdentifier::createObjectFromSTEP( args[7] );
m_PredefinedType = IfcPipeSegmentTypeEnum::createObjectFromSTEP( args[8] );
}
void IfcPipeSegment::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcFlowSegment::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "PredefinedType", m_PredefinedType ) );
}
void IfcPipeSegment::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcFlowSegment::getAttributesInverse( vec_attributes_inverse );
}
void IfcPipeSegment::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcFlowSegment::setInverseCounterparts( ptr_self_entity );
}
void IfcPipeSegment::unlinkFromInverseCounterparts()
{
IfcFlowSegment::unlinkFromInverseCounterparts();
}
| lgpl-2.1 |
pombredanne/zero-install | zeroinstall/injector/trust.py | 5033 | """
Records who we trust to sign feeds.
Trust is divided up into domains, so that it is possible to trust a key
in some cases and not others.
@var trust_db: Singleton trust database instance.
"""
# Copyright (C) 2009, Thomas Leonard
# See the README file for details, or visit http://0install.net.
from zeroinstall import _
import os
from zeroinstall.support import basedir
from namespaces import config_site, config_prog, XMLNS_TRUST
class TrustDB(object):
"""A database of trusted keys.
@ivar keys: maps trusted key fingerprints to a set of domains for which where it is trusted
@type keys: {str: set(str)}
@ivar watchers: callbacks invoked by L{notify}
@see: L{trust_db} - the singleton instance of this class"""
__slots__ = ['keys', 'watchers']
def __init__(self):
self.keys = None
self.watchers = []
def is_trusted(self, fingerprint, domain = None):
self.ensure_uptodate()
domains = self.keys.get(fingerprint, None)
if not domains: return False # Unknown key
if domain is None:
return True # Deprecated
return domain in domains or '*' in domains
def get_trust_domains(self, fingerprint):
"""Return the set of domains in which this key is trusted.
If the list includes '*' then the key is trusted everywhere.
@since: 0.27
"""
self.ensure_uptodate()
return self.keys.get(fingerprint, set())
def get_keys_for_domain(self, domain):
"""Return the set of keys trusted for this domain.
@since: 0.27"""
self.ensure_uptodate()
return set([fp for fp in self.keys
if domain in self.keys[fp]])
def trust_key(self, fingerprint, domain = '*'):
"""Add key to the list of trusted fingerprints.
@param fingerprint: base 16 fingerprint without any spaces
@type fingerprint: str
@param domain: domain in which key is to be trusted
@type domain: str
@note: call L{notify} after trusting one or more new keys"""
if self.is_trusted(fingerprint, domain): return
int(fingerprint, 16) # Ensure fingerprint is valid
if fingerprint not in self.keys:
self.keys[fingerprint] = set()
#if domain == '*':
# warn("Calling trust_key() without a domain is deprecated")
self.keys[fingerprint].add(domain)
self.save()
def untrust_key(self, key, domain = '*'):
self.ensure_uptodate()
self.keys[key].remove(domain)
if not self.keys[key]:
# No more domains for this key
del self.keys[key]
self.save()
def save(self):
from xml.dom import minidom
import tempfile
doc = minidom.Document()
root = doc.createElementNS(XMLNS_TRUST, 'trusted-keys')
root.setAttribute('xmlns', XMLNS_TRUST)
doc.appendChild(root)
for fingerprint in self.keys:
keyelem = doc.createElementNS(XMLNS_TRUST, 'key')
root.appendChild(keyelem)
keyelem.setAttribute('fingerprint', fingerprint)
for domain in self.keys[fingerprint]:
domainelem = doc.createElementNS(XMLNS_TRUST, 'domain')
domainelem.setAttribute('value', domain)
keyelem.appendChild(domainelem)
d = basedir.save_config_path(config_site, config_prog)
fd, tmpname = tempfile.mkstemp(dir = d, prefix = 'trust-')
tmp = os.fdopen(fd, 'wb')
doc.writexml(tmp, indent = "", addindent = " ", newl = "\n")
tmp.close()
os.rename(tmpname, os.path.join(d, 'trustdb.xml'))
def notify(self):
"""Call all watcher callbacks.
This should be called after trusting or untrusting one or more new keys.
@since: 0.25"""
for w in self.watchers: w()
def ensure_uptodate(self):
from xml.dom import minidom
# This is a bit inefficient... (could cache things)
self.keys = {}
trust = basedir.load_first_config(config_site, config_prog, 'trustdb.xml')
if trust:
keys = minidom.parse(trust).documentElement
for key in keys.getElementsByTagNameNS(XMLNS_TRUST, 'key'):
domains = set()
self.keys[key.getAttribute('fingerprint')] = domains
for domain in key.getElementsByTagNameNS(XMLNS_TRUST, 'domain'):
domains.add(domain.getAttribute('value'))
else:
# Convert old database to XML format
trust = basedir.load_first_config(config_site, config_prog, 'trust')
if trust:
#print "Loading trust from", trust_db
for key in file(trust).read().split('\n'):
if key:
self.keys[key] = set(['*'])
else:
# No trust database found.
# Trust Thomas Leonard's key for 0install.net by default.
# Avoids distracting confirmation box on first run when we check
# for updates to the GUI.
self.keys['92429807C9853C0744A68B9AAE07828059A53CC1'] = set(['0install.net'])
def domain_from_url(url):
"""Extract the trust domain for a URL.
@param url: the feed's URL
@type url: str
@return: the trust domain
@rtype: str
@since: 0.27
@raise SafeException: the URL can't be parsed"""
import urlparse
from zeroinstall import SafeException
if os.path.isabs(url):
raise SafeException(_("Can't get domain from a local path: '%s'") % url)
domain = urlparse.urlparse(url)[1]
if domain and domain != '*':
return domain
raise SafeException(_("Can't extract domain from URL '%s'") % url)
trust_db = TrustDB()
| lgpl-2.1 |
bparzella/secsgem | secsgem/common/__init__.py | 1123 | #####################################################################
# __init__.py
#
# (c) Copyright 2013-2021, Benjamin Parzella. All rights reserved.
#
# 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 software 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.
#####################################################################
"""Contains helper functions."""
from .callbacks import CallbackHandler
from .events import EventProducer
from .fysom import Fysom
from .helpers import format_hex, function_name, indent_block, is_windows, is_errorcode_ewouldblock
__all__ = ["CallbackHandler", "EventProducer", "Fysom", "format_hex", "function_name", "indent_block", "is_windows",
"is_errorcode_ewouldblock"]
| lgpl-2.1 |
FedoraScientific/salome-geom | src/AdvancedGUI/AdvancedGEOM_images.ts | 6339 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="en_US">
<context>
<name>@default</name>
<message>
<source>ICON_OBJBROWSER_ADVANCED_201</source>
<translation>tree_pipetshape.png</translation>
</message>
<message>
<source>ICON_OBJBROWSER_ADVANCED_202</source>
<translation>divided_disk.png</translation>
</message>
<message>
<source>ICON_OBJBROWSER_ADVANCED_203</source>
<translation>dividedcylinder.png</translation>
</message>
<message>
<source>ICON_OBJBROWSER_ADVANCED_204</source>
<translation>tree_smoothingsurface.png</translation>
</message>
<message>
<source>ICON_DLG_PIPETSHAPE</source>
<translation>pipetshape.png</translation>
</message>
<message>
<source>ICO_PIPETSHAPE</source>
<translation>pipetshape.png</translation>
</message>
<message>
<source>ICO_PIPETSHAPE_IMPORT</source>
<translation>pipetshape_import_icon.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE</source>
<translation>dlg_pipetshape.png</translation>
</message>
<message>
<source>IMG_PIPETSHAPE_SECT</source>
<translation>pipetshape_section.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_L1</source>
<translation>dlg_pipetshapel1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_R1</source>
<translation>dlg_pipetshaper1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_W1</source>
<translation>dlg_pipetshapew1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_L2</source>
<translation>dlg_pipetshapel2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_R2</source>
<translation>dlg_pipetshaper2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_W2</source>
<translation>dlg_pipetshapew2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET</source>
<translation>dlg_pipetshapefillet.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_L1</source>
<translation>dlg_pipetshapefilletl1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_R1</source>
<translation>dlg_pipetshapefilletr1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_W1</source>
<translation>dlg_pipetshapefilletw1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_L2</source>
<translation>dlg_pipetshapefilletl2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_R2</source>
<translation>dlg_pipetshapefilletr2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_W2</source>
<translation>dlg_pipetshapefilletw2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_FILLET_RF</source>
<translation>dlg_pipetshapefilletrf.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER</source>
<translation>dlg_pipetshapechamfer.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_L1</source>
<translation>dlg_pipetshapechamferl1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_R1</source>
<translation>dlg_pipetshapechamferr1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_W1</source>
<translation>dlg_pipetshapechamferw1.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_L2</source>
<translation>dlg_pipetshapechamferl2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_R2</source>
<translation>dlg_pipetshapechamferr2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_W2</source>
<translation>dlg_pipetshapechamferw2.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_H</source>
<translation>dlg_pipetshapechamferh.png</translation>
</message>
<message>
<source>DLG_PIPETSHAPE_CHAMFER_W</source>
<translation>dlg_pipetshapechamferw.png</translation>
</message>
<!--
<message>
<source>ICON_DLG_PIPETSHAPEGROUPS</source>
<translation>pipetshapegroups.png</translation>
</message>
<message>
<source>ICO_PIPETSHAPEGROUPS</source>
<translation>pipetshapegroups.png</translation>
</message>
-->
<message>
<source>ICON_DLG_DIVIDEDDISK_R_RATIO</source>
<translation>divided_disk.png</translation>
</message>
<message>
<source>ICO_DIVIDEDDISK</source>
<translation>divided_disk.png</translation>
</message>
<message>
<source>ICON_DLG_DIVIDEDCYLINDER_R_H</source>
<translation>dividedcylinder_r_h.png</translation>
</message>
<message>
<source>ICO_DIVIDEDCYLINDER</source>
<translation>dividedcylinder.png</translation>
</message>
<message>
<source>ICON_DLG_SMOOTHINGSURFACE_LPOINTS</source>
<translation>smoothingsurface_lpoints.png</translation>
</message>
<message>
<source>ICO_SMOOTHINGSURFACE</source>
<translation>smoothingsurface.png</translation>
</message>
<!-- @@ insert new functions before this line @@ do not remove this line @@ -->
</context>
</TS>
| lgpl-2.1 |
xpressengine/xe-module-textyle | libs/metaweblog.class.php | 20681 | <?php
class metaWebLog {
var $url = null;
var $user_id = null;
var $password = null;
var $blogid = null;
function metaWebLog($url, $user_id = null, $password = null, $blogid = null) {
if(!preg_match('/^(http|https)/i',$url)) $url = 'http://'.$url;
$this->url = $url;
$this->user_id = $user_id;
$this->password = $password;
$this->blogid = $blogid;
}
function getUsersBlogs() {
$oXmlParser = new XmlParser();
$input = sprintf(
'<?xml version="1.0" encoding="utf-8" ?><methodCall><methodName>blogger.getUsersBlogs</methodName><params><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param></params></methodCall>',
'textyle',
$this->user_id,
$this->password
);
$output = $this->_request($this->url, $input, 'application/octet-stream','POST', array(), array(), array('timeout'=>1, 'readTimeout'=>array(1,0)));
$xmlDoc = $oXmlParser->parse($output);
if(isset($xmlDoc->methodresponse->fault)) {
$code = $xmlDoc->methodresponse->fault->value->struct->member[0]->value->int->body;
$message = $xmlDoc->methodresponse->fault->value->struct->member[1]->value->string->body;
return new Object($code, $message);
}
$blogList = $xmlDoc->methodresponse->params->param->value->array->data->value;
$blogCount = count($blogList);
//return 되는 blog 개수에 따라 복수개가 넘어올 경우 blogid로 특정 blog만 뽑아오기 위해 선별
if($blogCount == 1) $val = $blogList->struct->member;
else if($blogCount > 1)
{
foreach($blogList AS $key=>$value)
{
$nodeList = $value->struct->member;
foreach($nodeList AS $key2=>$value2)
{
if($value2->name->body == 'blogid')
{
$blogid = $value2->value->string->body?$value2->value->string->body:$value2->value->body;
if(empty($this->blogid))
{
$val = $nodeList;
break;
}
else
{
if($this->blogid == $blogid)
{
$val = $nodeList;
break;
}
}
}
}
}
}
else return new Object(-1, 'msg_invalid_request');
if(!is_array($val)) return new Object(-1,'msg_invalid_request');
foreach($val as $node){
if($node->name->body == 'url'){
$url = $node->value->string->body?$node->value->string->body:$node->value->body;
} else if($node->name->body == 'blogid') {
$blogid = $node->value->string->body?$node->value->string->body:$node->value->body;
} else if($node->name->body == 'name' || $node->name->body == 'blogName') {
$name = $node->value->string->body?$node->value->string->body:$node->value->body;
}
}
$output = new Object();
$output->add('url', $url);
$output->add('blogid', $blogid);
$output->add('name', $name);
return $output;
}
function getCategories() {
$oXmlParser = new XmlParser();
$output = $this->getUsersBlogs();
if(!$output->toBool()) return array();
$this->blogid = $output->get('blogid');
$input = sprintf(
'<?xml version="1.0" encoding="utf-8" ?><methodCall><methodName>metaWeblog.getCategories</methodName><params><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param></params></methodCall>',
$this->blogid,
$this->user_id,
$this->password
);
$output = $this->_request($this->url, $input, 'application/octet-stream','POST', array(), array(), array('timeout'=>1, 'readTimeout'=>array(1,0)));
$xmlDoc = $oXmlParser->parse($output);
if(isset($xmlDoc->methodresponse->fault)) {
$code = $xmlDoc->methodresponse->fault->value->struct->member[0]->value->int->body;
$message = $xmlDoc->methodresponse->fault->value->struct->member[1]->value->string->body;
}
$val = $xmlDoc->methodresponse->params->param->value->array->data->value;
if(!is_array($val)) $list[] = $val;
else $list = $val;
$categories = array();
for($i=0,$c=count($list);$i<$c;$i++) {
$category = trim($list[$i]->struct->member[1]->value->string->body);
if(!$category) $category = trim($list[$i]->struct->member[2]->value->string->body);
if(!$category) $category = trim($list[$i]->struct->member[1]->value->body);
if(!$category) continue;
$categories[] = $category;
}
return $categories;
}
function newMediaObject($filename, $source_file) {
$oXmlParser = new XmlParser();
if(preg_match('/\.(jpg|gif|jpeg|png)$/i',$filename)) {
list($width, $height, $type, $attrs) = @getimagesize($source_file);
switch($type) {
case '1' :
$type = 'image/gif';
break;
case '2' :
$type = 'image/jpeg';
break;
case '3' :
$type = 'image/png';
break;
case '6' :
$type = 'image/bmp';
break;
}
}
$input = sprintf('<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>metaWeblog.newMediaObject</methodName><params><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><struct><member><name>name</name><value><string>%s</string></value></member><member><name>type</name><value><string>%s</string></value></member><member><name>bits</name><value><base64>%s</base64></value></member></struct></value></param></params></methodCall>',
$this->blogid,
$this->user_id,
$this->password,
str_replace(array('&','<','>'),array('&','<','>'),$filename),
$type,
base64_encode(FileHandler::readFile($source_file))
);
$output = $this->_request($this->url, $input, 'application/octet-stream','POST');
$xmlDoc = $oXmlParser->parse($output);
if(isset($xmlDoc->methodresponse->fault)) {
$code = $xmlDoc->methodresponse->fault->value->struct->member[0]->value->int->body;
$message = $xmlDoc->methodresponse->fault->value->struct->member[1]->value->string->body;
return new Object($code, $message);
}
$nodes = $xmlDoc->methodresponse->params->param->value->struct->member;
if(!is_array($nodes)) $nodes = array($nodes);
$target_file = null;
foreach($nodes as $node){
if($node->name->body == 'url') $target_file = $node->value->string->body?$node->value->string->body:$node->value->body;
}
if(!$target_file) return new Object(-1,'msg_not_uploaded');
$output = new Object();
$output->add('target_file',$target_file);
return $output;
}
function newPost($oDocument, $category = null) {
$oXmlParser = new XmlParser();
$output = $this->getUsersBlogs();
if(!$output->toBool()) return $output;
$this->blogid = $output->get('blogid');
if($oDocument->hasUploadedFiles()) {
$file_list = $oDocument->getUploadedFiles();
if(count($file_list)) {
$content = $oDocument->get('content');
$content = preg_replace('/src="(files\/)([^"]*)"/i','src="./files/$2"',$content);
foreach($file_list as $file) {
$output = $this->newMediaObject($file->source_filename, $file->uploaded_filename);
$target_file = $output->get('target_file');
if(!$target_file) continue;
preg_match('/(.+)\/'.preg_quote($file->source_filename).'$/',$file->uploaded_filename, $m);
$path = $m[1].'/';
$uploaded_filename = $file->uploaded_filename;
$encoded_filename = $path.str_replace('+','%20',urlencode($file->source_filename));
$extension = strrchr($uploaded_filename, '.');
$extension = '.resized'.$extension;
if(strpos($content, $uploaded_filename.$extension)!==false)
$content = str_replace($uploaded_filename.$extension, $uploaded_filename, $content);
if(strpos($content, $encoded_filename.$extension)!==false)
$content = str_replace($encoded_filename.$extension, $encoded_filename, $content);
if(strpos($content, $uploaded_filename)!==false) $content = str_replace($uploaded_filename, $target_file, $content);
if(strpos($content, $encoded_filename)!==false) $content = str_replace($encoded_filename, $target_file, $content);
$uploaded_filename = preg_replace('/^\.\//','',$file->uploaded_filename);
$encoded_filename = preg_replace('/^\.\//','',$path.str_replace('+','%20',urlencode($file->source_filename)));
if(strpos($content, $uploaded_filename.$extension)!==false)
$content = str_replace($uploaded_filename.$extension, $uploaded_filename, $content);
if(strpos($content, $encoded_filename.$extension)!==false)
$content = str_replace($encoded_filename.$extension, $encoded_filename, $content);
if(strpos($content, $uploaded_filename)!==false) $content = str_replace($uploaded_filename, $target_file, $content);
if(strpos($content, $encoded_filename)!==false) $content = str_replace($encoded_filename, $target_file, $content);
}
$oDocument->add('content', $content);
}
}
$content = $oDocument->get('content');
$content = preg_replace('/src="(\.\/)([^"]*)"/i','src="'.getFullUrl().'$2"',$content);
$oDocument->add('content', $content);
$input = sprintf('<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>metaWeblog.newPost</methodName><params><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><struct><member><name>title</name><value><string>%s</string></value></member><member><name>description</name><value><string>%s</string></value></member><member><name>categories</name><value><array><data><value><string>%s</string></value></data></array></value></member><member><name>tagwords</name><value><array><data><value><string>%s</string></value></data></array></value></member></struct></value></param><param><value><boolean>1</boolean></value></param></params></methodCall>',
$this->blogid,
$this->user_id,
$this->password,
str_replace(array('&','<','>'),array('&','<','>'),$oDocument->get('title')),
str_replace(array('&','<','>'),array('&','<','>'),$oDocument->get('content')),
str_replace(array('&','<','>'),array('&','<','>'),$category),
str_replace(array('&','<','>'),array('&','<','>'),$oDocument->get('tags'))
);
$output = $this->_request($this->url, $input, 'application/octet-stream','POST');
$xmlDoc = $oXmlParser->parse($output);
if(isset($xmlDoc->methodresponse->fault)) {
$code = $xmlDoc->methodresponse->fault->value->struct->member[0]->value->int->body;
$message = $xmlDoc->methodresponse->fault->value->struct->member[1]->value->string->body;
return new Object($code, $message);
}
$postid = '';
$postid_node = $xmlDoc->methodresponse->params->param->value;
if(trim($postid_node->body)){
$postid = trim($postid_node->body);
}else if($postid_node->string){
$postid = sprintf('<string>%s</string>',$postid_node->string->body);
}else if($postid_node->i4){
$postid = sprintf('<i4>%s</i4>',$postid_node->i4->body);
}
$output = new Object();
$output->add('postid', $postid);
return $output;
}
function editPost($postid, $oDocument, $category = null) {
$oXmlParser = new XmlParser();
$output = $this->getUsersBlogs();
if(!$output->toBool()) return $output;
$this->blogid = $output->get('blogid');
if($oDocument->hasUploadedFiles()) {
$file_list = $oDocument->getUploadedFiles();
if(count($file_list)) {
$content = $oDocument->get('content');
$content = preg_replace('/src="(files\/)([^"]*)"/i','src="./files/$2"',$content);
foreach($file_list as $file) {
$output = $this->newMediaObject($file->source_filename, $file->uploaded_filename);
$target_file = $output->get('target_file');
if(!$target_file) continue;
preg_match('/(.+)\/'.preg_quote($file->source_filename).'$/',$file->uploaded_filename, $m);
$path = $m[1].'/';
$encoded_filename = $path.str_replace('+','%20',urlencode($file->source_filename));
$uploaded_filename = $file->uploaded_filename;
$extension = strrchr($uploaded_filename, '.');
$extension = '.resized'.$extension;
if(strpos($content, $uploaded_filename.$extension)!==false)
$content = str_replace($uploaded_filename.$extension, $uploaded_filename, $content);
if(strpos($content, $encoded_filename.$extension)!==false)
$content = str_replace($encoded_filename.$extension, $encoded_filename, $content);
if(strpos($content, $uploaded_filename)!==false) $content = str_replace($uploaded_filename, $target_file, $content);
if(strpos($content, $encoded_filename)!==false) $content = str_replace($encoded_filename, $target_file, $content);
$uploaded_filename = preg_replace('/^\.\//','',$file->uploaded_filename);
$encoded_filename = preg_replace('/^\.\//','',$path.str_replace('+','%20',urlencode($file->source_filename)));
if(strpos($content, $uploaded_filename.$extension)!==false)
$content = str_replace($uploaded_filename.$extension, $uploaded_filename, $content);
if(strpos($content, $encoded_filename.$extension)!==false)
$content = str_replace($encoded_filename.$extension, $encoded_filename, $content);
if(strpos($content, $uploaded_filename)!==false) $content = str_replace($uploaded_filename, $target_file, $content);
if(strpos($content, $encoded_filename)!==false) $content = str_replace($encoded_filename, $target_file, $content);
}
$oDocument->add('content', $content);
}
}
$content = $oDocument->get('content');
$content = preg_replace('/src="(\.\/)([^"]*)"/i','src="'.getFullUrl().'$2"',$content);
$oDocument->add('content', $content);
$input = sprintf('<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>metaWeblog.editPost</methodName><params><param><value>%s</value></param><param><value><string>%s</string></value></param><param><value><string>%s</string></value></param><param><value><struct><member><name>title</name><value><string>%s</string></value></member><member><name>description</name><value><string>%s</string></value></member><member><name>categories</name><value><array><data><value><string>%s</string></value></data></array></value></member><member><name>tagwords</name><value><array><data><value><string>%s</string></value></data></array></value></member></struct></value></param><param><value><boolean>1</boolean></value></param></params></methodCall>',
$postid,
$this->user_id,
$this->password,
str_replace(array('&','<','>'),array('&','<','>'),$oDocument->get('title')),
str_replace(array('&','<','>'),array('&','<','>'),$oDocument->get('content')),
str_replace(array('&','<','>'),array('&','<','>'),$category),
str_replace(array('&','<','>'),array('&','<','>'),$oDocument->get('tags'))
);
$output = $this->_request($this->url, $input, 'application/octet-stream','POST');
$xmlDoc = $oXmlParser->parse($output);
if(isset($xmlDoc->methodresponse->fault)) {
$code = $xmlDoc->methodresponse->fault->value->struct->member[0]->value->int->body;
$message = $xmlDoc->methodresponse->fault->value->struct->member[1]->value->string->body;
return new Object($code, $message);
}
$output = new Object();
$output->add('postid', $postid);
return $output;
}
function _request($url, $body = null, $content_type = 'text/html', $method='GET', $headers = array(), $cookies = array(), $params = array()) {
set_include_path(_XE_PATH_."libs/PEAR");
require_once('PEAR.php');
require_once('HTTP/Request.php');
$url_info = parse_url($url);
$host = $url_info['host'];
if(__PROXY_SERVER__!==null) {
$oRequest = new HTTP_Request(__PROXY_SERVER__);
$oRequest->setMethod('POST');
$oRequest->addPostData('arg', serialize(array('Destination'=>$url, 'method'=>$method, 'body'=>$body, 'content_type'=>$content_type, "headers"=>$headers)));
} else {
$oRequest = new HTTP_Request($url,$params);
if(count($headers)) {
foreach($headers as $key => $val) {
$oRequest->addHeader($key, $val);
}
}
if($cookies[$host]) {
foreach($cookies[$host] as $key => $val) {
$oRequest->addCookie($key, $val);
}
}
if(!$content_type) $oRequest->addHeader('Content-Type', 'text/html');
else $oRequest->addHeader('Content-Type', $content_type);
$oRequest->setMethod($method);
if($body) $oRequest->setBody($body);
}
$oResponse = $oRequest->sendRequest();
$code = $oRequest->getResponseCode();
$header = $oRequest->getResponseHeader();
$response = $oRequest->getResponseBody();
if($c = $oRequest->getResponseCookies()) {
foreach($c as $k => $v) {
$cookies[$host][$v['name']] = $v['value'];
}
}
if($code > 300 && $code < 399 && $header['location']) {
return $this->_request($header['location'], $body, $content_type, $method, $headers, $cookies);
}
if($code != 200) return;
return $response;
}
}
?>
| lgpl-2.1 |
EmreAtes/spack | var/spack/repos/builtin/packages/essl/package.py | 3090 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Essl(Package):
"""IBM's Engineering and Scientific Subroutine Library (ESSL)."""
homepage = "https://www.ibm.com/systems/power/software/essl/"
url = "ibm-essl"
version('5.5')
variant('ilp64', default=False, description='64 bit integers')
variant(
'threads', default='openmp',
description='Multithreading support',
values=('openmp', 'none'),
multi=False
)
variant('cuda', default=False, description='CUDA acceleration')
provides('blas')
conflicts('+cuda', when='+ilp64',
msg='ESSL+cuda+ilp64 cannot combine CUDA acceleration'
' 64 bit integers')
conflicts('+cuda', when='threads=none',
msg='ESSL+cuda threads=none cannot combine CUDA acceleration'
' without multithreading support')
@property
def blas_libs(self):
spec = self.spec
prefix = self.prefix
if '+ilp64' in spec:
essl_lib = ['libessl6464']
else:
essl_lib = ['libessl']
if spec.satisfies('threads=openmp'):
# ESSL SMP support requires XL or Clang OpenMP library
if '%xl' in spec or '%xl_r' in spec or '%clang' in spec:
if '+ilp64' in spec:
essl_lib = ['libesslsmp6464']
else:
if '+cuda' in spec:
essl_lib = ['libesslsmpcuda']
else:
essl_lib = ['libesslsmp']
essl_root = prefix.lib64
essl_libs = find_libraries(
essl_lib,
root=essl_root,
shared=True
)
return essl_libs
def install(self, spec, prefix):
raise InstallError('IBM ESSL is not installable;'
' it is vendor supplied')
| lgpl-2.1 |
shabanovd/exist | src/org/exist/client/xacml/DatabaseInterface.java | 7141 | package org.exist.client.xacml;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.exist.client.ClientFrame;
import org.exist.security.xacml.XACMLConstants;
import org.exist.security.xacml.XACMLUtil;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;
import com.sun.xacml.ParsingException;
import com.sun.xacml.Policy;
import com.sun.xacml.PolicySet;
public class DatabaseInterface
{
private static final Logger LOG = Logger.getLogger(DatabaseInterface.class);
private Collection policyCollection;
@SuppressWarnings("unused")
private DatabaseInterface() {}
public DatabaseInterface(Collection systemCollection)
{
setup(systemCollection);
}
public Collection getPolicyCollection()
{
return policyCollection;
}
private void setup(Collection systemCollection)
{
if(systemCollection == null)
{throw new NullPointerException("System collection cannot be null");}
InputStream in = null;
try
{
final CollectionManagementService service = (CollectionManagementService)systemCollection.getService("CollectionManagementService", "1.0");
policyCollection = service.createCollection(XACMLConstants.POLICY_COLLECTION_NAME);
final Collection confCol = service.createCollection("config" + XACMLConstants.POLICY_COLLECTION);
final String confName = XACMLConstants.POLICY_COLLECTION_NAME + ".xconf";
final XMLResource res = (XMLResource)confCol.createResource(confName, "XMLResource");
in = DatabaseInterface.class.getResourceAsStream(confName);
if(in == null)
{LOG.warn("Could not find policy collection configuration file '" + confName + "'");}
final String content = XACMLUtil.toString(in);
res.setContent(content);
confCol.storeResource(res);
}
catch(final IOException ioe)
{
ClientFrame.showErrorMessage("Error setting up XACML editor", ioe);
}
catch(final XMLDBException xe)
{
ClientFrame.showErrorMessage("Error setting up XACML editor", xe);
}
finally
{
if(in != null)
{
try { in.close(); }
catch(final IOException ioe) {}
}
}
}
public void writePolicies(RootNode root)
{
Set<String> removeDocs;
try
{
removeDocs = new TreeSet<String>(Arrays.asList(policyCollection.listResources()));
}
catch(final XMLDBException xe)
{
LOG.warn("Could not list policy collection resources", xe);
removeDocs = null;
}
final int size = root.getChildCount();
for(int i = 0; i < size; ++i)
{
final AbstractPolicyNode node = (AbstractPolicyNode)root.getChild(i);
String documentName = node.getDocumentName();
if(documentName != null && removeDocs != null)
{removeDocs.remove(documentName);}
if(!node.isModified(true))
{continue;}
node.commit(true);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
node.create().encode(out);
try
{
XMLResource xres;
final Resource res = (documentName == null) ? null : policyCollection.getResource(documentName);
if(res == null)
{xres = null;}
else if(res instanceof XMLResource)
{xres = (XMLResource)res;}
else
{
xres = null;
policyCollection.removeResource(res);
}
if(xres == null)
{
xres = (XMLResource)policyCollection.createResource(documentName, "XMLResource");
if(documentName == null)
{
documentName = xres.getDocumentId();
node.setDocumentName(documentName);
}
}
xres.setContent(out.toString());
policyCollection.storeResource(xres);
node.commit(true);
}
catch (final XMLDBException e)
{
final StringBuffer message = new StringBuffer();
message.append("Error saving policy '");
message.append(node.getId());
message.append("' ");
if(documentName != null)
{
message.append(" to document '");
message.append(documentName);
message.append("' ");
}
ClientFrame.showErrorMessage(message.toString(), e);
}
}
if(removeDocs == null)
{return;}
for(final String documentName : removeDocs)
{
try
{
final Resource removeResource = policyCollection.getResource(documentName);
policyCollection.removeResource(removeResource);
}
catch (final XMLDBException xe)
{
LOG.warn("Could not remove resource '" + documentName + "'", xe);
}
}
}
public RootNode getPolicies()
{
final RootNode root = new RootNode();
findPolicies(root);
root.commit(true);
return root;
}
private void findPolicies(RootNode root)
{
try
{
final String[] resourceIds = policyCollection.listResources();
for(int i = 0; i < resourceIds.length; ++i)
{
final String resourceId = resourceIds[i];
final Resource resource = policyCollection.getResource(resourceId);
if(resource != null && resource instanceof XMLResource)
{handleResource((XMLResource)resource, root);}
}
}
catch (final XMLDBException xe)
{
ClientFrame.showErrorMessage("Error scanning for policies", xe);
}
}
private void handleResource(XMLResource xres, RootNode root) throws XMLDBException
{
final String documentName = xres.getDocumentId();
final Node content = xres.getContentAsDOM();
Element rootElement;
if(content instanceof Document)
{rootElement = ((Document)content).getDocumentElement();}
else if(content instanceof Element)
{rootElement = (Element)content;}
else
{
LOG.warn("The DOM representation of resource '" + documentName + "' in the policy collection was not a Document or Element node.");
return;
}
final String namespace = rootElement.getNamespaceURI();
final String tagName = rootElement.getTagName();
//sunxacml does not do namespaces, so this part is commented out for now
if(/*XACMLConstants.XACML_POLICY_NAMESPACE.equals(namespace) && */XACMLConstants.POLICY_ELEMENT_LOCAL_NAME.equals(tagName))
{
Policy policy;
try
{
policy = Policy.getInstance(rootElement);
}
catch(final ParsingException pe)
{
ClientFrame.showErrorMessage("Error parsing policy document '" + documentName +"'", pe);
return;
}
root.add(new PolicyNode(root, documentName, policy));
}
else if(/*XACMLConstants.XACML_POLICY_NAMESPACE.equals(namespace) && */XACMLConstants.POLICY_SET_ELEMENT_LOCAL_NAME.equals(tagName))
{
PolicySet policySet;
try
{
policySet = PolicySet.getInstance(rootElement);
}
catch(final ParsingException pe)
{
ClientFrame.showErrorMessage("Error parsing policy set document '" + documentName +"'", pe);
return;
}
root.add(new PolicySetNode(root, documentName, policySet));
}
else
{LOG.warn("Document '" + documentName + "' in policy collection is not a policy: root tag has namespace '" + namespace + "' and name '" + tagName + "'");}
}
}
| lgpl-2.1 |
skosukhin/spack | var/spack/repos/builtin/packages/hepmc/package.py | 2012 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Hepmc(CMakePackage):
"""The HepMC package is an object oriented, C++ event record for
High Energy Physics Monte Carlo generators and simulation."""
homepage = "http://hepmc.web.cern.ch/hepmc/"
url = "http://hepmc.web.cern.ch/hepmc/releases/hepmc2.06.09.tgz"
version('2.06.09', 'c47627ced4255b40e731b8666848b087')
version('2.06.08', 'a2e889114cafc4f60742029d69abd907')
version('2.06.07', '11d7035dccb0650b331f51520c6172e7')
version('2.06.06', '102e5503537a3ecd6ea6f466aa5bc4ae')
version('2.06.05', '2a4a2a945adf26474b8bdccf4f881d9c')
depends_on('[email protected]:', type='build')
def cmake_args(self):
return [
'-Dmomentum:STRING=GEV',
'-Dlength:STRING=MM',
]
| lgpl-2.1 |
GNOME/orca | test/keystrokes/firefox/aria_alert_dialog.py | 2343 | #!/usr/bin/python
"""Test of UIUC button presentation using Firefox."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
#sequence.append(WaitForDocLoad())
sequence.append(PauseAction(5000))
sequence.append(TypeAction("12"))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Return"))
sequence.append(utils.AssertPresentationAction(
"1. Open Alert Box",
["BRAILLE LINE: 'dialog'",
" VISIBLE: 'dialog', cursor=1",
"BRAILLE LINE: 'Browse mode'",
" VISIBLE: 'Browse mode', cursor=0",
"SPEECH OUTPUT: 'Alert Box You must choose a number between 1 and 10!'",
"SPEECH OUTPUT: 'Browse mode' voice=system"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Down"))
sequence.append(utils.AssertPresentationAction(
"2. Down to message",
["BRAILLE LINE: 'dialog'",
" VISIBLE: 'dialog', cursor=1",
"BRAILLE LINE: 'You must choose a number'",
" VISIBLE: 'You must choose a number', cursor=1",
"SPEECH OUTPUT: 'You must choose a number'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Down"))
sequence.append(utils.AssertPresentationAction(
"3. Down arrow to read next line of message",
["BRAILLE LINE: 'between 1 and 10!'",
" VISIBLE: 'between 1 and 10!', cursor=1",
"SPEECH OUTPUT: 'between 1 and 10!'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Down"))
sequence.append(utils.AssertPresentationAction(
"4. Down arrow to read next line of message",
["BRAILLE LINE: 'Close push button'",
" VISIBLE: 'Close push button', cursor=1",
"SPEECH OUTPUT: 'Close push button'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Return"))
sequence.append(utils.AssertPresentationAction(
"5. Close Alert",
["BRAILLE LINE: 'Guess a number between 1 and 10 12 $l invalid'",
" VISIBLE: '12 $l invalid', cursor=3",
"BRAILLE LINE: 'Focus mode'",
" VISIBLE: 'Focus mode', cursor=0",
"SPEECH OUTPUT: 'Guess a number between 1 and 10 entry 12 selected.'",
"SPEECH OUTPUT: 'invalid entry'",
"SPEECH OUTPUT: 'Focus mode' voice=system"]))
sequence.append(utils.AssertionSummaryAction())
sequence.start()
| lgpl-2.1 |
kuba1/qtcreator | src/plugins/debugger/sourceutils.cpp | 12387 | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "sourceutils.h"
#include "watchdata.h"
#include "watchutils.h"
#include <texteditor/texteditor.h>
#include <texteditor/textdocument.h>
#include <cpptools/abstracteditorsupport.h>
#include <cpptools/cppprojectfile.h>
#include <cpptools/cppmodelmanager.h>
#include <cplusplus/CppDocument.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <utils/qtcassert.h>
#include <QDebug>
#include <string.h>
#include <ctype.h>
enum { debug = 0 };
using namespace CppTools;
using namespace CPlusPlus;
using namespace TextEditor;
namespace CPlusPlus {
static void debugCppSymbolRecursion(QTextStream &str, const Overview &o,
const Symbol &s, bool doRecurse = true,
int recursion = 0)
{
for (int i = 0; i < recursion; i++)
str << " ";
str << "Symbol: " << o.prettyName(s.name()) << " at line " << s.line();
if (s.isFunction())
str << " function";
if (s.isClass())
str << " class";
if (s.isDeclaration())
str << " declaration";
if (s.isBlock())
str << " block";
if (doRecurse && s.isScope()) {
const Scope *scoped = s.asScope();
const int size = scoped->memberCount();
str << " scoped symbol of " << size << '\n';
for (int m = 0; m < size; m++)
debugCppSymbolRecursion(str, o, *scoped->memberAt(m), true, recursion + 1);
} else {
str << '\n';
}
}
QDebug operator<<(QDebug d, const Symbol &s)
{
QString output;
Overview o;
QTextStream str(&output);
debugCppSymbolRecursion(str, o, s, true, 0);
d.nospace() << output;
return d;
}
QDebug operator<<(QDebug d, const Scope &scope)
{
QString output;
Overview o;
QTextStream str(&output);
const int size = scope.memberCount();
str << "Scope of " << size;
if (scope.isNamespace())
str << " namespace";
if (scope.isClass())
str << " class";
if (scope.isEnum())
str << " enum";
if (scope.isBlock())
str << " block";
if (scope.isFunction())
str << " function";
if (scope.isDeclaration())
str << " prototype";
#if 0 // ### port me
if (const Symbol *owner = &scope) {
str << " owner: ";
debugCppSymbolRecursion(str, o, *owner, false, 0);
} else {
str << " 0-owner\n";
}
#endif
for (int s = 0; s < size; s++)
debugCppSymbolRecursion(str, o, *scope.memberAt(s), true, 2);
d.nospace() << output;
return d;
}
} // namespace CPlusPlus
namespace Debugger {
namespace Internal {
/* getUninitializedVariables(): Get variables that are not initialized
* at a certain line of a function from the code model to be able to
* indicate them as not in scope in the locals view.
* Find document + function in the code model, do a double check and
* collect declarative symbols that are in the function past or on
* the current line. blockRecursion() recurses up the scopes
* and collect symbols declared past or on the current line.
* Recursion goes up from the innermost scope, keeping a map
* of occurrences seen, to be able to derive the names of
* shadowed variables as the debugger sees them:
\code
int x; // Occurrence (1), should be reported as "x <shadowed 1>"
if (true) {
int x = 5; (2) // Occurrence (2), should be reported as "x"
}
\endcode
*/
typedef QHash<QString, int> SeenHash;
static void blockRecursion(const Overview &overview,
const Scope *scope,
unsigned line,
QStringList *uninitializedVariables,
SeenHash *seenHash,
int level = 0)
{
// Go backwards in case someone has identical variables in the same scope.
// Fixme: loop variables or similar are currently seen in the outer scope
for (int s = scope->memberCount() - 1; s >= 0; --s){
const Symbol *symbol = scope->memberAt(s);
if (symbol->isDeclaration()) {
// Find out about shadowed symbols by bookkeeping
// the already seen occurrences in a hash.
const QString name = overview.prettyName(symbol->name());
SeenHash::iterator it = seenHash->find(name);
if (it == seenHash->end())
it = seenHash->insert(name, 0);
else
++(it.value());
// Is the declaration on or past the current line, that is,
// the variable not initialized.
if (symbol->line() >= line)
uninitializedVariables->push_back(WatchData::shadowedName(name, it.value()));
}
}
// Next block scope.
if (const Scope *enclosingScope = scope->enclosingBlock())
blockRecursion(overview, enclosingScope, line, uninitializedVariables, seenHash, level + 1);
}
// Inline helper with integer error return codes.
static inline
int getUninitializedVariablesI(const Snapshot &snapshot,
const QString &functionName,
const QString &file,
int line,
QStringList *uninitializedVariables)
{
uninitializedVariables->clear();
// Find document
if (snapshot.isEmpty() || functionName.isEmpty() || file.isEmpty() || line < 1)
return 1;
const Snapshot::const_iterator docIt = snapshot.find(file);
if (docIt == snapshot.end())
return 2;
const Document::Ptr doc = docIt.value();
// Look at symbol at line and find its function. Either it is the
// function itself or some expression/variable.
const Symbol *symbolAtLine = doc->lastVisibleSymbolAt(line, 0);
if (!symbolAtLine)
return 4;
// First figure out the function to do a safety name check
// and the innermost scope at cursor position
const Function *function = 0;
const Scope *innerMostScope = 0;
if (symbolAtLine->isFunction()) {
function = symbolAtLine->asFunction();
if (function->memberCount() == 1) // Skip over function block
if (Block *block = function->memberAt(0)->asBlock())
innerMostScope = block;
} else {
if (const Scope *functionScope = symbolAtLine->enclosingFunction()) {
function = functionScope->asFunction();
innerMostScope = symbolAtLine->isBlock() ?
symbolAtLine->asBlock() :
symbolAtLine->enclosingBlock();
}
}
if (!function || !innerMostScope)
return 7;
// Compare function names with a bit off fuzz,
// skipping modules from a CDB symbol "lib!foo" or namespaces
// that the code model does not show at this point
Overview overview;
const QString name = overview.prettyName(function->name());
if (!functionName.endsWith(name))
return 11;
if (functionName.size() > name.size()) {
const char previousChar = functionName.at(functionName.size() - name.size() - 1).toLatin1();
if (previousChar != ':' && previousChar != '!' )
return 11;
}
// Starting from the innermost block scope, collect declarations.
SeenHash seenHash;
blockRecursion(overview, innerMostScope, line, uninitializedVariables, &seenHash);
return 0;
}
bool getUninitializedVariables(const Snapshot &snapshot,
const QString &function,
const QString &file,
int line,
QStringList *uninitializedVariables)
{
const int rc = getUninitializedVariablesI(snapshot, function, file, line, uninitializedVariables);
if (debug) {
QString msg;
QTextStream str(&msg);
str << "getUninitializedVariables() " << function << ' ' << file << ':' << line
<< " returns (int) " << rc << " '"
<< uninitializedVariables->join(QLatin1Char(',')) << '\'';
if (rc)
str << " of " << snapshot.size() << " documents";
qDebug() << msg;
}
return rc == 0;
}
// Editor tooltip support
bool isCppEditor(TextEditorWidget *editorWidget)
{
const TextDocument *document = editorWidget->textDocument();
return ProjectFile::classify(document->filePath().toString()) != ProjectFile::Unclassified;
}
QString cppFunctionAt(const QString &fileName, int line, int column)
{
const Snapshot snapshot = CppModelManager::instance()->snapshot();
if (const Document::Ptr document = snapshot.document(fileName))
return document->functionAt(line, column);
return QString();
}
// Return the Cpp expression, and, if desired, the function
QString cppExpressionAt(TextEditorWidget *editorWidget, int pos,
int *line, int *column, QString *function,
int *scopeFromLine, int *scopeToLine)
{
if (function)
function->clear();
const QString fileName = editorWidget->textDocument()->filePath().toString();
const Snapshot snapshot = CppModelManager::instance()->snapshot();
const Document::Ptr document = snapshot.document(fileName);
QTextCursor tc = editorWidget->textCursor();
QString expr = tc.selectedText();
if (expr.isEmpty()) {
tc.setPosition(pos);
const QChar ch = editorWidget->characterAt(pos);
if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
tc.movePosition(QTextCursor::EndOfWord);
// Fetch the expression's code.
ExpressionUnderCursor expressionUnderCursor(document ? document->languageFeatures()
: LanguageFeatures::defaultFeatures());
expr = expressionUnderCursor(tc);
}
*column = tc.positionInBlock();
*line = tc.blockNumber() + 1;
if (!expr.isEmpty() && document) {
QString func = document->functionAt(*line, *column, scopeFromLine, scopeToLine);
if (function)
*function = func;
}
return expr;
}
// Ensure an expression can be added as side-effect
// free debugger expression.
QString fixCppExpression(const QString &expIn)
{
QString exp = expIn.trimmed();
// Extract the first identifier, everything else is considered
// too dangerous.
int pos1 = 0, pos2 = exp.size();
bool inId = false;
for (int i = 0; i != exp.size(); ++i) {
const QChar c = exp.at(i);
const bool isIdChar = c.isLetterOrNumber() || c.unicode() == '_';
if (inId && !isIdChar) {
pos2 = i;
break;
}
if (!inId && isIdChar) {
inId = true;
pos1 = i;
}
}
exp = exp.mid(pos1, pos2 - pos1);
return removeObviousSideEffects(exp);
}
} // namespace Internal
} // namespace Debugger
| lgpl-2.1 |
mbatchelor/pentaho-reporting | libraries/libpensol/src/main/java/org/pentaho/reporting/libraries/pensol/LibPensolInfo.java | 1911 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.reporting.libraries.pensol;
import org.pentaho.reporting.libraries.base.LibBaseInfo;
import org.pentaho.reporting.libraries.base.versioning.ProjectInformation;
public class LibPensolInfo extends ProjectInformation {
private static LibPensolInfo instance;
/**
* Returns the singleton instance of the ProjectInformation-class.
*
* @return the singleton ProjectInformation.
*/
public static synchronized ProjectInformation getInstance() {
if ( instance == null ) {
instance = new LibPensolInfo();
instance.initialize();
}
return instance;
}
/**
* Constructs an empty project info object.
*/
private LibPensolInfo() {
super( "libpensol", "LibPenSol" );
}
/**
* Initialized the project info object.
*/
private void initialize() {
setLicenseName( "LGPL" );
setInfo( "http://reporting.pentaho.org/libpensol/" );
setCopyright( "(C)opyright 2010, by Pentaho Corporation and Contributors" );
setBootClass( LibPensolBoot.class.getName() );
addLibrary( LibBaseInfo.getInstance() );
}
}
| lgpl-2.1 |
0xbb/jitsi | src/net/java/sip/communicator/impl/gui/main/contactlist/ContactListPane.java | 32591 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.Timer;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.event.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.main.chat.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.service.contacteventhandler.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.gui.Container;
import net.java.sip.communicator.service.gui.event.*;
import net.java.sip.communicator.service.muc.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* The contactlist panel not only contains the contact list but it has the role
* of a message dispatcher. It process all sent and received messages as well as
* all typing notifications. Here are managed all contact list mouse events.
*
* @author Yana Stamcheva
* @author Hristo Terezov
*/
public class ContactListPane
extends SIPCommScrollPane
implements MessageListener,
TypingNotificationsListener,
FileTransferListener,
ContactListListener,
PluginComponentListener
{
/**
* Serial version UID.
*/
private static final long serialVersionUID = 0L;
private final MainFrame mainFrame;
private TreeContactList contactList;
private final TypingTimer typingTimer = new TypingTimer();
private CommonRightButtonMenu commonRightButtonMenu;
private final Logger logger = Logger.getLogger(ContactListPane.class);
private final ChatWindowManager chatWindowManager;
/**
* Creates the contactlist scroll panel defining the parent frame.
*
* @param mainFrame The parent frame.
*/
public ContactListPane(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
this.chatWindowManager
= GuiActivator.getUIService().getChatWindowManager();
this.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY));
this.initPluginComponents();
}
/**
* Initializes the contact list.
*
* @param contactListService The MetaContactListService which will be used
* for a contact list data model.
*/
public void initList(MetaContactListService contactListService)
{
this.contactList = new TreeContactList(mainFrame);
// We should first set the contact list to the GuiActivator, so that
// anybody could get it from there.
GuiActivator.setContactList(contactList);
// By default we set the current filter to be the presence filter.
contactList.applyFilter(TreeContactList.presenceFilter);
TransparentPanel transparentPanel
= new TransparentPanel(new BorderLayout());
transparentPanel.add(contactList, BorderLayout.NORTH);
this.setViewportView(transparentPanel);
transparentPanel.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
this.contactList.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
this.contactList.addContactListListener(this);
this.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
{
commonRightButtonMenu = new CommonRightButtonMenu(mainFrame);
commonRightButtonMenu.setInvoker(ContactListPane.this);
commonRightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
commonRightButtonMenu.setVisible(true);
}
}
});
}
/**
* Returns the contact list.
*
* @return the contact list
*/
public TreeContactList getContactList()
{
return this.contactList;
}
/**
* Implements the ContactListListener.contactSelected method.
* @param evt the <tt>ContactListEvent</tt> that notified us
*/
public void contactClicked(ContactListEvent evt)
{
// We're interested only in two click events.
if (evt.getClickCount() < 2)
return;
UIContact descriptor = evt.getSourceContact();
// We're currently only interested in MetaContacts.
if (descriptor.getDescriptor() instanceof MetaContact)
{
MetaContact metaContact = (MetaContact) descriptor.getDescriptor();
// Searching for the right proto contact to use as default for the
// chat conversation.
Contact defaultContact = metaContact.getDefaultContact(
OperationSetBasicInstantMessaging.class);
// do nothing
if(defaultContact == null)
{
defaultContact = metaContact.getDefaultContact(
OperationSetSmsMessaging.class);
if(defaultContact == null)
return;
}
ProtocolProviderService defaultProvider
= defaultContact.getProtocolProvider();
OperationSetBasicInstantMessaging
defaultIM = defaultProvider.getOperationSet(
OperationSetBasicInstantMessaging.class);
ProtocolProviderService protoContactProvider;
OperationSetBasicInstantMessaging protoContactIM;
boolean isOfflineMessagingSupported
= defaultIM != null && !defaultIM.isOfflineMessagingSupported();
if (defaultContact.getPresenceStatus().getStatus() < 1
&& (!isOfflineMessagingSupported
|| !defaultProvider.isRegistered()))
{
Iterator<Contact> protoContacts = metaContact.getContacts();
while(protoContacts.hasNext())
{
Contact contact = protoContacts.next();
protoContactProvider = contact.getProtocolProvider();
protoContactIM = protoContactProvider.getOperationSet(
OperationSetBasicInstantMessaging.class);
if(protoContactIM != null
&& protoContactIM.isOfflineMessagingSupported()
&& protoContactProvider.isRegistered())
{
defaultContact = contact;
}
}
}
ContactEventHandler contactHandler = mainFrame
.getContactHandler(defaultContact.getProtocolProvider());
contactHandler.contactClicked(defaultContact, evt.getClickCount());
}
else if(descriptor.getDescriptor() instanceof SourceContact)
{
SourceContact contact = (SourceContact)descriptor.getDescriptor();
List<ContactDetail> imDetails = contact.getContactDetails(
OperationSetBasicInstantMessaging.class);
List<ContactDetail> mucDetails = contact.getContactDetails(
OperationSetMultiUserChat.class);
if(imDetails != null && imDetails.size() > 0)
{
ProtocolProviderService pps
= imDetails.get(0).getPreferredProtocolProvider(
OperationSetBasicInstantMessaging.class);
GuiActivator.getUIService().getChatWindowManager()
.startChat(contact.getContactAddress(), pps);
}
else if(mucDetails != null && mucDetails.size() > 0)
{
ChatRoomWrapper room
= GuiActivator.getMUCService()
.findChatRoomWrapperFromSourceContact(contact);
if(room == null)
{
// lets check by id
ProtocolProviderService pps =
mucDetails.get(0).getPreferredProtocolProvider(
OperationSetMultiUserChat.class);
room = GuiActivator.getMUCService()
.findChatRoomWrapperFromChatRoomID(
contact.getContactAddress(), pps);
if(room == null)
{
GuiActivator.getMUCService().createChatRoom(
contact.getContactAddress(),
pps,
new ArrayList<String>(),
"",
false,
false,
false);
}
}
if(room != null)
GuiActivator.getMUCService().openChatRoom(room);
}
else
{
List<ContactDetail> smsDetails = contact.getContactDetails(
OperationSetSmsMessaging.class);
if(smsDetails != null && smsDetails.size() > 0)
{
GuiActivator.getUIService().getChatWindowManager()
.startChat(contact.getContactAddress(), true);
}
}
}
}
/**
* Implements the ContactListListener.groupSelected method.
* @param evt the <tt>ContactListEvent</tt> that notified us
*/
public void groupClicked(ContactListEvent evt) {}
/**
* We're not interested in group selection events here.
*/
public void groupSelected(ContactListEvent evt) {}
/**
* We're not interested in contact selection events here.
*/
public void contactSelected(ContactListEvent evt) {}
/**
* When a message is received determines whether to open a new chat window
* or chat window tab, or to indicate that a message is received from a
* contact which already has an open chat. When the chat is found checks if
* in mode "Auto popup enabled" and if this is the case shows the message in
* the appropriate chat panel.
*
* @param evt the event containing details on the received message
*/
public void messageReceived(MessageReceivedEvent evt)
{
if (logger.isTraceEnabled())
logger.trace("MESSAGE RECEIVED from contact: "
+ evt.getSourceContact().getAddress());
Contact protocolContact = evt.getSourceContact();
ContactResource contactResource = evt.getContactResource();
Message message = evt.getSourceMessage();
int eventType = evt.getEventType();
MetaContact metaContact = GuiActivator.getContactListService()
.findMetaContactByContact(protocolContact);
if(metaContact != null)
{
messageReceived(protocolContact,
contactResource,
metaContact,
message,
eventType,
evt.getTimestamp(),
evt.getCorrectedMessageUID(),
evt.isPrivateMessaging(),
evt.getPrivateMessagingContactRoom());
}
else
{
if (logger.isTraceEnabled())
logger.trace("MetaContact not found for protocol contact: "
+ protocolContact + ".");
}
}
/**
* When a message is received determines whether to open a new chat window
* or chat window tab, or to indicate that a message is received from a
* contact which already has an open chat. When the chat is found checks if
* in mode "Auto popup enabled" and if this is the case shows the message in
* the appropriate chat panel.
*
* @param protocolContact the source contact of the event
* @param contactResource the resource from which the contact is writing
* @param metaContact the metacontact containing <tt>protocolContact</tt>
* @param message the message to deliver
* @param eventType the event type
* @param timestamp the timestamp of the event
* @param correctedMessageUID the identifier of the corrected message
* @param isPrivateMessaging if <tt>true</tt> the message is received from
* private messaging contact.
* @param privateContactRoom the chat room associated with the private
* messaging contact.
*/
private void messageReceived(final Contact protocolContact,
final ContactResource contactResource,
final MetaContact metaContact,
final Message message,
final int eventType,
final Date timestamp,
final String correctedMessageUID,
final boolean isPrivateMessaging,
final ChatRoom privateContactRoom)
{
if(!SwingUtilities.isEventDispatchThread())
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
messageReceived(protocolContact,
contactResource,
metaContact,
message,
eventType,
timestamp,
correctedMessageUID,
isPrivateMessaging,
privateContactRoom);
}
});
return;
}
// Obtain the corresponding chat panel.
final ChatPanel chatPanel
= chatWindowManager.getContactChat( metaContact,
protocolContact,
contactResource,
message.getMessageUID());
// Show an envelope on the sender contact in the contact list and
// in the systray.
if (!chatPanel.isChatFocused())
contactList.setActiveContact(metaContact, true);
// Distinguish the message type, depending on the type of event that
// we have received.
String messageType = null;
if(eventType == MessageReceivedEvent.CONVERSATION_MESSAGE_RECEIVED)
{
messageType = Chat.INCOMING_MESSAGE;
}
else if(eventType == MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED)
{
messageType = Chat.SYSTEM_MESSAGE;
}
else if(eventType == MessageReceivedEvent.SMS_MESSAGE_RECEIVED)
{
messageType = Chat.SMS_MESSAGE;
}
String contactAddress = (contactResource != null)
? protocolContact.getAddress()
+ " (" + contactResource.getResourceName() + ")"
: protocolContact.getAddress();
chatPanel.addMessage(
contactAddress,
protocolContact.getDisplayName(),
timestamp,
messageType,
message.getContent(),
message.getContentType(),
message.getMessageUID(),
correctedMessageUID);
String resourceName = (contactResource != null)
? contactResource.getResourceName()
: null;
if(isPrivateMessaging)
{
chatWindowManager.openPrivateChatForChatRoomMember(
privateContactRoom,
protocolContact);
}
else
{
chatWindowManager.openChat(chatPanel, false);
}
ChatTransport chatTransport
= chatPanel.getChatSession()
.findChatTransportForDescriptor(protocolContact, resourceName);
chatPanel.setSelectedChatTransport(chatTransport, true);
}
/**
* When a sent message is delivered shows it in the chat conversation panel.
*
* @param evt the event containing details on the message delivery
*/
public void messageDelivered(MessageDeliveredEvent evt)
{
Contact contact = evt.getDestinationContact();
MetaContact metaContact = GuiActivator.getContactListService()
.findMetaContactByContact(contact);
if (logger.isTraceEnabled())
logger.trace("MESSAGE DELIVERED to contact: " + contact.getAddress());
ChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact, false);
if (chatPanel != null)
{
Message msg = evt.getSourceMessage();
ProtocolProviderService protocolProvider
= contact.getProtocolProvider();
if (logger.isTraceEnabled())
logger.trace(
"MESSAGE DELIVERED: process message to chat for contact: "
+ contact.getAddress()
+ " MESSAGE: " + msg.getContent());
chatPanel.addMessage(
this.mainFrame.getAccountAddress(protocolProvider),
this.mainFrame.getAccountDisplayName(protocolProvider),
evt.getTimestamp(),
Chat.OUTGOING_MESSAGE,
msg.getContent(),
msg.getContentType(),
msg.getMessageUID(),
evt.getCorrectedMessageUID());
if(evt.isSmsMessage()
&& !ConfigurationUtils.isSmsNotifyTextDisabled())
{
chatPanel.addMessage(
contact.getDisplayName(),
new Date(),
Chat.ACTION_MESSAGE,
GuiActivator.getResources().getI18NString(
"service.gui.SMS_SUCCESSFULLY_SENT"),
"text");
}
}
}
/**
* Shows a warning message to the user when message delivery has failed.
*
* @param evt the event containing details on the message delivery failure
*/
public void messageDeliveryFailed(MessageDeliveryFailedEvent evt)
{
logger.error(evt.getReason());
String errorMsg = null;
Message sourceMessage = (Message) evt.getSource();
Contact sourceContact = evt.getDestinationContact();
MetaContact metaContact = GuiActivator.getContactListService()
.findMetaContactByContact(sourceContact);
if (evt.getErrorCode()
== MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED)
{
errorMsg = GuiActivator.getResources().getI18NString(
"service.gui.MSG_DELIVERY_NOT_SUPPORTED",
new String[] {sourceContact.getDisplayName()});
}
else if (evt.getErrorCode()
== MessageDeliveryFailedEvent.NETWORK_FAILURE)
{
errorMsg = GuiActivator.getResources().getI18NString(
"service.gui.MSG_NOT_DELIVERED");
}
else if (evt.getErrorCode()
== MessageDeliveryFailedEvent.PROVIDER_NOT_REGISTERED)
{
errorMsg = GuiActivator.getResources().getI18NString(
"service.gui.MSG_SEND_CONNECTION_PROBLEM");
}
else if (evt.getErrorCode()
== MessageDeliveryFailedEvent.INTERNAL_ERROR)
{
errorMsg = GuiActivator.getResources().getI18NString(
"service.gui.MSG_DELIVERY_INTERNAL_ERROR");
}
else
{
errorMsg = GuiActivator.getResources().getI18NString(
"service.gui.MSG_DELIVERY_ERROR");
}
String reason = evt.getReason();
if (reason != null)
errorMsg += " " + GuiActivator.getResources().getI18NString(
"service.gui.ERROR_WAS",
new String[]{reason});
ChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact, sourceContact);
chatPanel.addMessage(
sourceContact.getAddress(),
metaContact.getDisplayName(),
new Date(),
Chat.OUTGOING_MESSAGE,
sourceMessage.getContent(),
sourceMessage.getContentType(),
sourceMessage.getMessageUID(),
evt.getCorrectedMessageUID());
chatPanel.addErrorMessage(
metaContact.getDisplayName(),
errorMsg);
chatWindowManager.openChat(chatPanel, false);
}
/**
* Informs the user what is the typing state of his chat contacts.
*
* @param evt the event containing details on the typing notification
*/
public void typingNotificationReceived(TypingNotificationEvent evt)
{
if (typingTimer.isRunning())
typingTimer.stop();
String notificationMsg = "";
MetaContact metaContact = GuiActivator.getContactListService()
.findMetaContactByContact(evt.getSourceContact());
String contactName = metaContact.getDisplayName() + " ";
if (contactName.equals(""))
{
contactName = GuiActivator.getResources()
.getI18NString("service.gui.UNKNOWN") + " ";
}
int typingState = evt.getTypingState();
ChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact, false);
if (typingState == OperationSetTypingNotifications.STATE_TYPING)
{
notificationMsg
= GuiActivator.getResources().getI18NString(
"service.gui.CONTACT_TYPING",
new String[]{contactName});
// Proactive typing notification
if (!chatWindowManager.isChatOpenedFor(metaContact))
{
return;
}
if (chatPanel != null)
chatPanel.addTypingNotification(notificationMsg);
typingTimer.setMetaContact(metaContact);
typingTimer.start();
}
else if (typingState == OperationSetTypingNotifications.STATE_PAUSED)
{
notificationMsg = GuiActivator.getResources().getI18NString(
"service.gui.CONTACT_PAUSED_TYPING",
new String[]{contactName});
if (chatPanel != null)
chatPanel.addTypingNotification(notificationMsg);
typingTimer.setMetaContact(metaContact);
typingTimer.start();
}
else
{
if (chatPanel != null)
chatPanel.removeTypingNotification();
}
}
/**
* Called to indicate that sending typing notification has failed.
*
* @param evt a <tt>TypingNotificationEvent</tt> containing the sender
* of the notification and its type.
*/
public void typingNotificationDeliveryFailed(TypingNotificationEvent evt)
{
if (typingTimer.isRunning())
typingTimer.stop();
String notificationMsg = "";
MetaContact metaContact = GuiActivator.getContactListService()
.findMetaContactByContact(evt.getSourceContact());
String contactName = metaContact.getDisplayName();
if (contactName.equals(""))
{
contactName = GuiActivator.getResources()
.getI18NString("service.gui.UNKNOWN") + " ";
}
ChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact, false);
notificationMsg
= GuiActivator.getResources().getI18NString(
"service.gui.CONTACT_TYPING_SEND_FAILED",
new String[]{contactName});
// Proactive typing notification
if (!chatWindowManager.isChatOpenedFor(metaContact))
{
return;
}
if (chatPanel != null)
chatPanel.addErrorSendingTypingNotification(notificationMsg);
typingTimer.setMetaContact(metaContact);
typingTimer.start();
}
/**
* When a request has been received we show it to the user through the
* chat session renderer.
*
* @param event <tt>FileTransferRequestEvent</tt>
* @see FileTransferListener#fileTransferRequestReceived(FileTransferRequestEvent)
*/
public void fileTransferRequestReceived(FileTransferRequestEvent event)
{
IncomingFileTransferRequest request = event.getRequest();
Contact sourceContact = request.getSender();
MetaContact metaContact = GuiActivator.getContactListService()
.findMetaContactByContact(sourceContact);
final ChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact, sourceContact);
chatPanel.addIncomingFileTransferRequest(
event.getFileTransferOperationSet(), request, event.getTimestamp());
ChatTransport chatTransport
= chatPanel.getChatSession()
.findChatTransportForDescriptor(sourceContact, null);
chatPanel.setSelectedChatTransport(chatTransport, true);
// Opens the chat panel with the new message in the UI thread.
chatWindowManager.openChat(chatPanel, false);
}
/**
* Nothing to do here, because we already know when a file transfer is
* created.
* @param event the <tt>FileTransferCreatedEvent</tt> that notified us
*/
public void fileTransferCreated(FileTransferCreatedEvent event)
{}
/**
* Called when a new <tt>IncomingFileTransferRequest</tt> has been rejected.
* Nothing to do here, because we are the one who rejects the request.
*
* @param event the <tt>FileTransferRequestEvent</tt> containing the
* received request which was rejected.
*/
public void fileTransferRequestRejected(FileTransferRequestEvent event)
{
}
/**
* Called when an <tt>IncomingFileTransferRequest</tt> has been canceled
* from the contact who sent it.
*
* @param event the <tt>FileTransferRequestEvent</tt> containing the
* request which was canceled.
*/
public void fileTransferRequestCanceled(FileTransferRequestEvent event)
{
}
/**
* Returns the right button menu of the contact list.
* @return the right button menu of the contact list
*/
public CommonRightButtonMenu getCommonRightButtonMenu()
{
return commonRightButtonMenu;
}
/**
* The TypingTimer is started after a PAUSED typing notification is
* received. It waits 5 seconds and if no other typing event occurs removes
* the PAUSED message from the chat status panel.
*/
private class TypingTimer extends Timer
{
/**
* Serial version UID.
*/
private static final long serialVersionUID = 0L;
private MetaContact metaContact;
public TypingTimer()
{
// Set delay
super(5 * 1000, null);
this.addActionListener(new TimerActionListener());
}
private class TimerActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
ChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact, false);
if (chatPanel != null)
chatPanel.removeTypingNotification();
}
}
private void setMetaContact(MetaContact metaContact)
{
this.metaContact = metaContact;
}
}
private void initPluginComponents()
{
// Search for plugin components registered through the OSGI bundle
// context.
ServiceReference[] serRefs = null;
String osgiFilter = "("
+ Container.CONTAINER_ID
+ "="+Container.CONTAINER_CONTACT_LIST.getID()+")";
try
{
serRefs = GuiActivator.bundleContext.getServiceReferences(
PluginComponentFactory.class.getName(),
osgiFilter);
}
catch (InvalidSyntaxException exc)
{
logger.error("Could not obtain plugin reference.", exc);
}
if (serRefs != null)
{
for (ServiceReference serRef : serRefs)
{
PluginComponentFactory factory =
(PluginComponentFactory)
GuiActivator.bundleContext.getService(serRef);
PluginComponent component =
factory.getPluginComponentInstance(this);
Object selectedValue = getContactList().getSelectedValue();
if(selectedValue instanceof MetaContact)
{
component.setCurrentContact((MetaContact)selectedValue);
}
else if(selectedValue instanceof MetaContactGroup)
{
component
.setCurrentContactGroup((MetaContactGroup)selectedValue);
}
String pluginConstraints = factory.getConstraints();
Object constraints;
if (pluginConstraints != null)
constraints = UIServiceImpl
.getBorderLayoutConstraintsFromContainer(
pluginConstraints);
else
constraints = BorderLayout.SOUTH;
this.add((Component)component.getComponent(), constraints);
this.repaint();
}
}
GuiActivator.getUIService().addPluginComponentListener(this);
}
/**
* Adds the plugin component given by <tt>event</tt> to this panel if it's
* its container.
* @param event the <tt>PluginComponentEvent</tt> that notified us
*/
public void pluginComponentAdded(PluginComponentEvent event)
{
PluginComponentFactory factory = event.getPluginComponentFactory();
// If the container id doesn't correspond to the id of the plugin
// container we're not interested.
if(!factory.getContainer().equals(Container.CONTAINER_CONTACT_LIST))
return;
Object constraints = UIServiceImpl
.getBorderLayoutConstraintsFromContainer(factory.getConstraints());
if (constraints == null)
constraints = BorderLayout.SOUTH;
PluginComponent pluginComponent =
factory.getPluginComponentInstance(this);
this.add((Component)pluginComponent.getComponent(), constraints);
Object selectedValue = getContactList().getSelectedValue();
if(selectedValue instanceof MetaContact)
{
pluginComponent
.setCurrentContact((MetaContact)selectedValue);
}
else if(selectedValue instanceof MetaContactGroup)
{
pluginComponent
.setCurrentContactGroup((MetaContactGroup)selectedValue);
}
this.revalidate();
this.repaint();
}
/**
* Removes the plugin component given by <tt>event</tt> if previously added
* in this panel.
* @param event the <tt>PluginComponentEvent</tt> that notified us
*/
public void pluginComponentRemoved(PluginComponentEvent event)
{
PluginComponentFactory factory = event.getPluginComponentFactory();
// If the container id doesn't correspond to the id of the plugin
// container we're not interested.
if(!factory.getContainer()
.equals(Container.CONTAINER_CONTACT_LIST))
return;
this.remove(
(Component)factory.getPluginComponentInstance(this).getComponent());
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | designer/datasource-editor-jdbc/src/main/java/org/pentaho/reporting/ui/datasources/jdbc/ui/JdbcQueryDesignerDialog.java | 5581 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2008 - 2018 Hitachi Vantara, . All rights reserved.
*/
package org.pentaho.reporting.ui.datasources.jdbc.ui;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.Locale;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.JFrame;
import nickyb.sqleonardo.querybuilder.QueryBuilder;
import nickyb.sqleonardo.querybuilder.QueryModel;
import nickyb.sqleonardo.querybuilder.syntax.SQLParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.designtime.DesignTimeContext;
import org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ConnectionProvider;
import org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.SimpleSQLReportDataFactory;
import org.pentaho.reporting.engine.classic.core.parameters.ReportParameterDefinition;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
import org.pentaho.reporting.libraries.base.util.ResourceBundleSupport;
import org.pentaho.reporting.libraries.designtime.swing.CommonDialog;
import org.pentaho.reporting.libraries.designtime.swing.background.DataPreviewDialog;
import org.pentaho.reporting.ui.datasources.jdbc.JdbcDataSourceModule;
/**
* @author David Kincade
*/
public class JdbcQueryDesignerDialog extends CommonDialog {
private class PreviewButtonAction extends AbstractAction {
private PreviewButtonAction() {
putValue( Action.NAME, getBundleSupport().getString( "JdbcDataSourceDialog.Preview" ) );
}
public void actionPerformed( final ActionEvent arg0 ) {
try {
final String query = getQuery();
final DataPreviewDialog dialog = new DataPreviewDialog( JdbcQueryDesignerDialog.this );
MasterReport report = (MasterReport) designTimeContext.getReport();
ReportParameterDefinition parameters = null;
if ( report != null ) {
parameters = report.getParameterDefinition();
}
dialog.showData( new JdbcPreviewWorker( new SimpleSQLReportDataFactory( getConnectionDefinition() ), query, 0, 0, parameters ) );
} catch ( Exception e ) {
log.warn( "QueryPanel.actionPerformed ", e );
if ( designTimeContext != null ) {
designTimeContext.userError( e );
}
}
}
}
private static final Log log = LogFactory.getLog( JdbcQueryDesignerDialog.class );
private QueryBuilder queryBuilder;
private ConnectionProvider connectionProvider;
private ResourceBundleSupport bundleSupport;
private DesignTimeContext designTimeContext;
public JdbcQueryDesignerDialog( final JDialog owner, final QueryBuilder queryBuilder ) {
super( owner );
if ( queryBuilder == null ) {
throw new NullPointerException();
}
setModal( true );
bundleSupport = new ResourceBundleSupport( Locale.getDefault(), JdbcDataSourceModule.MESSAGES,
ObjectUtilities.getClassLoader( JdbcDataSourceModule.class ) );
setTitle( bundleSupport.getString( "JdbcDataSourceDialog.SQLLeonardoTitle" ) );
this.queryBuilder = queryBuilder;
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
init();
}
protected void performInitialResize() {
setSize( 800, 600 );
setLocationRelativeTo( getParent() );
}
protected String getDialogId() {
return "JdbcDataSourceEditor.QueryDesigner";
}
protected Component createContentPane() {
return queryBuilder;
}
protected Action[] getExtraActions() {
return new Action[]{new PreviewButtonAction()};
}
public String designQuery( final DesignTimeContext designTimeContext,
final ConnectionProvider jndiSource,
final String schema, final String query ) {
this.designTimeContext = designTimeContext;
this.connectionProvider = jndiSource;
try {
final QueryModel queryModel = SQLParser.toQueryModel( query );
queryBuilder.setQueryModel( queryModel );
} catch ( Exception e1 ) {
log.warn( "QueryPanel.actionPerformed ", e1 );
}
try {
if ( schema != null ) {
final QueryModel qm = queryBuilder.getQueryModel();
qm.setSchema( schema );
queryBuilder.setQueryModel( qm );
}
} catch ( Exception e1 ) {
log.warn( "QueryPanel.actionPerformed ", e1 );
}
if ( performEdit() ) {
return getQuery();
}
return null;
}
protected ConnectionProvider getConnectionDefinition() {
return connectionProvider;
}
protected String getQuery() {
return queryBuilder.getQueryModel().toString( true );
}
protected ResourceBundleSupport getBundleSupport() {
return bundleSupport;
}
}
| lgpl-2.1 |
noahc3/abilitystones | src/main/java/com/noahc3/abilitystones/recipe/AdvRecipe.java | 468 | package com.noahc3.abilitystones.recipe;
import java.util.ArrayList;
public class AdvRecipe {
public String output;
public int dustCost;
public ArrayList<ItemGroup> recipe = new ArrayList<>();
public AdvRecipe(String output, int dustCost, ItemGroup ... itemGroups) {
this.output = output;
this.dustCost = dustCost;
for(int i=0; i < itemGroups.length; i++) {
this.recipe.add(itemGroups[i]);
}
}
}
| lgpl-2.1 |
ambs/exist | exist-core/src/main/java/org/exist/util/Configuration.java | 75650 | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* 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-1301 USA
*/
package org.exist.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.backup.SystemExport;
import org.exist.collections.CollectionCache;
import org.exist.repo.Deployment;
import org.exist.start.Main;
import org.exist.storage.lock.LockManager;
import org.exist.storage.lock.LockTable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.exist.Indexer;
import org.exist.indexing.IndexManager;
import org.exist.dom.memtree.SAXAdapter;
import org.exist.scheduler.JobConfig;
import org.exist.scheduler.JobException;
import org.exist.storage.BrokerFactory;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.IndexSpec;
import org.exist.storage.NativeBroker;
import org.exist.storage.NativeValueIndex;
import org.exist.storage.XQueryPool;
import org.exist.storage.journal.Journal;
import org.exist.storage.serializers.CustomMatchListenerFactory;
import org.exist.storage.serializers.Serializer;
import org.exist.validation.GrammarPool;
import org.exist.validation.resolver.eXistXMLCatalogResolver;
import org.exist.xmldb.DatabaseImpl;
import org.exist.xquery.FunctionFactory;
import org.exist.xquery.PerformanceStats;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.XQueryWatchDog;
import org.exist.xslt.TransformerFactoryAllocator;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.exist.Namespaces;
import org.exist.scheduler.JobType;
import org.exist.xquery.Module;
import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING;
public class Configuration implements ErrorHandler
{
private final static Logger LOG = LogManager.getLogger(Configuration.class); //Logger
protected Optional<Path> configFilePath = Optional.empty();
protected Optional<Path> existHome = Optional.empty();
protected DocumentBuilder builder = null;
protected HashMap<String, Object> config = new HashMap<>(); //Configuration
private static final String XQUERY_CONFIGURATION_ELEMENT_NAME = "xquery";
private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME = "builtin-modules";
private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME = "module";
public final static String BINARY_CACHE_CLASS_PROPERTY = "binary.cache.class";
public Configuration() throws DatabaseConfigurationException {
this(DatabaseImpl.CONF_XML, Optional.empty());
}
public Configuration(final String configFilename) throws DatabaseConfigurationException {
this(configFilename, Optional.empty());
}
public Configuration(String configFilename, Optional<Path> existHomeDirname) throws DatabaseConfigurationException {
InputStream is = null;
try {
if(configFilename == null) {
// Default file name
configFilename = DatabaseImpl.CONF_XML;
}
// firstly, try to read the configuration from a file within the
// classpath
try {
is = Configuration.class.getClassLoader().getResourceAsStream(configFilename);
if(is != null) {
LOG.info("Reading configuration from classloader");
configFilePath = Optional.of(Paths.get(Configuration.class.getClassLoader().getResource(configFilename).toURI()));
}
} catch(final Exception e) {
// EB: ignore and go forward, e.g. in case there is an absolute
// file name for configFileName
LOG.debug( e );
}
// otherwise, secondly try to read configuration from file. Guess the
// location if necessary
if(is == null) {
existHome = existHomeDirname.map(Optional::of).orElse(ConfigurationHelper.getExistHome(configFilename));
if(!existHome.isPresent()) {
// EB: try to create existHome based on location of config file
// when config file points to absolute file location
final Path absoluteConfigFile = Paths.get(configFilename);
if(absoluteConfigFile.isAbsolute() && Files.exists(absoluteConfigFile) && Files.isReadable(absoluteConfigFile)) {
existHome = Optional.of(absoluteConfigFile.getParent());
configFilename = FileUtils.fileName(absoluteConfigFile);
}
}
Path configFile = Paths.get(configFilename);
if(!configFile.isAbsolute() && existHome.isPresent()) {
// try the passed or constructed existHome first
configFile = existHome.get().resolve(configFilename);
if (!Files.exists(configFile)) {
configFile = existHome.get().resolve(Main.CONFIG_DIR_NAME).resolve(configFilename);
}
}
//if( configFile == null ) {
// configFile = ConfigurationHelper.lookup( configFilename );
//}
if(!Files.exists(configFile) || !Files.isReadable(configFile)) {
throw new DatabaseConfigurationException("Unable to read configuration file at " + configFile);
}
configFilePath = Optional.of(configFile.toAbsolutePath());
is = Files.newInputStream(configFile);
}
LOG.info("Reading configuration from file " + configFilePath.map(Path::toString).orElse("Unknown"));
// set dbHome to parent of the conf file found, to resolve relative
// path from conf file
existHomeDirname = configFilePath.map(Path::getParent);
// initialize xml parser
// we use eXist's in-memory DOM implementation to work
// around a bug in Xerces
final SAXParserFactory factory = ExistSAXParserFactory.getSAXParserFactory();
factory.setNamespaceAware(true);
// factory.setFeature("http://apache.org/xml/features/validation/schema", true);
// factory.setFeature("http://apache.org/xml/features/validation/dynamic", true);
final InputSource src = new InputSource(is);
final SAXParser parser = factory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
reader.setFeature(FEATURE_SECURE_PROCESSING, true);
final SAXAdapter adapter = new SAXAdapter();
reader.setContentHandler(adapter);
reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
reader.parse(src);
final Document doc = adapter.getDocument();
//indexer settings
final NodeList indexers = doc.getElementsByTagName(Indexer.CONFIGURATION_ELEMENT_NAME);
if(indexers.getLength() > 0) {
configureIndexer( existHomeDirname, doc, (Element)indexers.item( 0 ) );
}
//scheduler settings
final NodeList schedulers = doc.getElementsByTagName(JobConfig.CONFIGURATION_ELEMENT_NAME);
if(schedulers.getLength() > 0) {
configureScheduler((Element)schedulers.item(0));
}
//db connection settings
final NodeList dbcon = doc.getElementsByTagName(BrokerPool.CONFIGURATION_CONNECTION_ELEMENT_NAME);
if(dbcon.getLength() > 0) {
configureBackend(existHomeDirname, (Element)dbcon.item(0));
}
// lock-table settings
final NodeList lockManager = doc.getElementsByTagName("lock-manager");
if(lockManager.getLength() > 0) {
configureLockManager((Element) lockManager.item(0));
}
// repository settings
final NodeList repository = doc.getElementsByTagName("repository");
if(repository.getLength() > 0) {
configureRepository((Element) repository.item(0));
}
// binary manager settings
final NodeList binaryManager = doc.getElementsByTagName("binary-manager");
if(binaryManager.getLength() > 0) {
configureBinaryManager((Element)binaryManager.item(0));
}
//transformer settings
final NodeList transformers = doc.getElementsByTagName(TransformerFactoryAllocator.CONFIGURATION_ELEMENT_NAME);
if( transformers.getLength() > 0 ) {
configureTransformer((Element)transformers.item(0));
}
//parser settings
final NodeList parsers = doc.getElementsByTagName(HtmlToXmlParser.PARSER_ELEMENT_NAME);
if(parsers.getLength() > 0) {
configureParser((Element)parsers.item(0));
}
//serializer settings
final NodeList serializers = doc.getElementsByTagName(Serializer.CONFIGURATION_ELEMENT_NAME);
if(serializers.getLength() > 0) {
configureSerializer((Element)serializers.item(0));
}
//XUpdate settings
final NodeList xupdates = doc.getElementsByTagName(DBBroker.CONFIGURATION_ELEMENT_NAME);
if(xupdates.getLength() > 0) {
configureXUpdate((Element)xupdates.item(0));
}
//XQuery settings
final NodeList xquery = doc.getElementsByTagName(XQUERY_CONFIGURATION_ELEMENT_NAME);
if(xquery.getLength() > 0) {
configureXQuery((Element)xquery.item(0));
}
//Validation
final NodeList validations = doc.getElementsByTagName(XMLReaderObjectFactory.CONFIGURATION_ELEMENT_NAME);
if(validations.getLength() > 0) {
configureValidation(existHomeDirname, doc, (Element)validations.item(0));
}
}
catch(final SAXException | IOException | ParserConfigurationException e) {
LOG.error("error while reading config file: " + configFilename, e);
throw new DatabaseConfigurationException(e.getMessage(), e);
} finally {
if(is != null) {
try {
is.close();
} catch(final IOException ioe) {
LOG.error(ioe);
}
}
}
}
private void configureLockManager(final Element lockManager) throws DatabaseConfigurationException {
final boolean upgradeCheck = parseBoolean(getConfigAttributeValue(lockManager, "upgrade-check"), false);
final boolean warnWaitOnReadForWrite = parseBoolean(getConfigAttributeValue(lockManager, "warn-wait-on-read-for-write"), false);
final boolean pathsMultiWriter = parseBoolean(getConfigAttributeValue(lockManager, "paths-multi-writer"), false);
config.put(LockManager.CONFIGURATION_UPGRADE_CHECK, upgradeCheck);
config.put(LockManager.CONFIGURATION_WARN_WAIT_ON_READ_FOR_WRITE, warnWaitOnReadForWrite);
config.put(LockManager.CONFIGURATION_PATHS_MULTI_WRITER, pathsMultiWriter);
final NodeList nlLockTable = lockManager.getElementsByTagName("lock-table");
if(nlLockTable.getLength() > 0) {
final Element lockTable = (Element)nlLockTable.item(0);
final boolean lockTableDisabled = parseBoolean(getConfigAttributeValue(lockTable, "disabled"), false);
final int lockTableTraceStackDepth = parseInt(getConfigAttributeValue(lockTable, "trace-stack-depth"), 0);
config.put(LockTable.CONFIGURATION_DISABLED, lockTableDisabled);
config.put(LockTable.CONFIGURATION_TRACE_STACK_DEPTH, lockTableTraceStackDepth);
}
final NodeList nlDocument = lockManager.getElementsByTagName("document");
if(nlDocument.getLength() > 0) {
final Element document = (Element)nlDocument.item(0);
final boolean documentUsePathLocks = parseBoolean(getConfigAttributeValue(document, "use-path-locks"), false);
config.put(LockManager.CONFIGURATION_PATH_LOCKS_FOR_DOCUMENTS, documentUsePathLocks);
}
}
private void configureRepository(Element element) {
String root = getConfigAttributeValue(element, "root");
if (root != null && !root.isEmpty()) {
if (!root.endsWith("/"))
{root += "/";}
config.put(Deployment.PROPERTY_APP_ROOT, root);
}
}
private void configureBinaryManager(Element binaryManager) throws DatabaseConfigurationException {
final NodeList nlCache = binaryManager.getElementsByTagName("cache");
if(nlCache.getLength() > 0) {
final Element cache = (Element)nlCache.item(0);
final String binaryCacheClass = getConfigAttributeValue(cache, "class");
config.put(BINARY_CACHE_CLASS_PROPERTY, binaryCacheClass);
LOG.debug(BINARY_CACHE_CLASS_PROPERTY + ": " + config.get(BINARY_CACHE_CLASS_PROPERTY));
}
}
private void configureXQuery( Element xquery ) throws DatabaseConfigurationException
{
//java binding
final String javabinding = getConfigAttributeValue( xquery, FunctionFactory.ENABLE_JAVA_BINDING_ATTRIBUTE );
if( javabinding != null ) {
config.put( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING, javabinding );
LOG.debug( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING + ": " + config.get( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING ) );
}
final String disableDeprecated = getConfigAttributeValue( xquery, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_ATTRIBUTE );
config.put( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS, Configuration.parseBoolean( disableDeprecated, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_BY_DEFAULT ) );
LOG.debug( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS + ": " + config.get( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS ) );
final String optimize = getConfigAttributeValue( xquery, XQueryContext.ENABLE_QUERY_REWRITING_ATTRIBUTE );
if( ( optimize != null ) && (!optimize.isEmpty()) ) {
config.put( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING, optimize );
LOG.debug( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING + ": " + config.get( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING ) );
}
final String enforceIndexUse = getConfigAttributeValue( xquery, XQueryContext.ENFORCE_INDEX_USE_ATTRIBUTE );
if (enforceIndexUse != null) {
config.put( XQueryContext.PROPERTY_ENFORCE_INDEX_USE, enforceIndexUse );
}
final String backwardCompatible = getConfigAttributeValue( xquery, XQueryContext.XQUERY_BACKWARD_COMPATIBLE_ATTRIBUTE );
if( ( backwardCompatible != null ) && (!backwardCompatible.isEmpty()) ) {
config.put( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE, backwardCompatible );
LOG.debug( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE + ": " + config.get( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE ) );
}
final String raiseErrorOnFailedRetrieval = getConfigAttributeValue( xquery, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_ATTRIBUTE );
config.put( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, Configuration.parseBoolean( raiseErrorOnFailedRetrieval, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_DEFAULT ) );
LOG.debug( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL + ": " + config.get( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL ) );
final String trace = getConfigAttributeValue( xquery, PerformanceStats.CONFIG_ATTR_TRACE );
config.put( PerformanceStats.CONFIG_PROPERTY_TRACE, trace );
// built-in-modules
final Map<String, Class<?>> classMap = new HashMap<>();
final Map<String, String> knownMappings = new HashMap<>();
final Map<String, Map<String, List<? extends Object>>> moduleParameters = new HashMap<>();
loadModuleClasses(xquery, classMap, knownMappings, moduleParameters);
config.put( XQueryContext.PROPERTY_BUILT_IN_MODULES, classMap);
config.put( XQueryContext.PROPERTY_STATIC_MODULE_MAP, knownMappings);
config.put( XQueryContext.PROPERTY_MODULE_PARAMETERS, moduleParameters);
}
/**
* Read list of built-in modules from the configuration. This method will only make sure
* that the specified module class exists and is a subclass of {@link org.exist.xquery.Module}.
*
* @param xquery configuration root
* @param modulesClassMap map containing all classes of modules
* @param modulesSourceMap map containing all source uris to external resources
*
* @throws DatabaseConfigurationException
*/
private void loadModuleClasses( Element xquery, Map<String, Class<?>> modulesClassMap, Map<String, String> modulesSourceMap, Map<String, Map<String, List<? extends Object>>> moduleParameters) throws DatabaseConfigurationException {
// add the standard function module
modulesClassMap.put(Namespaces.XPATH_FUNCTIONS_NS, org.exist.xquery.functions.fn.FnModule.class);
// add other modules specified in configuration
final NodeList builtins = xquery.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME);
// search under <builtin-modules>
if(builtins.getLength() > 0) {
Element elem = (Element)builtins.item(0);
final NodeList modules = elem.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME);
if(modules.getLength() > 0) {
// iterate over all <module src= uri= class=> entries
for(int i = 0; i < modules.getLength(); i++) {
// Get element.
elem = (Element)modules.item(i);
// Get attributes uri class and src
final String uri = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_URI_ATTRIBUTE);
final String clazz = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_CLASS_ATTRIBUTE);
final String source = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_SOURCE_ATTRIBUTE);
// uri attribute is the identifier and is always required
if(uri == null) {
throw(new DatabaseConfigurationException("element 'module' requires an attribute 'uri'" ));
}
// either class or source attribute must be present
if((clazz == null) && (source == null)) {
throw(new DatabaseConfigurationException("element 'module' requires either an attribute " + "'class' or 'src'" ));
}
if(source != null) {
// Store src attribute info
modulesSourceMap.put(uri, source);
if(LOG.isDebugEnabled()) {
LOG.debug( "Registered mapping for module '" + uri + "' to '" + source + "'");
}
} else {
// source class attribute info
// Get class of module
final Class<?> moduleClass = lookupModuleClass(uri, clazz);
// Store class if thw module class actually exists
if( moduleClass != null) {
modulesClassMap.put(uri, moduleClass);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Configured module '" + uri + "' implemented in '" + clazz + "'");
}
}
//parse any module parameters
moduleParameters.put(uri, ParametersExtractor.extract(elem.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME)));
}
}
}
}
/**
* Returns the Class object associated with the with the given module class name. All
* important exceptions are caught. @see org.exist.xquery.Module
*
* @param uri namespace of class. For logging purposes only.
* @param clazz the fully qualified name of the desired module class.
* @return the module Class object for the module with the specified name.
* @throws DatabaseConfigurationException if the given module class is not an instance
* of org.exist.xquery.Module
*/
private Class<?> lookupModuleClass(String uri, String clazz) throws DatabaseConfigurationException
{
Class<?> mClass = null;
try {
mClass = Class.forName( clazz );
if( !( Module.class.isAssignableFrom( mClass ) ) ) {
throw( new DatabaseConfigurationException( "Failed to load module: " + uri
+ ". Class " + clazz + " is not an instance of org.exist.xquery.Module." ) );
}
} catch( final ClassNotFoundException e ) {
// Note: can't throw an exception here since this would create
// problems with test cases and jar dependencies
LOG.error( "Configuration problem: class not found for module '" + uri
+ "' (ClassNotFoundException); class:'" + clazz
+ "'; message:'" + e.getMessage() + "'");
} catch( final NoClassDefFoundError e ) {
LOG.error( "Module " + uri + " could not be initialized due to a missing "
+ "dependancy (NoClassDefFoundError): " + e.getMessage(), e );
}
return mClass;
}
/**
* DOCUMENT ME!
*
* @param xupdate
*
* @throws NumberFormatException
*/
private void configureXUpdate( Element xupdate ) throws NumberFormatException
{
final String fragmentation = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_FRAGMENTATION_FACTOR_ATTRIBUTE );
if( fragmentation != null ) {
config.put( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR, Integer.valueOf(fragmentation) );
LOG.debug( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR + ": " + config.get( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR ) );
}
final String consistencyCheck = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_CONSISTENCY_CHECKS_ATTRIBUTE );
if( consistencyCheck != null ) {
config.put( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS, parseBoolean( consistencyCheck, false ) );
LOG.debug( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS + ": " + config.get( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS ) );
}
}
private void configureTransformer( Element transformer )
{
final String className = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CLASS_ATTRIBUTE );
if( className != null ) {
config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS, className );
LOG.debug( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS + ": " + config.get( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS ) );
// Process any specified attributes that should be passed to the transformer factory
final NodeList attrs = transformer.getElementsByTagName( TransformerFactoryAllocator.CONFIGURATION_TRANSFORMER_ATTRIBUTE_ELEMENT_NAME );
final Hashtable<Object, Object> attributes = new Properties();
for( int a = 0; a < attrs.getLength(); a++ ) {
final Element attr = (Element)attrs.item( a );
final String name = attr.getAttribute( "name" );
final String value = attr.getAttribute( "value" );
final String type = attr.getAttribute( "type" );
if( ( name == null ) || (name.isEmpty()) ) {
LOG.warn( "Discarded invalid attribute for TransformerFactory: '" + className + "', name not specified" );
} else if( ( type == null ) || (type.isEmpty()) || type.equalsIgnoreCase( "string" ) ) {
attributes.put( name, value );
} else if( type.equalsIgnoreCase( "boolean" ) ) {
attributes.put( name, Boolean.valueOf( value ) );
} else if( type.equalsIgnoreCase( "integer" ) ) {
try {
attributes.put( name, Integer.valueOf( value ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Discarded invalid attribute for TransformerFactory: '" + className + "', name: " + name + ", value not integer: " + value, nfe);
}
} else {
// Assume string type
attributes.put( name, value );
}
}
config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_ATTRIBUTES, attributes );
}
final String cachingValue = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CACHING_ATTRIBUTE );
if( cachingValue != null ) {
config.put( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE, parseBoolean( cachingValue, false ) );
LOG.debug( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE + ": " + config.get( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE ) );
}
}
private void configureParser(final Element parser) {
configureXmlParser(parser);
configureHtmlToXmlParser(parser);
}
private void configureXmlParser(final Element parser) {
final NodeList nlXml = parser.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_ELEMENT);
if(nlXml.getLength() > 0) {
final Element xml = (Element)nlXml.item(0);
final NodeList nlFeatures = xml.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_ELEMENT);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_PROPERTY, features);
}
}
}
}
private void configureHtmlToXmlParser(final Element parser) {
final NodeList nlHtmlToXml = parser.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_ELEMENT);
if(nlHtmlToXml.getLength() > 0) {
final Element htmlToXml = (Element)nlHtmlToXml.item(0);
final String htmlToXmlParserClass = getConfigAttributeValue(htmlToXml, HtmlToXmlParser.HTML_TO_XML_PARSER_CLASS_ATTRIBUTE);
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTY, htmlToXmlParserClass);
final NodeList nlProperties = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_ELEMENT);
if(nlProperties.getLength() > 0) {
final Properties pProperties = ParametersExtractor.parseProperties(nlProperties.item(0));
if(pProperties != null) {
final Map<String, Object> properties = new HashMap<>();
pProperties.forEach((k,v) -> properties.put(k.toString(), v));
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_PROPERTY, properties);
}
}
final NodeList nlFeatures = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_ELEMENT);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_PROPERTY, features);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param serializer
*/
private void configureSerializer( Element serializer )
{
final String xinclude = getConfigAttributeValue( serializer, Serializer.ENABLE_XINCLUDE_ATTRIBUTE );
if( xinclude != null ) {
config.put( Serializer.PROPERTY_ENABLE_XINCLUDE, xinclude );
LOG.debug( Serializer.PROPERTY_ENABLE_XINCLUDE + ": " + config.get( Serializer.PROPERTY_ENABLE_XINCLUDE ) );
}
final String xsl = getConfigAttributeValue( serializer, Serializer.ENABLE_XSL_ATTRIBUTE );
if( xsl != null ) {
config.put( Serializer.PROPERTY_ENABLE_XSL, xsl );
LOG.debug( Serializer.PROPERTY_ENABLE_XSL + ": " + config.get( Serializer.PROPERTY_ENABLE_XSL ) );
}
final String indent = getConfigAttributeValue( serializer, Serializer.INDENT_ATTRIBUTE );
if( indent != null ) {
config.put( Serializer.PROPERTY_INDENT, indent );
LOG.debug( Serializer.PROPERTY_INDENT + ": " + config.get( Serializer.PROPERTY_INDENT ) );
}
final String compress = getConfigAttributeValue( serializer, Serializer.COMPRESS_OUTPUT_ATTRIBUTE );
if( compress != null ) {
config.put( Serializer.PROPERTY_COMPRESS_OUTPUT, compress );
LOG.debug( Serializer.PROPERTY_COMPRESS_OUTPUT + ": " + config.get( Serializer.PROPERTY_COMPRESS_OUTPUT ) );
}
final String internalId = getConfigAttributeValue( serializer, Serializer.ADD_EXIST_ID_ATTRIBUTE );
if( internalId != null ) {
config.put( Serializer.PROPERTY_ADD_EXIST_ID, internalId );
LOG.debug( Serializer.PROPERTY_ADD_EXIST_ID + ": " + config.get( Serializer.PROPERTY_ADD_EXIST_ID ) );
}
final String tagElementMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ELEMENTS_ATTRIBUTE );
if( tagElementMatches != null ) {
config.put( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS, tagElementMatches );
LOG.debug( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS + ": " + config.get( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS ) );
}
final String tagAttributeMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ATTRIBUTES_ATTRIBUTE );
if( tagAttributeMatches != null ) {
config.put( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES, tagAttributeMatches );
LOG.debug( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES + ": " + config.get( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES ) );
}
final NodeList nlFilters = serializer.getElementsByTagName( CustomMatchListenerFactory.CONFIGURATION_ELEMENT );
if( nlFilters != null ) {
final List<String> filters = new ArrayList<>(nlFilters.getLength());
for (int i = 0; i < nlFilters.getLength(); i++) {
final Element filterElem = (Element) nlFilters.item(i);
final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": " + filterClass);
} else {
LOG.warn("Configuration element " + CustomMatchListenerFactory.CONFIGURATION_ELEMENT + " needs an attribute 'class'");
}
}
config.put(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS, filters);
}
final NodeList backupFilters = serializer.getElementsByTagName( SystemExport.CONFIGURATION_ELEMENT );
if( backupFilters != null ) {
final List<String> filters = new ArrayList<>(backupFilters.getLength());
for (int i = 0; i < backupFilters.getLength(); i++) {
final Element filterElem = (Element) backupFilters.item(i);
final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": " + filterClass);
} else {
LOG.warn("Configuration element " + SystemExport.CONFIGURATION_ELEMENT + " needs an attribute 'class'");
}
}
if (!filters.isEmpty()) config.put(SystemExport.CONFIG_FILTERS, filters);
}
}
/**
* Reads the scheduler configuration.
*
* @param scheduler DOCUMENT ME!
*/
private void configureScheduler(final Element scheduler)
{
final NodeList nlJobs = scheduler.getElementsByTagName(JobConfig.CONFIGURATION_JOB_ELEMENT_NAME);
if(nlJobs == null) {
return;
}
final List<JobConfig> jobList = new ArrayList<>();
for(int i = 0; i < nlJobs.getLength(); i++) {
final Element job = (Element)nlJobs.item( i );
//get the job type
final String strJobType = getConfigAttributeValue(job, JobConfig.JOB_TYPE_ATTRIBUTE);
final JobType jobType;
if(strJobType == null) {
jobType = JobType.USER; //default to user if unspecified
} else {
jobType = JobType.valueOf(strJobType.toUpperCase(Locale.ENGLISH));
}
final String jobName = getConfigAttributeValue(job, JobConfig.JOB_NAME_ATTRIBUTE);
//get the job resource
String jobResource = getConfigAttributeValue(job, JobConfig.JOB_CLASS_ATTRIBUTE);
if(jobResource == null) {
jobResource = getConfigAttributeValue(job, JobConfig.JOB_XQUERY_ATTRIBUTE);
}
//get the job schedule
String jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_CRON_TRIGGER_ATTRIBUTE);
if(jobSchedule == null) {
jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_PERIOD_ATTRIBUTE);
}
final String jobUnschedule = getConfigAttributeValue(job, JobConfig.JOB_UNSCHEDULE_ON_EXCEPTION);
//create the job config
try {
final JobConfig jobConfig = new JobConfig(jobType, jobName, jobResource, jobSchedule, jobUnschedule);
//get and set the job delay
final String jobDelay = getConfigAttributeValue(job, JobConfig.JOB_DELAY_ATTRIBUTE);
if((jobDelay != null) && (!jobDelay.isEmpty())) {
jobConfig.setDelay(Long.parseLong(jobDelay));
}
//get and set the job repeat
final String jobRepeat = getConfigAttributeValue(job, JobConfig.JOB_REPEAT_ATTRIBUTE);
if((jobRepeat != null) && (!jobRepeat.isEmpty())) {
jobConfig.setRepeat(Integer.parseInt(jobRepeat));
}
final NodeList nlParam = job.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME);
final Map<String, List<? extends Object>> params = ParametersExtractor.extract(nlParam);
for(final Entry<String, List<? extends Object>> param : params.entrySet()) {
final List<? extends Object> values = param.getValue();
if(values != null && !values.isEmpty()) {
jobConfig.addParameter(param.getKey(), values.get(0).toString());
if(values.size() > 1) {
LOG.warn("Parameter '" + param.getKey() + "' for job '" + jobName + "' has more than one value, ignoring further values.");
}
}
}
jobList.add(jobConfig);
LOG.debug("Configured scheduled '" + jobType + "' job '" + jobResource + ((jobSchedule == null) ? "" : ("' with trigger '" + jobSchedule)) + ((jobDelay == null) ? "" : ("' with delay '" + jobDelay)) + ((jobRepeat == null) ? "" : ("' repetitions '" + jobRepeat)) + "'");
} catch(final JobException je) {
LOG.error(je);
}
}
if(!jobList.isEmpty()) {
final JobConfig[] configs = new JobConfig[jobList.size()];
for(int i = 0; i < jobList.size(); i++) {
configs[i] = (JobConfig)jobList.get(i);
}
config.put(JobConfig.PROPERTY_SCHEDULER_JOBS, configs);
}
}
/**
* DOCUMENT ME!
*
* @param dbHome
* @param con
*
* @throws DatabaseConfigurationException
*/
private void configureBackend( final Optional<Path> dbHome, Element con ) throws DatabaseConfigurationException
{
final String database = getConfigAttributeValue(con, BrokerFactory.PROPERTY_DATABASE);
if (database != null) {
config.put(BrokerFactory.PROPERTY_DATABASE, database);
LOG.debug(BrokerFactory.PROPERTY_DATABASE + ": " + config.get(BrokerFactory.PROPERTY_DATABASE));
}
// directory for database files
final String dataFiles = getConfigAttributeValue( con, BrokerPool.DATA_DIR_ATTRIBUTE );
if (dataFiles != null) {
final Path df = ConfigurationHelper.lookup( dataFiles, dbHome );
if (!Files.isReadable(df)) {
try {
Files.createDirectories(df);
} catch (final IOException ioe) {
throw new DatabaseConfigurationException("cannot read data directory: " + df.toAbsolutePath().toString(), ioe);
}
}
config.put(BrokerPool.PROPERTY_DATA_DIR, df.toAbsolutePath());
LOG.debug(BrokerPool.PROPERTY_DATA_DIR + ": " + config.get(BrokerPool.PROPERTY_DATA_DIR));
}
String cacheMem = getConfigAttributeValue( con, DefaultCacheManager.CACHE_SIZE_ATTRIBUTE );
if( cacheMem != null ) {
if( cacheMem.endsWith( "M" ) || cacheMem.endsWith( "m" ) ) {
cacheMem = cacheMem.substring( 0, cacheMem.length() - 1 );
}
try {
config.put( DefaultCacheManager.PROPERTY_CACHE_SIZE, Integer.valueOf(cacheMem) );
LOG.debug( DefaultCacheManager.PROPERTY_CACHE_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_SIZE ) + "m" );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + DefaultCacheManager.PROPERTY_CACHE_SIZE + " value to integer: " + cacheMem, nfe);
}
}
// Process the Check Max Cache value
String checkMaxCache = getConfigAttributeValue( con, DefaultCacheManager.CACHE_CHECK_MAX_SIZE_ATTRIBUTE );
if( checkMaxCache == null ) {
checkMaxCache = DefaultCacheManager.DEFAULT_CACHE_CHECK_MAX_SIZE_STRING;
}
config.put( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE, parseBoolean( checkMaxCache, true ) );
LOG.debug( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE ) );
String cacheShrinkThreshold = getConfigAttributeValue( con, DefaultCacheManager.SHRINK_THRESHOLD_ATTRIBUTE );
if( cacheShrinkThreshold == null ) {
cacheShrinkThreshold = DefaultCacheManager.DEFAULT_SHRINK_THRESHOLD_STRING;
}
try {
config.put(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY, Integer.valueOf(cacheShrinkThreshold));
LOG.debug(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + ": " + config.get(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY));
} catch(final NumberFormatException nfe) {
LOG.warn("Cannot convert " + DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + " value to integer: " + cacheShrinkThreshold, nfe);
}
String collectionCache = getConfigAttributeValue(con, CollectionCache.CACHE_SIZE_ATTRIBUTE);
if(collectionCache != null) {
collectionCache = collectionCache.toLowerCase();
try {
final int collectionCacheBytes;
if(collectionCache.endsWith("k")) {
collectionCacheBytes = 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("kb")) {
collectionCacheBytes = 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("m")) {
collectionCacheBytes = 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("mb")) {
collectionCacheBytes = 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("g")) {
collectionCacheBytes = 1024 * 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("gb")) {
collectionCacheBytes = 1024 * 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else {
collectionCacheBytes = Integer.parseInt(collectionCache);
}
config.put(CollectionCache.PROPERTY_CACHE_SIZE_BYTES, collectionCacheBytes);
if(LOG.isDebugEnabled()) {
LOG.debug("Set config {} = {}", CollectionCache.PROPERTY_CACHE_SIZE_BYTES, config.get(CollectionCache.PROPERTY_CACHE_SIZE_BYTES));
}
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + CollectionCache.PROPERTY_CACHE_SIZE_BYTES + " value to integer: " + collectionCache, nfe);
}
}
final String pageSize = getConfigAttributeValue( con, NativeBroker.PAGE_SIZE_ATTRIBUTE );
if( pageSize != null ) {
try {
config.put( BrokerPool.PROPERTY_PAGE_SIZE, Integer.valueOf(pageSize) );
LOG.debug( BrokerPool.PROPERTY_PAGE_SIZE + ": " + config.get( BrokerPool.PROPERTY_PAGE_SIZE ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_PAGE_SIZE + " value to integer: " + pageSize, nfe);
}
}
//Not clear : rather looks like a buffers count
final String collCacheSize = getConfigAttributeValue( con, BrokerPool.COLLECTION_CACHE_SIZE_ATTRIBUTE );
if( collCacheSize != null ) {
try {
config.put( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE, Integer.valueOf(collCacheSize) );
LOG.debug( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + ": " + config.get( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + " value to integer: " + collCacheSize, nfe);
}
}
final String nodesBuffer = getConfigAttributeValue( con, BrokerPool.NODES_BUFFER_ATTRIBUTE );
if( nodesBuffer != null ) {
try {
config.put( BrokerPool.PROPERTY_NODES_BUFFER, Integer.valueOf(nodesBuffer) );
LOG.debug( BrokerPool.PROPERTY_NODES_BUFFER + ": " + config.get( BrokerPool.PROPERTY_NODES_BUFFER ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_NODES_BUFFER + " value to integer: " + nodesBuffer, nfe);
}
}
String diskSpace = getConfigAttributeValue(con, BrokerPool.DISK_SPACE_MIN_ATTRIBUTE);
if( diskSpace != null ) {
if( diskSpace.endsWith( "M" ) || diskSpace.endsWith( "m" ) ) {
diskSpace = diskSpace.substring( 0, diskSpace.length() - 1 );
}
try {
config.put(BrokerPool.DISK_SPACE_MIN_PROPERTY, Short.valueOf(diskSpace));
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.DISK_SPACE_MIN_PROPERTY + " value to integer: " + diskSpace, nfe);
}
}
final String posixChownRestrictedStr = getConfigAttributeValue(con, DBBroker.POSIX_CHOWN_RESTRICTED_ATTRIBUTE);
final boolean posixChownRestricted;
if(posixChownRestrictedStr == null) {
posixChownRestricted = true; // default
} else {
if(Boolean.parseBoolean(posixChownRestrictedStr)) {
posixChownRestricted = true;
} else {
// configuration explicitly specifies that posix chown should NOT be restricted
posixChownRestricted = false;
}
}
config.put(DBBroker.POSIX_CHOWN_RESTRICTED_PROPERTY, posixChownRestricted);
final String preserveOnCopyStr = getConfigAttributeValue(con, DBBroker.PRESERVE_ON_COPY_ATTRIBUTE);
final DBBroker.PreserveType preserveOnCopy;
if(preserveOnCopyStr == null) {
preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE; // default
} else {
if(Boolean.parseBoolean(preserveOnCopyStr)) {
// configuration explicitly specifies that attributes should be preserved on copy
preserveOnCopy = DBBroker.PreserveType.PRESERVE;
} else {
preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE;
}
}
config.put(DBBroker.PRESERVE_ON_COPY_PROPERTY, preserveOnCopy);
final NodeList startupConf = con.getElementsByTagName(BrokerPool.CONFIGURATION_STARTUP_ELEMENT_NAME);
if(startupConf.getLength() > 0) {
configureStartup((Element)startupConf.item(0));
} else {
// Prevent NPE
final List<StartupTriggerConfig> startupTriggers = new ArrayList<>();
config.put(BrokerPool.PROPERTY_STARTUP_TRIGGERS, startupTriggers);
}
final NodeList poolConf = con.getElementsByTagName( BrokerPool.CONFIGURATION_POOL_ELEMENT_NAME );
if( poolConf.getLength() > 0 ) {
configurePool( (Element)poolConf.item( 0 ) );
}
final NodeList queryPoolConf = con.getElementsByTagName( XQueryPool.CONFIGURATION_ELEMENT_NAME );
if( queryPoolConf.getLength() > 0 ) {
configureXQueryPool( (Element)queryPoolConf.item( 0 ) );
}
final NodeList watchConf = con.getElementsByTagName( XQueryWatchDog.CONFIGURATION_ELEMENT_NAME );
if( watchConf.getLength() > 0 ) {
configureWatchdog( (Element)watchConf.item( 0 ) );
}
final NodeList recoveries = con.getElementsByTagName( BrokerPool.CONFIGURATION_RECOVERY_ELEMENT_NAME );
if( recoveries.getLength() > 0 ) {
configureRecovery( dbHome, (Element)recoveries.item( 0 ) );
}
}
private void configureRecovery( final Optional<Path> dbHome, Element recovery ) throws DatabaseConfigurationException
{
String option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_ENABLED_ATTRIBUTE );
setProperty( BrokerPool.PROPERTY_RECOVERY_ENABLED, parseBoolean( option, true ) );
LOG.debug( BrokerPool.PROPERTY_RECOVERY_ENABLED + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_ENABLED ) );
option = getConfigAttributeValue( recovery, Journal.RECOVERY_SYNC_ON_COMMIT_ATTRIBUTE );
setProperty( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT, parseBoolean( option, true ) );
LOG.debug( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT + ": " + config.get( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT ) );
option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_GROUP_COMMIT_ATTRIBUTE );
setProperty( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT, parseBoolean( option, false ) );
LOG.debug( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT ) );
option = getConfigAttributeValue( recovery, Journal.RECOVERY_JOURNAL_DIR_ATTRIBUTE );
if(option != null) {
//DWES
final Path rf = ConfigurationHelper.lookup( option, dbHome );
if(!Files.isReadable(rf)) {
throw new DatabaseConfigurationException( "cannot read data directory: " + rf.toAbsolutePath());
}
setProperty(Journal.PROPERTY_RECOVERY_JOURNAL_DIR, rf.toAbsolutePath());
LOG.debug(Journal.PROPERTY_RECOVERY_JOURNAL_DIR + ": " + config.get(Journal.PROPERTY_RECOVERY_JOURNAL_DIR));
}
option = getConfigAttributeValue( recovery, Journal.RECOVERY_SIZE_LIMIT_ATTRIBUTE );
if( option != null ) {
if( option.endsWith( "M" ) || option.endsWith( "m" ) ) {
option = option.substring( 0, option.length() - 1 );
}
try {
final Integer size = Integer.valueOf( option );
setProperty( Journal.PROPERTY_RECOVERY_SIZE_LIMIT, size );
LOG.debug( Journal.PROPERTY_RECOVERY_SIZE_LIMIT + ": " + config.get( Journal.PROPERTY_RECOVERY_SIZE_LIMIT ) + "m" );
}
catch( final NumberFormatException e ) {
throw( new DatabaseConfigurationException( "size attribute in recovery section needs to be a number" ) );
}
}
option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_FORCE_RESTART_ATTRIBUTE );
boolean value = false;
if( option != null ) {
value = "yes".equals(option);
}
setProperty( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART, value);
LOG.debug( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART ) );
option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_POST_RECOVERY_CHECK );
value = false;
if( option != null ) {
value = "yes".equals(option);
}
setProperty( BrokerPool.PROPERTY_RECOVERY_CHECK, value);
LOG.debug( BrokerPool.PROPERTY_RECOVERY_CHECK + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_CHECK ) );
}
/**
* DOCUMENT ME!
*
* @param watchDog
*/
private void configureWatchdog( Element watchDog )
{
final String timeout = getConfigAttributeValue( watchDog, "query-timeout" );
if( timeout != null ) {
try {
config.put( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT, Long.valueOf(timeout) );
LOG.debug( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT + ": " + config.get( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String maxOutput = getConfigAttributeValue( watchDog, "output-size-limit" );
if( maxOutput != null ) {
try {
config.put( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT, Integer.valueOf(maxOutput) );
LOG.debug( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT + ": " + config.get( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
}
/**
* DOCUMENT ME!
*
* @param queryPool
*/
private void configureXQueryPool( Element queryPool )
{
final String maxStackSize = getConfigAttributeValue( queryPool, XQueryPool.MAX_STACK_SIZE_ATTRIBUTE );
if( maxStackSize != null ) {
try {
config.put( XQueryPool.PROPERTY_MAX_STACK_SIZE, Integer.valueOf(maxStackSize) );
LOG.debug( XQueryPool.PROPERTY_MAX_STACK_SIZE + ": " + config.get( XQueryPool.PROPERTY_MAX_STACK_SIZE ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String maxPoolSize = getConfigAttributeValue( queryPool, XQueryPool.POOL_SIZE_ATTTRIBUTE );
if( maxPoolSize != null ) {
try {
config.put( XQueryPool.PROPERTY_POOL_SIZE, Integer.valueOf(maxPoolSize) );
LOG.debug( XQueryPool.PROPERTY_POOL_SIZE + ": " + config.get( XQueryPool.PROPERTY_POOL_SIZE ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String timeout = getConfigAttributeValue( queryPool, XQueryPool.TIMEOUT_ATTRIBUTE );
if( timeout != null ) {
try {
config.put( XQueryPool.PROPERTY_TIMEOUT, Long.valueOf(timeout) );
LOG.debug( XQueryPool.PROPERTY_TIMEOUT + ": " + config.get( XQueryPool.PROPERTY_TIMEOUT ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
}
public static class StartupTriggerConfig {
private final String clazz;
private final Map<String, List<? extends Object>> params;
public StartupTriggerConfig(final String clazz, final Map<String, List<? extends Object>> params) {
this.clazz = clazz;
this.params = params;
}
public String getClazz() {
return clazz;
}
public Map<String, List<? extends Object>> getParams() {
return params;
}
}
private void configureStartup(final Element startup) {
// Retrieve <triggers>
final NodeList nlTriggers = startup.getElementsByTagName("triggers");
// If <triggers> exists
if(nlTriggers != null && nlTriggers.getLength() > 0) {
// Get <triggers>
final Element triggers = (Element)nlTriggers.item(0);
// Get <trigger>
final NodeList nlTrigger = triggers.getElementsByTagName("trigger");
// If <trigger> exists and there are more than 0
if(nlTrigger != null && nlTrigger.getLength() > 0) {
// Initialize trigger configuration
List<StartupTriggerConfig> startupTriggers = (List<StartupTriggerConfig>)config.get(BrokerPool.PROPERTY_STARTUP_TRIGGERS);
if(startupTriggers == null) {
startupTriggers = new ArrayList<>();
config.put(BrokerPool.PROPERTY_STARTUP_TRIGGERS, startupTriggers);
}
// Iterate over <trigger> elements
for(int i = 0; i < nlTrigger.getLength(); i++) {
// Get <trigger> element
final Element trigger = (Element)nlTrigger.item(i);
// Get @class
final String startupTriggerClass = trigger.getAttribute("class");
boolean isStartupTrigger = false;
try {
// Verify if class is StartupTrigger
for(final Class iface : Class.forName(startupTriggerClass).getInterfaces()) {
if("org.exist.storage.StartupTrigger".equals(iface.getName())) {
isStartupTrigger = true;
break;
}
}
// if it actually is a StartupTrigger
if(isStartupTrigger) {
// Parse additional parameters
final Map<String, List<? extends Object>> params
= ParametersExtractor.extract(trigger.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME));
// Register trigger
startupTriggers.add(new StartupTriggerConfig(startupTriggerClass, params));
// Done
LOG.info("Registered StartupTrigger: " + startupTriggerClass);
} else {
LOG.warn("StartupTrigger: " + startupTriggerClass + " does not implement org.exist.storage.StartupTrigger. IGNORING!");
}
} catch(final ClassNotFoundException cnfe) {
LOG.error("Could not find StartupTrigger class: " + startupTriggerClass + ". " + cnfe.getMessage(), cnfe);
}
}
}
}
}
/**
* DOCUMENT ME!
*
* @param pool
*/
private void configurePool( Element pool )
{
final String min = getConfigAttributeValue( pool, BrokerPool.MIN_CONNECTIONS_ATTRIBUTE );
if( min != null ) {
try {
config.put( BrokerPool.PROPERTY_MIN_CONNECTIONS, Integer.valueOf(min) );
LOG.debug( BrokerPool.PROPERTY_MIN_CONNECTIONS + ": " + config.get( BrokerPool.PROPERTY_MIN_CONNECTIONS ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String max = getConfigAttributeValue( pool, BrokerPool.MAX_CONNECTIONS_ATTRIBUTE );
if( max != null ) {
try {
config.put( BrokerPool.PROPERTY_MAX_CONNECTIONS, Integer.valueOf(max) );
LOG.debug( BrokerPool.PROPERTY_MAX_CONNECTIONS + ": " + config.get( BrokerPool.PROPERTY_MAX_CONNECTIONS ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String sync = getConfigAttributeValue( pool, BrokerPool.SYNC_PERIOD_ATTRIBUTE );
if( sync != null ) {
try {
config.put( BrokerPool.PROPERTY_SYNC_PERIOD, Long.valueOf(sync) );
LOG.debug( BrokerPool.PROPERTY_SYNC_PERIOD + ": " + config.get( BrokerPool.PROPERTY_SYNC_PERIOD ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String maxShutdownWait = getConfigAttributeValue( pool, BrokerPool.SHUTDOWN_DELAY_ATTRIBUTE );
if( maxShutdownWait != null ) {
try {
config.put( BrokerPool.PROPERTY_SHUTDOWN_DELAY, Long.valueOf(maxShutdownWait) );
LOG.debug( BrokerPool.PROPERTY_SHUTDOWN_DELAY + ": " + config.get( BrokerPool.PROPERTY_SHUTDOWN_DELAY ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
}
private void configureIndexer( final Optional<Path> dbHome, Document doc, Element indexer ) throws DatabaseConfigurationException, MalformedURLException
{
final String caseSensitive = getConfigAttributeValue( indexer, NativeValueIndex.INDEX_CASE_SENSITIVE_ATTRIBUTE );
if( caseSensitive != null ) {
config.put( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE, parseBoolean( caseSensitive, false ) );
LOG.debug( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE + ": " + config.get( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE ) );
}
int depth = 3;
final String indexDepth = getConfigAttributeValue( indexer, NativeBroker.INDEX_DEPTH_ATTRIBUTE );
if( indexDepth != null ) {
try {
depth = Integer.parseInt( indexDepth );
if( depth < 3 ) {
LOG.warn( "parameter index-depth should be >= 3 or you will experience a severe " + "performance loss for node updates (XUpdate or XQuery update extensions)" );
depth = 3;
}
config.put( NativeBroker.PROPERTY_INDEX_DEPTH, depth);
LOG.debug( NativeBroker.PROPERTY_INDEX_DEPTH + ": " + config.get( NativeBroker.PROPERTY_INDEX_DEPTH ) );
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String suppressWS = getConfigAttributeValue( indexer, Indexer.SUPPRESS_WHITESPACE_ATTRIBUTE );
if( suppressWS != null ) {
config.put( Indexer.PROPERTY_SUPPRESS_WHITESPACE, suppressWS );
LOG.debug( Indexer.PROPERTY_SUPPRESS_WHITESPACE + ": " + config.get( Indexer.PROPERTY_SUPPRESS_WHITESPACE ) );
}
final String suppressWSmixed = getConfigAttributeValue( indexer, Indexer.PRESERVE_WS_MIXED_CONTENT_ATTRIBUTE );
if( suppressWSmixed != null ) {
config.put( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT, parseBoolean( suppressWSmixed, false ) );
LOG.debug( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT + ": " + config.get( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT ) );
}
// index settings
final NodeList cl = doc.getElementsByTagName( Indexer.CONFIGURATION_INDEX_ELEMENT_NAME );
if( cl.getLength() > 0 ) {
final Element elem = (Element)cl.item( 0 );
final IndexSpec spec = new IndexSpec( null, elem );
config.put( Indexer.PROPERTY_INDEXER_CONFIG, spec );
//LOG.debug(Indexer.PROPERTY_INDEXER_CONFIG + ": " + config.get(Indexer.PROPERTY_INDEXER_CONFIG));
}
// index modules
NodeList modules = indexer.getElementsByTagName( IndexManager.CONFIGURATION_ELEMENT_NAME );
if( modules.getLength() > 0 ) {
modules = ( (Element)modules.item( 0 ) ).getElementsByTagName( IndexManager.CONFIGURATION_MODULE_ELEMENT_NAME );
final IndexModuleConfig[] modConfig = new IndexModuleConfig[modules.getLength()];
for( int i = 0; i < modules.getLength(); i++ ) {
final Element elem = (Element)modules.item( i );
final String className = elem.getAttribute( IndexManager.INDEXER_MODULES_CLASS_ATTRIBUTE );
final String id = elem.getAttribute( IndexManager.INDEXER_MODULES_ID_ATTRIBUTE );
if( ( className == null ) || (className.isEmpty()) ) {
throw( new DatabaseConfigurationException( "Required attribute class is missing for module" ) );
}
if( ( id == null ) || (id.isEmpty()) ) {
throw( new DatabaseConfigurationException( "Required attribute id is missing for module" ) );
}
modConfig[i] = new IndexModuleConfig( id, className, elem );
}
config.put( IndexManager.PROPERTY_INDEXER_MODULES, modConfig );
}
}
private void configureValidation( final Optional<Path> dbHome, Document doc, Element validation ) throws DatabaseConfigurationException
{
// Determine validation mode
final String mode = getConfigAttributeValue( validation, XMLReaderObjectFactory.VALIDATION_MODE_ATTRIBUTE );
if( mode != null ) {
config.put( XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE, mode );
LOG.debug( XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE + ": " + config.get( XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE ) );
}
// Extract catalogs
LOG.debug( "Creating eXist catalog resolver" );
final eXistXMLCatalogResolver resolver = new eXistXMLCatalogResolver();
final NodeList entityResolver = validation.getElementsByTagName( XMLReaderObjectFactory.CONFIGURATION_ENTITY_RESOLVER_ELEMENT_NAME );
if( entityResolver.getLength() > 0 ) {
final Element r = (Element)entityResolver.item( 0 );
final NodeList catalogs = r.getElementsByTagName( XMLReaderObjectFactory.CONFIGURATION_CATALOG_ELEMENT_NAME );
LOG.debug( "Found " + catalogs.getLength() + " catalog uri entries." );
LOG.debug( "Using dbHome=" + dbHome );
// Determine webapps directory. SingleInstanceConfiguration cannot
// be used at this phase. Trick is to check wether dbHOME is
// pointing to a WEB-INF directory, meaning inside war file)
final Path webappHome = dbHome.map(h -> {
if(FileUtils.fileName(h).endsWith("WEB-INF")) {
return h.getParent().toAbsolutePath();
} else {
return h.resolve("webapp").toAbsolutePath();
}
}).orElse(Paths.get("webapp").toAbsolutePath());
LOG.debug("using webappHome=" + webappHome.toString());
// Get and store all URIs
final List<String> allURIs = new ArrayList<>();
for( int i = 0; i < catalogs.getLength(); i++ ) {
String uri = ( (Element)catalogs.item( i ) ).getAttribute( "uri" );
if( uri != null ) { // when uri attribute is filled in
// Substitute string, creating an uri from a local file
if(uri.contains("${WEBAPP_HOME}")) {
uri = uri.replaceAll( "\\$\\{WEBAPP_HOME\\}", webappHome.toUri().toString() );
}
if(uri.contains("${EXIST_HOME}")) {
uri = uri.replaceAll( "\\$\\{EXIST_HOME\\}", dbHome.toString() );
}
// Add uri to confiuration
LOG.info( "Add catalog uri " + uri + "" );
allURIs.add( uri );
}
}
resolver.setCatalogs( allURIs );
// Store all configured URIs
config.put( XMLReaderObjectFactory.CATALOG_URIS, allURIs );
}
// Store resolver
config.put( XMLReaderObjectFactory.CATALOG_RESOLVER, resolver );
// cache
final GrammarPool gp = new GrammarPool();
config.put( XMLReaderObjectFactory.GRAMMER_POOL, gp );
}
/**
* Gets the value of a configuration attribute
*
* The value typically is specified in the conf.xml file, but can be overridden with using a System Property
*
* @param element The attribute's parent element
* @param attributeName The name of the attribute
*
* @return The value of the attribute
*/
private String getConfigAttributeValue( Element element, String attributeName )
{
String value = null;
if( element != null && attributeName != null ) {
final String property = getAttributeSystemPropertyName( element, attributeName );
value = System.getProperty( property );
// If the value has not been overriden in a system property, then get it from the configuration
if( value != null ) {
LOG.warn( "Configuration value overridden by system property: " + property + ", with value: " + value );
} else {
value = element.getAttribute( attributeName );
}
}
return( value );
}
/**
* Generates a suitable system property name from the given config attribute and parent element.
*
* values are of the form org.element.element.....attribute and follow the heirarchical structure of the conf.xml file.
* For example, the db-connection cacheSize property name would be org.exist.db-connection.cacheSize
*
* @param element The attribute's parent element
* @param attributeName The name of the attribute
*
* @return The generated system property name
*/
private String getAttributeSystemPropertyName( Element element, String attributeName )
{
final StringBuilder property = new StringBuilder( attributeName );
Node parent = element.getParentNode();
property.insert( 0, "." );
property.insert( 0, element.getLocalName() );
while( parent != null && parent instanceof Element ) {
final String parentName = ((Element)parent).getLocalName();
property.insert( 0, "." );
property.insert( 0, parentName );
parent = parent.getParentNode();
}
property.insert( 0, "org." );
return( property.toString() );
}
public Optional<Path> getConfigFilePath() {
return configFilePath;
}
public Optional<Path> getExistHome() {
return existHome;
}
public Object getProperty(final String name) {
return config.get(name);
}
public <T> T getProperty(final String name, final T defaultValue) {
return Optional.ofNullable((T)config.get(name)).orElse(defaultValue);
}
public boolean hasProperty(final String name) {
return config.containsKey(name);
}
public void setProperty(final String name, final Object obj) {
config.put(name, obj);
}
public void removeProperty(final String name) {
config.remove(name);
}
/**
* Takes the passed string and converts it to a non-null <code>Boolean</code> object. If value is null, the specified default value is used.
* Otherwise, Boolean.TRUE is returned if and only if the passed string equals "yes" or "true", ignoring case.
*
* @param value The string to parse
* @param defaultValue The default if the string is null
*
* @return The parsed <code>Boolean</code>
*/
public static boolean parseBoolean(@Nullable final String value, final boolean defaultValue) {
return Optional.ofNullable(value)
.map(v -> v.equalsIgnoreCase("yes") || v.equalsIgnoreCase("true"))
.orElse(defaultValue);
}
/**
* Takes the passed string and converts it to a non-null <code>int</code> value. If value is null, the specified default value is used.
* Otherwise, Boolean.TRUE is returned if and only if the passed string equals "yes" or "true", ignoring case.
*
* @param value The string to parse
* @param defaultValue The default if the string is null or empty
*
* @return The parsed <code>int</code>
*/
public static int parseInt(@Nullable final String value, final int defaultValue) {
if (value == null || value.isEmpty()) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (final NumberFormatException e) {
LOG.warn("Could not parse: " + value + ", as an int: " + e.getMessage());
return defaultValue;
}
}
public int getInteger(final String name) {
return Optional.ofNullable(getProperty(name))
.filter(v -> v instanceof Integer)
.map(v -> (int)v)
.orElse(-1);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
*/
@Override
public void error( SAXParseException exception ) throws SAXException
{
LOG.error( "error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception );
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
*/
@Override
public void fatalError( SAXParseException exception ) throws SAXException
{
LOG.error("error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
*/
@Override
public void warning( SAXParseException exception ) throws SAXException
{
LOG.error( "error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception );
}
public static final class IndexModuleConfig {
private final String id;
private final String className;
private final Element config;
public IndexModuleConfig(final String id, final String className, final Element config) {
this.id = id;
this.className = className;
this.config = config;
}
public String getId()
{
return( id );
}
public String getClassName()
{
return( className );
}
public Element getConfig()
{
return( config );
}
}
}
| lgpl-2.1 |
kadamwhite/p5.js | src/core/constants.js | 4541 | /**
* @module Constants
* @submodule Constants
* @for p5
*/
var PI = Math.PI;
module.exports = {
// GRAPHICS RENDERER
P2D: 'p2d',
WEBGL: 'webgl',
// ENVIRONMENT
ARROW: 'default',
CROSS: 'crosshair',
HAND: 'pointer',
MOVE: 'move',
TEXT: 'text',
WAIT: 'wait',
// TRIGONOMETRY
/**
* HALF_PI is a mathematical constant with the value
* 1.57079632679489661923. It is half the ratio of the
* circumference of a circle to its diameter. It is useful in
* combination with the trigonometric functions sin() and cos().
*
* @property HALF_PI
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, HALF_PI);
* </code></div>
*
* @alt
* 80x80 white quarter-circle with curve toward bottom right of canvas.
*
*/
HALF_PI: PI / 2,
/**
* PI is a mathematical constant with the value
* 3.14159265358979323846. It is the ratio of the circumference
* of a circle to its diameter. It is useful in combination with
* the trigonometric functions sin() and cos().
*
* @property PI
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, PI);
* </code></div>
*
* @alt
* white half-circle with curve toward bottom of canvas.
*
*/
PI: PI,
/**
* QUARTER_PI is a mathematical constant with the value 0.7853982.
* It is one quarter the ratio of the circumference of a circle to
* its diameter. It is useful in combination with the trigonometric
* functions sin() and cos().
*
* @property QUARTER_PI
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, QUARTER_PI);
* </code></div>
*
* @alt
* white eighth-circle rotated about 40 degrees with curve bottom right canvas.
*
*/
QUARTER_PI: PI / 4,
/**
* TAU is an alias for TWO_PI, a mathematical constant with the
* value 6.28318530717958647693. It is twice the ratio of the
* circumference of a circle to its diameter. It is useful in
* combination with the trigonometric functions sin() and cos().
*
* @property TAU
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, TAU);
* </code></div>
*
* @alt
* 80x80 white ellipse shape in center of canvas.
*
*/
TAU: PI * 2,
/**
* TWO_PI is a mathematical constant with the value
* 6.28318530717958647693. It is twice the ratio of the
* circumference of a circle to its diameter. It is useful in
* combination with the trigonometric functions sin() and cos().
*
* @property TWO_PI
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, TWO_PI);
* </code></div>
*
* @alt
* 80x80 white ellipse shape in center of canvas.
*
*/
TWO_PI: PI * 2,
DEGREES: 'degrees',
RADIANS: 'radians',
// SHAPE
CORNER: 'corner',
CORNERS: 'corners',
RADIUS: 'radius',
RIGHT: 'right',
LEFT: 'left',
CENTER: 'center',
TOP: 'top',
BOTTOM: 'bottom',
BASELINE: 'alphabetic',
POINTS: 0x0000,
LINES: 0x0001,
LINE_STRIP: 0x0003,
LINE_LOOP: 0x0002,
TRIANGLES: 0x0004,
TRIANGLE_FAN: 0x0006,
TRIANGLE_STRIP: 0x0005,
QUADS: 'quads',
QUAD_STRIP: 'quad_strip',
CLOSE: 'close',
OPEN: 'open',
CHORD: 'chord',
PIE: 'pie',
PROJECT: 'square', // PEND: careful this is counterintuitive
SQUARE: 'butt',
ROUND: 'round',
BEVEL: 'bevel',
MITER: 'miter',
// COLOR
RGB: 'rgb',
HSB: 'hsb',
HSL: 'hsl',
// DOM EXTENSION
AUTO: 'auto',
// INPUT
ALT: 18,
BACKSPACE: 8,
CONTROL: 17,
DELETE: 46,
DOWN_ARROW: 40,
ENTER: 13,
ESCAPE: 27,
LEFT_ARROW: 37,
OPTION: 18,
RETURN: 13,
RIGHT_ARROW: 39,
SHIFT: 16,
TAB: 9,
UP_ARROW: 38,
// RENDERING
BLEND: 'source-over',
ADD: 'lighter',
//ADD: 'add', //
//SUBTRACT: 'subtract', //
DARKEST: 'darken',
LIGHTEST: 'lighten',
DIFFERENCE: 'difference',
EXCLUSION: 'exclusion',
MULTIPLY: 'multiply',
SCREEN: 'screen',
REPLACE: 'copy',
OVERLAY: 'overlay',
HARD_LIGHT: 'hard-light',
SOFT_LIGHT: 'soft-light',
DODGE: 'color-dodge',
BURN: 'color-burn',
// FILTERS
THRESHOLD: 'threshold',
GRAY: 'gray',
OPAQUE: 'opaque',
INVERT: 'invert',
POSTERIZE: 'posterize',
DILATE: 'dilate',
ERODE: 'erode',
BLUR: 'blur',
// TYPOGRAPHY
NORMAL: 'normal',
ITALIC: 'italic',
BOLD: 'bold',
// TYPOGRAPHY-INTERNAL
_DEFAULT_TEXT_FILL: '#000000',
_DEFAULT_LEADMULT: 1.25,
_CTX_MIDDLE: 'middle',
// VERTICES
LINEAR: 'linear',
QUADRATIC: 'quadratic',
BEZIER: 'bezier',
CURVE: 'curve',
// DEFAULTS
_DEFAULT_STROKE: '#000000',
_DEFAULT_FILL: '#FFFFFF'
};
| lgpl-2.1 |
rhinstaller/blivet | blivet/size.py | 6452 | # size.py
# Python module to represent storage sizes
#
# Copyright (C) 2010 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): David Cantrell <[email protected]>
from bytesize import bytesize
# we just need to make these objects available here
# pylint: disable=unused-import
from bytesize.bytesize import B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB, KB, MB, GB, TB, PB, EB, ZB, YB
from bytesize.bytesize import ROUND_UP, ROUND_DOWN, ROUND_HALF_UP
ROUND_DEFAULT = ROUND_HALF_UP
def unit_str(unit, xlate=False):
""" Return a string representation of unit.
:param unit: a named unit, e.g., KiB
:param bool xlate: if True, translate to current locale
:rtype: some kind of string type
:returns: string representation of unit
"""
return bytesize.unit_str(unit, xlate)
class Size(bytesize.Size):
""" Common class to represent storage device and filesystem sizes.
Can handle parsing strings such as 45MB or 6.7GB to initialize
itself, or can be initialized with a numerical size in bytes.
Also generates human readable strings to a specified number of
decimal places.
"""
def __abs__(self):
return Size(bytesize.Size.__abs__(self))
def __add__(self, other):
return Size(bytesize.Size.__add__(self, other))
# needed to make sum() work with Size arguments
def __radd__(self, other):
return Size(bytesize.Size.__radd__(self, other))
def __sub__(self, other):
return Size(bytesize.Size.__sub__(self, other))
def __rsub__(self, other):
return Size(bytesize.Size.__rsub__(self, other))
def __mul__(self, other):
return Size(bytesize.Size.__mul__(self, other))
__rmul__ = __mul__
def __div__(self, other): # pylint: disable=unused-argument
ret = bytesize.Size.__div__(self, other) # pylint: disable=no-member
if isinstance(ret, bytesize.Size):
ret = Size(ret)
return ret
def __truediv__(self, other):
ret = bytesize.Size.__truediv__(self, other)
if isinstance(ret, bytesize.Size):
ret = Size(ret)
return ret
def __floordiv__(self, other):
ret = bytesize.Size.__floordiv__(self, other)
if isinstance(ret, bytesize.Size):
ret = Size(ret)
return ret
def __mod__(self, other):
return Size(bytesize.Size.__mod__(self, other))
def __deepcopy__(self, memo_dict):
return Size(bytesize.Size.__deepcopy__(self, memo_dict))
# pylint: disable=arguments-differ
def convert_to(self, spec=None):
""" Return the size in the units indicated by the specifier.
:param spec: a units specifier
:type spec: a units specifier or :class:`Size`
:returns: a numeric value in the units indicated by the specifier
:rtype: Decimal
:raises ValueError: if Size unit specifier is non-positive
.. versionadded:: 1.6
spec parameter may be Size as well as units specifier.
"""
if isinstance(spec, Size):
if spec == Size(0):
raise ValueError("cannot convert to 0 size")
return bytesize.Size.__truediv__(self, spec)
spec = B if spec is None else spec
return bytesize.Size.convert_to(self, spec)
def human_readable(self, min_unit=B, max_places=2, xlate=True):
""" Return a string representation of this size with appropriate
size specifier and in the specified number of decimal places.
Values are always represented using binary not decimal units.
For example, if the number of bytes represented by this size
is 65531, expect the representation to be something like
64.00 KiB, not 65.53 KB.
:param min_unit: the smallest unit the returned representation should use
:type min_unit: one of the B, KiB, MiB,... (binary) units from this module
or str ("B", "KiB",...)
:param max_places: number of decimal places to use
:type max_places: an integer type or NoneType
:param bool xlate: If True, translate for current locale
:returns: a representation of the size
:rtype: str
"""
if max_places is None:
max_places = -1
return bytesize.Size.human_readable(self, min_unit, max_places, xlate)
# pylint: disable=arguments-differ
def round_to_nearest(self, size, rounding=ROUND_DEFAULT):
""" Rounds to nearest unit specified as a named constant or a Size.
:param size: a size specifier
:type size: a named constant like KiB, or any non-negative Size
:keyword rounding: which direction to round
:type rounding: one of ROUND_UP, ROUND_DOWN, or ROUND_DEFAULT
:returns: Size rounded to nearest whole specified unit
:rtype: :class:`Size`
.. warning:: Always think about the rounding mode and specify it!
If size is Size(0), returns Size(0).
"""
if rounding not in (ROUND_UP, ROUND_DOWN, ROUND_DEFAULT):
raise ValueError("invalid rounding specifier")
if isinstance(size, Size):
if size.get_bytes() == 0:
return Size(0)
elif size < Size(0):
raise ValueError("invalid rounding size: %s" % size)
return Size(bytesize.Size.round_to_nearest(self, size, rounding))
| lgpl-2.1 |
Radi0actvChickn/Polyglot-Trait-Extension | src/polyglot/frontend/Compiler.java | 11840 | /*******************************************************************************
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2012 Polyglot project group, Cornell University
* Copyright (c) 2006-2012 IBM Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program and the accompanying materials are made available under
* the terms of the Lesser GNU Public License v2.0 which accompanies this
* distribution.
*
* The development of the Polyglot project has been supported by a
* number of funding sources, including DARPA Contract F30602-99-1-0533,
* monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and
* N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302,
* and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan
* Research Fellowship, and an Intel Research Ph.D. Fellowship.
*
* See README for contributors.
******************************************************************************/
package polyglot.frontend;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import javax.tools.JavaFileObject;
import polyglot.frontend.Source.Kind;
import polyglot.frontend.goals.Goal;
import polyglot.main.Options;
import polyglot.types.reflect.ClassFileLoader;
import polyglot.util.CodeWriter;
import polyglot.util.ErrorInfo;
import polyglot.util.ErrorLimitError;
import polyglot.util.ErrorQueue;
import polyglot.util.InternalCompilerError;
import polyglot.util.OptimalCodeWriter;
import polyglot.util.SimpleCodeWriter;
import polyglot.util.StdErrorQueue;
/**
* This is the main entry point for the compiler. It contains a work list that
* contains entries for all classes that must be compiled (or otherwise worked
* on).
*/
public class Compiler {
/** The extension info */
private ExtensionInfo extensionInfo;
/** A list of all extension infos active in this compiler. */
private List<ExtensionInfo> allExtensions;
/** The error queue handles outputting error messages. */
private ErrorQueue eq;
/**
* Class file loader. There should be only one of these so we can cache
* across type systems.
*/
private ClassFileLoader loader;
/**
* The output files generated by the compiler. This is used to to call the
* post-compiler (e.g., javac).
*/
private Collection<JavaFileObject> outputFiles = new LinkedHashSet<>();
/**
* Initialize the compiler.
*
* @param extensionInfo the {@code ExtensionInfo} this compiler is for.
*/
public Compiler(ExtensionInfo extensionInfo) {
this(extensionInfo,
new StdErrorQueue(System.err,
extensionInfo.getOptions().error_count,
extensionInfo.compilerName()));
}
/**
* Initialize the compiler.
*
* @param extensionInfo the {@code ExtensionInfo} this compiler is for.
*/
public Compiler(ExtensionInfo extensionInfo, ErrorQueue eq) {
this.extensionInfo = extensionInfo;
this.eq = eq;
allExtensions = new ArrayList<>(2);
loader = extensionInfo.classFileLoader();
// This must be done last.
extensionInfo.initCompiler(this);
}
/** Return a set of output filenames resulting from a compilation. */
public Collection<JavaFileObject> outputFiles() {
return outputFiles;
}
/**
* Compile all the files listed in the set of strings {@code source}.
* Return true on success. The method {@code outputFiles} can be
* used to obtain the output of the compilation. This is the main entry
* point for the compiler, called from main().
*/
public boolean compileFiles(Collection<String> filenames) {
List<FileSource> sources = new ArrayList<>(filenames.size());
// Construct a list of sources from the list of file names.
try {
try {
SourceLoader source_loader = sourceExtension().sourceLoader();
for (String sourceName : filenames) {
// mark this source as being explicitly specified
// by the user.
FileSource source =
source_loader.fileSource(sourceName,
Kind.USER_SPECIFIED);
sources.add(source);
}
}
catch (FileNotFoundException e) {
eq.enqueue(ErrorInfo.IO_ERROR,
"Cannot find source file \"" + e.getMessage()
+ "\".");
eq.flush();
return false;
}
catch (IOException e) {
eq.enqueue(ErrorInfo.IO_ERROR, e.getMessage());
eq.flush();
return false;
}
catch (InternalCompilerError e) {
// Report it like other errors, but rethrow to get the stack
// trace.
try {
eq.enqueue(ErrorInfo.INTERNAL_ERROR,
e.message(),
e.position());
}
catch (ErrorLimitError e2) {
}
eq.flush();
throw e;
}
catch (RuntimeException e) {
// Flush the error queue, then rethrow to get the stack trace.
eq.flush();
throw e;
}
}
catch (ErrorLimitError e) {
eq.flush();
return false;
}
return compile(sources);
}
/**
* Compile all the files listed in the set of Sources {@code source}.
* Return true on success. The method {@code outputFiles} can be
* used to obtain the output of the compilation. This is the main entry
* point for the compiler, called from main().
*/
public boolean compile(Collection<FileSource> sources) {
return runToGoal(sources, new GoalFactory() {
@Override
public Goal getGoal(Job job) {
return sourceExtension().getCompileGoal(job);
}
});
}
/**
* Validates the files listed in the set of Sources {@code source} by
* running passes that are dependent on the validation goal. Returns true on
* success.
*/
public boolean validate(Collection<Source> sources) {
return runToGoal(sources, new GoalFactory() {
@Override
public Goal getGoal(Job job) {
return sourceExtension().getValidationGoal(job);
}
});
}
private static interface GoalFactory {
Goal getGoal(Job job);
}
private boolean runToGoal(Collection<? extends Source> sources,
GoalFactory goalFactory) {
boolean okay = false;
try {
try {
Scheduler scheduler = sourceExtension().scheduler();
List<Job> jobs = new ArrayList<>();
// First, create a goal to compile every source file.
for (Source source : sources) {
// Add a new SourceJob for the given source. If a Job for the source
// already exists, then we will be given the existing job.
Job job = scheduler.addJob(source);
jobs.add(job);
// Now, add a goal for completing the job.
scheduler.addGoal(goalFactory.getGoal(job));
}
scheduler.setCommandLineJobs(jobs);
// Then, compile the files to completion.
okay = scheduler.runToCompletion();
}
catch (InternalCompilerError e) {
// Report it like other errors, but rethrow to get the stack trace.
try {
eq.enqueue(ErrorInfo.INTERNAL_ERROR,
e.message(),
e.position());
}
catch (ErrorLimitError e2) {
}
eq.flush();
throw e;
}
catch (RuntimeException e) {
// Flush the error queue, then rethrow to get the stack trace.
eq.flush();
throw e;
}
}
catch (ErrorLimitError e) {
}
eq.flush();
for (ExtensionInfo ext : allExtensions)
ext.getStats().report();
return okay;
}
/** Get the compiler's class file loader. */
public ClassFileLoader loader() {
return loader;
}
/** Should fully qualified class names be used in the output? */
public boolean useFullyQualifiedNames() {
return extensionInfo.getOptions().fully_qualified_names;
}
/** Return a list of all languages extensions active in the compiler. */
public void addExtension(ExtensionInfo ext) {
allExtensions.add(ext);
}
/** Return a list of all languages extensions active in the compiler. */
public List<ExtensionInfo> allExtensions() {
return allExtensions;
}
/** Get information about the language extension being compiled. */
public ExtensionInfo sourceExtension() {
return extensionInfo;
}
/** Maximum number of characters on each line of output */
public int outputWidth() {
return extensionInfo.getOptions().output_width;
}
/** Should class info be serialized into the output? */
public boolean serializeClassInfo() {
return extensionInfo.getOptions().serialize_type_info;
}
/** Get the compiler's error queue. */
public ErrorQueue errorQueue() {
return eq;
}
static {
// FIXME: if we get an io error (due to too many files open, for example)
// it will throw an exception. but, we won't be able to do anything with
// it since the exception handlers will want to load
// polyglot.util.CodeWriter and polyglot.util.ErrorInfo to print and
// enqueue the error; but the classes must be in memory since the io
// can't open any files; thus, we force the classloader to load the class
// file.
try {
ClassLoader loader = Compiler.class.getClassLoader();
// loader.loadClass("polyglot.util.CodeWriter");
// loader.loadClass("polyglot.util.ErrorInfo");
loader.loadClass("polyglot.util.StdErrorQueue");
}
catch (ClassNotFoundException e) {
throw new InternalCompilerError(e.getMessage());
}
}
public static CodeWriter createCodeWriter(OutputStream w) {
return createCodeWriter(w, Options.global.output_width);
}
public static CodeWriter createCodeWriter(OutputStream w, int width) {
if (Options.global.use_simple_code_writer)
return new SimpleCodeWriter(w, width);
else return new OptimalCodeWriter(w, width);
}
public static CodeWriter createCodeWriter(Writer w) {
return createCodeWriter(w, Options.global.output_width);
}
public static CodeWriter createCodeWriter(Writer w, int width) {
if (Options.global.use_simple_code_writer)
return new SimpleCodeWriter(w, width);
else return new OptimalCodeWriter(w, width);
}
}
| lgpl-2.1 |
micrexp/gtkwebkitsharp | Webkit/DOM/WebKitDOMMediaError.cs | 2135 | //----------------------------------------------------------------------------
// This is autogenerated code by CppSharp.
// Do not edit this file or all your changes will be lost after re-generation.
//----------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace Webbed.Scripting.Interop
{
// DEBUG: struct _WebKitDOMMediaError { WebKitDOMObject parent_instance;}
[StructLayout(LayoutKind.Explicit, Size = 16)]
public unsafe struct _WebKitDOMMediaError
{
// DEBUG: WebKitDOMObject parent_instance
[FieldOffset(0)]
public _WebKitDOMObject parent_instance;
}
// DEBUG: struct _WebKitDOMMediaErrorClass { WebKitDOMObjectClass parent_class;}
[StructLayout(LayoutKind.Explicit, Size = 68)]
public unsafe struct _WebKitDOMMediaErrorClass
{
// DEBUG: WebKitDOMObjectClass parent_class
[FieldOffset(0)]
public _WebKitDOMObjectClass parent_class;
}
public unsafe partial class WebKitDOMMediaError: GLib.Object
{
public WebKitDOMMediaError(IntPtr handle) : base(handle) { }
// DEBUG: WEBKIT_API GTypewebkit_dom_media_error_get_type (void)
[SuppressUnmanagedCodeSecurity]
[DllImport("webkitgtk-1.0", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="webkit_dom_media_error_get_type")]
internal static extern uint webkit_dom_media_error_get_type();
public GLib.GType Type
{
get
{
return new GLib.GType((IntPtr)webkit_dom_media_error_get_type());
}
}
// DEBUG: WEBKIT_API gushortwebkit_dom_media_error_get_code(WebKitDOMMediaError* self)
[SuppressUnmanagedCodeSecurity]
[DllImport("webkitgtk-1.0", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="webkit_dom_media_error_get_code")]
internal static extern ushort webkit_dom_media_error_get_code(global::System.IntPtr self);
}
}
| lgpl-2.1 |
ianmartin/GPSTk | src/EphemerisRange.cpp | 7906 | #pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file EphemerisRange.cpp
* Computation of range and associated quantities from EphemerisStore,
* given receiver position and time.
*/
#include "EphemerisRange.hpp"
#include "MiscMath.hpp"
#include "GPSGeoid.hpp"
#include "icd_200_constants.hpp"
#include "geometry.hpp"
using namespace std;
using namespace gpstk;
namespace gpstk
{
// Compute the corrected range at RECEIVE time, from receiver at position Rx,
// to the GPS satellite given by SatID sat, as well as all the CER quantities,
// given the nominal receive time tr_nom and an EphemerisStore. Note that this
// routine does not intrinsicly account for the receiver clock error
// like the ComputeAtTransmitTime routine does.
double CorrectedEphemerisRange::ComputeAtReceiveTime(
const DayTime& tr_nom,
const Position& Rx,
const SatID sat,
const XvtStore<SatID>& Eph)
{
try {
int nit;
double tof,tof_old,wt,sx,sy;
GPSGeoid geoid;
nit = 0;
tof = 0.07; // initial guess 70ms
do {
// best estimate of transmit time
transmit = tr_nom;
transmit -= tof;
tof_old = tof;
// get SV position
try {
svPosVel = Eph.getXvt(sat, transmit);
}
catch(InvalidRequest& e) {
GPSTK_RETHROW(e);
}
rotateEarth(Rx);
// update raw range and time of flight
rawrange = RSS(svPosVel.x[0]-Rx.X(),
svPosVel.x[1]-Rx.Y(),
svPosVel.x[2]-Rx.Z());
tof = rawrange/geoid.c();
} while(ABS(tof-tof_old)>1.e-13 && ++nit<5);
updateCER(Rx);
return (rawrange-svclkbias-relativity);
}
catch(gpstk::Exception& e) {
GPSTK_RETHROW(e);
}
} // end CorrectedEphemerisRange::ComputeAtReceiveTime
// Compute the corrected range at TRANSMIT time, from receiver at position Rx,
// to the GPS satellite given by SatID sat, as well as all the CER quantities,
// given the nominal receive time tr_nom and an EphemerisStore, as well as
// the raw measured pseudorange.
double CorrectedEphemerisRange::ComputeAtTransmitTime(
const DayTime& tr_nom,
const double& pr,
const Position& Rx,
const SatID sat,
const XvtStore<SatID>& Eph)
{
try {
DayTime tt;
// 0-th order estimate of transmit time = receiver - pseudorange/c
transmit = tr_nom;
transmit -= pr/C_GPS_M;
tt = transmit;
// correct for SV clock
for(int i=0; i<2; i++) {
// get SV position
try {
svPosVel = Eph.getXvt(sat,tt);
}
catch(InvalidRequest& e) {
GPSTK_RETHROW(e);
}
tt = transmit;
tt -= svPosVel.dtime; // clock and relativity
}
rotateEarth(Rx);
// raw range
rawrange = RSS(svPosVel.x[0]-Rx.X(),
svPosVel.x[1]-Rx.Y(),
svPosVel.x[2]-Rx.Z());
updateCER(Rx);
return (rawrange-svclkbias-relativity);
}
catch(gpstk::Exception& e) {
GPSTK_RETHROW(e);
}
} // end CorrectedEphemerisRange::ComputeAtTransmitTime
double CorrectedEphemerisRange::ComputeAtTransmitSvTime(
const DayTime& tt_nom,
const double& pr,
const Position& rx,
const SatID sat,
const XvtStore<SatID>& eph)
{
try {
svPosVel = eph.getXvt(sat, tt_nom);
// compute rotation angle in the time of signal transit
// While this is quite similiar to rotateEarth, its not the same and jcl doesn't
// know which is really correct
GPSGeoid gm;
double rotation_angle = -gm.angVelocity() * (pr/gm.c() - svPosVel.dtime);
svPosVel.x[0] = svPosVel.x[0] - svPosVel.x[1] * rotation_angle;
svPosVel.x[1] = svPosVel.x[1] + svPosVel.x[0] * rotation_angle;
svPosVel.x[2] = svPosVel.x[2];
rawrange =rx.slantRange(svPosVel.x);
updateCER(rx);
return rawrange - svclkbias - relativity;
}
catch (Exception& e) {
GPSTK_RETHROW(e);
}
}
void CorrectedEphemerisRange::updateCER(const Position& Rx)
{
relativity = RelativityCorrection(svPosVel) * C_GPS_M;
// relativity correction is added to dtime by the
// EphemerisStore::getSatXvt routines...
svclkbias = svPosVel.dtime*C_GPS_M - relativity;
svclkdrift = svPosVel.ddtime * C_GPS_M;
cosines[0] = (Rx.X()-svPosVel.x[0])/rawrange;
cosines[1] = (Rx.Y()-svPosVel.x[1])/rawrange;
cosines[2] = (Rx.Z()-svPosVel.x[2])/rawrange;
Position SV(svPosVel);
elevation = Rx.elevation(SV);
azimuth = Rx.azimuth(SV);
elevationGeodetic = Rx.elevationGeodetic(SV);
azimuthGeodetic = Rx.azimuthGeodetic(SV);
}
void CorrectedEphemerisRange::rotateEarth(const Position& Rx)
{
GPSGeoid geoid;
double tof = RSS(svPosVel.x[0]-Rx.X(),
svPosVel.x[1]-Rx.Y(),
svPosVel.x[2]-Rx.Z())/geoid.c();
double wt = geoid.angVelocity()*tof;
double sx = cos(wt)*svPosVel.x[0] + sin(wt)*svPosVel.x[1];
double sy = -sin(wt)*svPosVel.x[0] + cos(wt)*svPosVel.x[1];
svPosVel.x[0] = sx;
svPosVel.x[1] = sy;
sx = cos(wt)*svPosVel.v[0] + sin(wt)*svPosVel.v[1];
sy = -sin(wt)*svPosVel.v[0] + cos(wt)*svPosVel.v[1];
svPosVel.v[0] = sx;
svPosVel.v[1] = sy;
}
double RelativityCorrection(const Xvt& svPosVel)
{
// relativity correction is added to dtime by the
// EphemerisStore::getSatXvt routines...
// dtr = -2*dot(R,V)/(c*c) = -4.4428e-10(s/sqrt(m)) * ecc * sqrt(A(m)) * sinE
// compute it separately here, in units seconds.
double dtr = ( -2.0 *( svPosVel.x[0] * svPosVel.v[0]
+ svPosVel.x[1] * svPosVel.v[1]
+ svPosVel.x[2] * svPosVel.v[2] ) / C_GPS_M ) / C_GPS_M;
return dtr;
}
} // namespace gpstk
| lgpl-2.1 |
knowarth-technologies/theme-personalizer | liferay-6-2-0/theme-personalizer/theme-personalizer-portlet/src/main/java/com/knowarth/portlets/themepersonalizer/model/impl/UserPersonalizedThemeBaseImpl.java | 1552 | package com.knowarth.portlets.themepersonalizer.model.impl;
import com.knowarth.portlets.themepersonalizer.model.UserPersonalizedTheme;
import com.knowarth.portlets.themepersonalizer.service.UserPersonalizedThemeLocalServiceUtil;
import com.liferay.portal.kernel.exception.SystemException;
/**
* The extended model base implementation for the UserPersonalizedTheme service. Represents a row in the "KNOWARTH_UserPersonalizedTheme" database table, with each column mapped to a property of this class.
*
* <p>
* This class exists only as a container for the default extended model level methods generated by ServiceBuilder. Helper methods and all application logic should be put in {@link UserPersonalizedThemeImpl}.
* </p>
*
* @author Samir Bhatt
* @see UserPersonalizedThemeImpl
* @see com.knowarth.portlets.themepersonalizer.model.UserPersonalizedTheme
* @generated
*/
public abstract class UserPersonalizedThemeBaseImpl
extends UserPersonalizedThemeModelImpl implements UserPersonalizedTheme {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. All methods that expect a user personalized theme model instance should use the {@link UserPersonalizedTheme} interface instead.
*/
@Override
public void persist() throws SystemException {
if (this.isNew()) {
UserPersonalizedThemeLocalServiceUtil.addUserPersonalizedTheme(this);
} else {
UserPersonalizedThemeLocalServiceUtil.updateUserPersonalizedTheme(this);
}
}
}
| lgpl-2.1 |
PhoenixClub/libcommoncpp | lib/commonc++/ByteBufferDataWriter.h++ | 2087 | /* ---------------------------------------------------------------------------
commonc++ - A C++ Common Class Library
Copyright (C) 2005-2012 Mark A Lindner
This file is part of commonc++.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
---------------------------------------------------------------------------
*/
#ifndef __ccxx_ByteBufferDataWriter_hxx
#define __ccxx_ByteBufferDataWriter_hxx
#include <commonc++/DataWriter.h++>
#include <commonc++/Buffer.h++>
#include <commonc++/IOException.h++>
namespace ccxx {
/** A DataWriter which writes data to a ByteBuffer.
*
* @author Mark Lindner
*/
class COMMONCPP_API ByteBufferDataWriter : public DataWriter
{
public:
/** Construct a new ByteBufferDataWriter for the given ByteBuffer.
*
* @param buffer Tthe buffer.
*/
ByteBufferDataWriter(ByteBuffer &buffer);
/** Destructor. */
~ByteBufferDataWriter() throw();
void skip(size_t count) throw(IOException);
void skip(size_t count, byte_t fillByte) throw(IOException);
void flush() throw(IOException);
void reset() throw(IOException);
void setOffset(int64_t offset) throw(IOException);
protected:
size_t write(const byte_t *buf, size_t count) throw(IOException);
private:
ByteBuffer &_buffer;
size_t _oldPos;
CCXX_COPY_DECLS(ByteBufferDataWriter);
};
}; // namespace ccxx
#endif // __ccxx_ByteBufferDataWriter_hxx
/* end of header file */
| lgpl-2.1 |
khanhhua/priced | src/wsgi.py | 1656 | import sys, os
from os.path import (join,
dirname,
realpath)
from tornado.web import (StaticFileHandler,
url
)
from app import App
base_path = dirname(__file__)
sys.path.insert(0, base_path)
static_path = realpath(join(base_path, "static", "assets"))
template_path = realpath(join(base_path, "template"))
print("template_path: %s" % template_path)
print("static_path: %s" % static_path)
from app import webhandlers
urls = [url(r"/", webhandlers.PageHandler),
url(r"/admin(/.*)?", webhandlers.PageHandler, {"template_name": "admin/index"}),
url(r"/api/products/(\w+?)", webhandlers.ProductsHandler),
url(r"/api/products/(\w+?)/prices", webhandlers.ProductPricesHandler),
url(r"/api/scenarios/(\w+?)", webhandlers.ScenariosHandler),
url(r"/api/transactions", webhandlers.TransactionsHandler),
url(r"/api/taxcodes(?:/(.+))?", webhandlers.TaxCodesHandler),
url(r"/api/units(?:/(.+))?", webhandlers.UnitsHandler),
url(r"/api/scenarios(?:/(.+))?", webhandlers.ScenariosHandler),
url(r"/api/scenario-sessions(?:/(.+))?", webhandlers.ScenarioSessionsHandler)
]
# url(r"/api/products/(?P<product_id>)")
config = dict(static_url_prefix="/assets/",
static_path=static_path,
template_path=template_path,
debug=True,
autoreload=True)
application = App(urls, **config)
if __name__ == "__main__":
application.listen(os.getenv("PORT", 8080))
import tornado.ioloop
tornado.ioloop.IOLoop().current().start() | lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/Java5FeaturesTest.java | 3813 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.annotations.entity;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* @author Emmanuel Bernard
*/
public class Java5FeaturesTest extends BaseCoreFunctionalTestCase {
@Test
public void testInterface() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
Race r = new Race();
r.setId( new Integer( 1 ) );
r.setLength( new Long( 3 ) );
s.persist( r );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
r = (Race) s.get( Race.class, r.getId() );
assertEquals( new Long( 3 ), r.getLength() );
tx.commit();
s.close();
}
@Test
public void testEnums() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
CommunityBid communityBid = new CommunityBid();
communityBid.setId( new Integer( 2 ) );
communityBid.setCommunityNote( Starred.OK );
Bid bid = new Bid();
bid.setId( new Integer( 1 ) );
bid.setDescription( "My best one" );
bid.setNote( Starred.OK );
bid.setEditorsNote( Starred.GOOD );
s.persist( bid );
s.persist( communityBid );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
//bid = (Bid) s.get( Bid.class, bid.getId() );
bid = (Bid)s.createQuery( "select b from Bid b where b.note = " +
Starred.class.getName() + ".OK and b.editorsNote = " +
Starred.class.getName() + ".GOOD and b.id = :id")
.setParameter( "id", bid.getId() ).uniqueResult();
//testing constant value
assertEquals( Starred.OK, bid.getNote() );
assertEquals( Starred.GOOD, bid.getEditorsNote() );
bid = (Bid)s.createQuery( "select b from Bid b where b.note = :note" +
" and b.editorsNote = :editorNote " +
" and b.id = :id")
.setParameter( "id", bid.getId() )
.setParameter( "note", Starred.OK )
.setParameter( "editorNote", Starred.GOOD )
.uniqueResult();
//testing constant value
assertEquals( Starred.OK, bid.getNote() );
assertEquals( Starred.GOOD, bid.getEditorsNote() );
bid.setNote( null );
tx.commit();
s.clear();
tx = s.beginTransaction();
bid = (Bid) s.get( Bid.class, bid.getId() );
communityBid = (CommunityBid) s.get( CommunityBid.class, communityBid.getId() );
assertNull( bid.getNote() );
assertEquals( Starred.OK, communityBid.getCommunityNote() );
s.delete( bid );
s.clear();
communityBid = (CommunityBid) s.createSQLQuery( "select {b.*} from Bid b where b.id = ?" )
.addEntity( "b", CommunityBid.class )
.setInteger( 0, communityBid.getId() ).uniqueResult();
assertEquals( Starred.OK, communityBid.getCommunityNote() );
s.delete( communityBid );
tx.commit();
s.close();
}
public void testAutoboxing() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
Bid bid = new Bid();
bid.setId( new Integer( 2 ) );
bid.setDescription( "My best one" );
bid.setNote( Starred.OK );
bid.setEditorsNote( Starred.GOOD );
bid.setApproved( null );
s.persist( bid );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
bid = (Bid) s.get( Bid.class, bid.getId() );
assertEquals( null, bid.getApproved() );
s.delete( bid );
tx.commit();
s.close();
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[]{
Race.class,
Bid.class,
CommunityBid.class
};
}
}
| lgpl-2.1 |
nonrational/qt-everywhere-opensource-src-4.8.6 | src/3rdparty/webkit/Source/WebKit/qt/declarative/.moc/release-shared/moc_qdeclarativewebview_p.cpp | 31537 | /****************************************************************************
** Meta object code from reading C++ file 'qdeclarativewebview_p.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../qdeclarativewebview_p.h"
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qdeclarativewebview_p.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_QDeclarativeWebPage[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_QDeclarativeWebPage[] = {
"QDeclarativeWebPage\0"
};
void QDeclarativeWebPage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData QDeclarativeWebPage::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QDeclarativeWebPage::staticMetaObject = {
{ &QWebPage::staticMetaObject, qt_meta_stringdata_QDeclarativeWebPage,
qt_meta_data_QDeclarativeWebPage, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QDeclarativeWebPage::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QDeclarativeWebPage::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QDeclarativeWebPage::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QDeclarativeWebPage))
return static_cast<void*>(const_cast< QDeclarativeWebPage*>(this));
return QWebPage::qt_metacast(_clname);
}
int QDeclarativeWebPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWebPage::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
static const uint qt_meta_data_GraphicsWebView[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: signature, parameters, type, tag, flags
31, 17, 16, 16, 0x05,
0 // eod
};
static const char qt_meta_stringdata_GraphicsWebView[] = {
"GraphicsWebView\0\0clickX,clickY\0"
"doubleClick(int,int)\0"
};
void GraphicsWebView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
GraphicsWebView *_t = static_cast<GraphicsWebView *>(_o);
switch (_id) {
case 0: _t->doubleClick((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
default: ;
}
}
}
const QMetaObjectExtraData GraphicsWebView::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject GraphicsWebView::staticMetaObject = {
{ &QGraphicsWebView::staticMetaObject, qt_meta_stringdata_GraphicsWebView,
qt_meta_data_GraphicsWebView, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &GraphicsWebView::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *GraphicsWebView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *GraphicsWebView::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_GraphicsWebView))
return static_cast<void*>(const_cast< GraphicsWebView*>(this));
return QGraphicsWebView::qt_metacast(_clname);
}
int GraphicsWebView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGraphicsWebView::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
}
return _id;
}
// SIGNAL 0
void GraphicsWebView::doubleClick(int _t1, int _t2)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
static const uint qt_meta_data_QDeclarativeWebView[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
34, 14, // methods
22, 184, // properties
1, 294, // enums/sets
0, 0, // constructors
0, // flags
22, // signalCount
// signals: signature, parameters, type, tag, flags
21, 20, 20, 20, 0x05,
45, 20, 20, 20, 0x05,
70, 20, 20, 20, 0x05,
83, 20, 20, 20, 0x05,
101, 20, 20, 20, 0x05,
123, 20, 20, 20, 0x05,
145, 20, 20, 20, 0x05,
159, 20, 20, 20, 0x05,
179, 20, 20, 20, 0x05,
193, 20, 20, 20, 0x05,
216, 20, 20, 20, 0x05,
244, 20, 20, 20, 0x05,
269, 20, 20, 20, 0x05,
295, 20, 20, 20, 0x05,
322, 20, 20, 20, 0x05,
345, 20, 20, 20, 0x05,
370, 20, 20, 20, 0x05,
384, 20, 20, 20, 0x05,
399, 20, 20, 20, 0x05,
426, 412, 20, 20, 0x05,
468, 447, 20, 20, 0x05,
498, 490, 20, 20, 0x05,
// slots: signature, parameters, type, tag, flags
522, 20, 513, 20, 0x0a,
550, 20, 20, 20, 0x08,
568, 566, 20, 20, 0x08,
591, 588, 20, 20, 0x08,
612, 20, 20, 20, 0x08,
635, 20, 20, 20, 0x08,
657, 20, 20, 20, 0x08,
674, 20, 20, 20, 0x08,
690, 20, 20, 20, 0x08,
745, 721, 20, 20, 0x08,
802, 797, 776, 20, 0x08,
// methods: signature, parameters, type, tag, flags
867, 845, 840, 20, 0x02,
// properties: name, type, flags
904, 896, 0x0a495001,
918, 910, 0x41495001,
923, 896, 0x0a495001,
934, 896, 0x0a495103,
943, 939, 0x02495103,
957, 939, 0x02495103,
972, 939, 0x02495103,
993, 988, 0x11495103,
1003, 997, ((uint)QMetaType::QReal << 24) | 0x00495001,
1019, 1012, 0x00495009,
1035, 1026, 0x00095409,
1042, 1026, 0x00095409,
1047, 1026, 0x00095409,
1055, 1026, 0x00095409,
1085, 1060, 0x00095409,
1128, 1094, 0x00095409,
1175, 1152, 0x0049510b,
1212, 1194, 0x0049510b,
1228, 840, 0x01495103,
1251, 1245, 0x15495001,
1264, 997, ((uint)QMetaType::QReal << 24) | 0x00495103,
1285, 1278, 0x43c95103,
// properties: notify_signal_id
5,
6,
7,
8,
9,
0,
1,
2,
3,
4,
0,
0,
0,
0,
0,
0,
10,
11,
12,
13,
14,
15,
// properties: revision
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
// enums: name, flags, count, data
1012, 0x0, 4, 298,
// enum data: key, value
1301, uint(QDeclarativeWebView::Null),
1306, uint(QDeclarativeWebView::Ready),
1312, uint(QDeclarativeWebView::Loading),
1320, uint(QDeclarativeWebView::Error),
0 // eod
};
static const char qt_meta_stringdata_QDeclarativeWebView[] = {
"QDeclarativeWebView\0\0preferredWidthChanged()\0"
"preferredHeightChanged()\0urlChanged()\0"
"progressChanged()\0statusChanged(Status)\0"
"titleChanged(QString)\0iconChanged()\0"
"statusTextChanged()\0htmlChanged()\0"
"pressGrabTimeChanged()\0"
"newWindowComponentChanged()\0"
"newWindowParentChanged()\0"
"renderingEnabledChanged()\0"
"contentsSizeChanged(QSize)\0"
"contentsScaleChanged()\0backgroundColorChanged()\0"
"loadStarted()\0loadFinished()\0loadFailed()\0"
"clickX,clickY\0doubleClick(int,int)\0"
"zoom,centerX,centerY\0zoomTo(qreal,int,int)\0"
"message\0alert(QString)\0QVariant\0"
"evaluateJavaScript(QString)\0doLoadStarted()\0"
"p\0doLoadProgress(int)\0ok\0doLoadFinished(bool)\0"
"setStatusText(QString)\0windowObjectCleared()\0"
"pageUrlChanged()\0initialLayout()\0"
"updateDeclarativeWebViewSize()\0"
"newGeometry,oldGeometry\0"
"geometryChanged(QRectF,QRectF)\0"
"QDeclarativeWebView*\0type\0"
"createWindow(QWebPage::WebWindowType)\0"
"bool\0clickX,clickY,maxzoom\0"
"heuristicZoom(int,int,qreal)\0QString\0"
"title\0QPixmap\0icon\0statusText\0html\0"
"int\0pressGrabTime\0preferredWidth\0"
"preferredHeight\0QUrl\0url\0qreal\0progress\0"
"Status\0status\0QAction*\0reload\0back\0"
"forward\0stop\0QDeclarativeWebSettings*\0"
"settings\0QDeclarativeListProperty<QObject>\0"
"javaScriptWindowObjects\0QDeclarativeComponent*\0"
"newWindowComponent\0QDeclarativeItem*\0"
"newWindowParent\0renderingEnabled\0QSize\0"
"contentsSize\0contentsScale\0QColor\0"
"backgroundColor\0Null\0Ready\0Loading\0"
"Error\0"
};
void QDeclarativeWebView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
QDeclarativeWebView *_t = static_cast<QDeclarativeWebView *>(_o);
switch (_id) {
case 0: _t->preferredWidthChanged(); break;
case 1: _t->preferredHeightChanged(); break;
case 2: _t->urlChanged(); break;
case 3: _t->progressChanged(); break;
case 4: _t->statusChanged((*reinterpret_cast< Status(*)>(_a[1]))); break;
case 5: _t->titleChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 6: _t->iconChanged(); break;
case 7: _t->statusTextChanged(); break;
case 8: _t->htmlChanged(); break;
case 9: _t->pressGrabTimeChanged(); break;
case 10: _t->newWindowComponentChanged(); break;
case 11: _t->newWindowParentChanged(); break;
case 12: _t->renderingEnabledChanged(); break;
case 13: _t->contentsSizeChanged((*reinterpret_cast< const QSize(*)>(_a[1]))); break;
case 14: _t->contentsScaleChanged(); break;
case 15: _t->backgroundColorChanged(); break;
case 16: _t->loadStarted(); break;
case 17: _t->loadFinished(); break;
case 18: _t->loadFailed(); break;
case 19: _t->doubleClick((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 20: _t->zoomTo((*reinterpret_cast< qreal(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
case 21: _t->alert((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 22: { QVariant _r = _t->evaluateJavaScript((*reinterpret_cast< const QString(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< QVariant*>(_a[0]) = _r; } break;
case 23: _t->doLoadStarted(); break;
case 24: _t->doLoadProgress((*reinterpret_cast< int(*)>(_a[1]))); break;
case 25: _t->doLoadFinished((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 26: _t->setStatusText((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 27: _t->windowObjectCleared(); break;
case 28: _t->pageUrlChanged(); break;
case 29: _t->initialLayout(); break;
case 30: _t->updateDeclarativeWebViewSize(); break;
case 31: _t->geometryChanged((*reinterpret_cast< const QRectF(*)>(_a[1])),(*reinterpret_cast< const QRectF(*)>(_a[2]))); break;
case 32: { QDeclarativeWebView* _r = _t->createWindow((*reinterpret_cast< QWebPage::WebWindowType(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< QDeclarativeWebView**>(_a[0]) = _r; } break;
case 33: { bool _r = _t->heuristicZoom((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< qreal(*)>(_a[3])));
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break;
default: ;
}
}
}
const QMetaObjectExtraData QDeclarativeWebView::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QDeclarativeWebView::staticMetaObject = {
{ &QDeclarativeItem::staticMetaObject, qt_meta_stringdata_QDeclarativeWebView,
qt_meta_data_QDeclarativeWebView, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QDeclarativeWebView::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QDeclarativeWebView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QDeclarativeWebView::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QDeclarativeWebView))
return static_cast<void*>(const_cast< QDeclarativeWebView*>(this));
return QDeclarativeItem::qt_metacast(_clname);
}
int QDeclarativeWebView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDeclarativeItem::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 34)
qt_static_metacall(this, _c, _id, _a);
_id -= 34;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< QString*>(_v) = title(); break;
case 1: *reinterpret_cast< QPixmap*>(_v) = icon(); break;
case 2: *reinterpret_cast< QString*>(_v) = statusText(); break;
case 3: *reinterpret_cast< QString*>(_v) = html(); break;
case 4: *reinterpret_cast< int*>(_v) = pressGrabTime(); break;
case 5: *reinterpret_cast< int*>(_v) = preferredWidth(); break;
case 6: *reinterpret_cast< int*>(_v) = preferredHeight(); break;
case 7: *reinterpret_cast< QUrl*>(_v) = url(); break;
case 8: *reinterpret_cast< qreal*>(_v) = progress(); break;
case 9: *reinterpret_cast< Status*>(_v) = status(); break;
case 10: *reinterpret_cast< QAction**>(_v) = reloadAction(); break;
case 11: *reinterpret_cast< QAction**>(_v) = backAction(); break;
case 12: *reinterpret_cast< QAction**>(_v) = forwardAction(); break;
case 13: *reinterpret_cast< QAction**>(_v) = stopAction(); break;
case 14: *reinterpret_cast< QDeclarativeWebSettings**>(_v) = settingsObject(); break;
case 15: *reinterpret_cast< QDeclarativeListProperty<QObject>*>(_v) = javaScriptWindowObjects(); break;
case 16: *reinterpret_cast< QDeclarativeComponent**>(_v) = newWindowComponent(); break;
case 17: *reinterpret_cast< QDeclarativeItem**>(_v) = newWindowParent(); break;
case 18: *reinterpret_cast< bool*>(_v) = renderingEnabled(); break;
case 19: *reinterpret_cast< QSize*>(_v) = contentsSize(); break;
case 20: *reinterpret_cast< qreal*>(_v) = contentsScale(); break;
case 21: *reinterpret_cast< QColor*>(_v) = backgroundColor(); break;
}
_id -= 22;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
switch (_id) {
case 3: setHtml(*reinterpret_cast< QString*>(_v)); break;
case 4: setPressGrabTime(*reinterpret_cast< int*>(_v)); break;
case 5: setPreferredWidth(*reinterpret_cast< int*>(_v)); break;
case 6: setPreferredHeight(*reinterpret_cast< int*>(_v)); break;
case 7: setUrl(*reinterpret_cast< QUrl*>(_v)); break;
case 16: setNewWindowComponent(*reinterpret_cast< QDeclarativeComponent**>(_v)); break;
case 17: setNewWindowParent(*reinterpret_cast< QDeclarativeItem**>(_v)); break;
case 18: setRenderingEnabled(*reinterpret_cast< bool*>(_v)); break;
case 20: setContentsScale(*reinterpret_cast< qreal*>(_v)); break;
case 21: setBackgroundColor(*reinterpret_cast< QColor*>(_v)); break;
}
_id -= 22;
} else if (_c == QMetaObject::ResetProperty) {
_id -= 22;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 22;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 22;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 22;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 22;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 22;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void QDeclarativeWebView::preferredWidthChanged()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
// SIGNAL 1
void QDeclarativeWebView::preferredHeightChanged()
{
QMetaObject::activate(this, &staticMetaObject, 1, 0);
}
// SIGNAL 2
void QDeclarativeWebView::urlChanged()
{
QMetaObject::activate(this, &staticMetaObject, 2, 0);
}
// SIGNAL 3
void QDeclarativeWebView::progressChanged()
{
QMetaObject::activate(this, &staticMetaObject, 3, 0);
}
// SIGNAL 4
void QDeclarativeWebView::statusChanged(Status _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 4, _a);
}
// SIGNAL 5
void QDeclarativeWebView::titleChanged(const QString & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 5, _a);
}
// SIGNAL 6
void QDeclarativeWebView::iconChanged()
{
QMetaObject::activate(this, &staticMetaObject, 6, 0);
}
// SIGNAL 7
void QDeclarativeWebView::statusTextChanged()
{
QMetaObject::activate(this, &staticMetaObject, 7, 0);
}
// SIGNAL 8
void QDeclarativeWebView::htmlChanged()
{
QMetaObject::activate(this, &staticMetaObject, 8, 0);
}
// SIGNAL 9
void QDeclarativeWebView::pressGrabTimeChanged()
{
QMetaObject::activate(this, &staticMetaObject, 9, 0);
}
// SIGNAL 10
void QDeclarativeWebView::newWindowComponentChanged()
{
QMetaObject::activate(this, &staticMetaObject, 10, 0);
}
// SIGNAL 11
void QDeclarativeWebView::newWindowParentChanged()
{
QMetaObject::activate(this, &staticMetaObject, 11, 0);
}
// SIGNAL 12
void QDeclarativeWebView::renderingEnabledChanged()
{
QMetaObject::activate(this, &staticMetaObject, 12, 0);
}
// SIGNAL 13
void QDeclarativeWebView::contentsSizeChanged(const QSize & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 13, _a);
}
// SIGNAL 14
void QDeclarativeWebView::contentsScaleChanged()
{
QMetaObject::activate(this, &staticMetaObject, 14, 0);
}
// SIGNAL 15
void QDeclarativeWebView::backgroundColorChanged()
{
QMetaObject::activate(this, &staticMetaObject, 15, 0);
}
// SIGNAL 16
void QDeclarativeWebView::loadStarted()
{
QMetaObject::activate(this, &staticMetaObject, 16, 0);
}
// SIGNAL 17
void QDeclarativeWebView::loadFinished()
{
QMetaObject::activate(this, &staticMetaObject, 17, 0);
}
// SIGNAL 18
void QDeclarativeWebView::loadFailed()
{
QMetaObject::activate(this, &staticMetaObject, 18, 0);
}
// SIGNAL 19
void QDeclarativeWebView::doubleClick(int _t1, int _t2)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 19, _a);
}
// SIGNAL 20
void QDeclarativeWebView::zoomTo(qreal _t1, int _t2, int _t3)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 20, _a);
}
// SIGNAL 21
void QDeclarativeWebView::alert(const QString & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 21, _a);
}
static const uint qt_meta_data_QDeclarativeWebViewAttached[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
1, 14, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// properties: name, type, flags
36, 28, 0x0a095103,
0 // eod
};
static const char qt_meta_stringdata_QDeclarativeWebViewAttached[] = {
"QDeclarativeWebViewAttached\0QString\0"
"windowObjectName\0"
};
void QDeclarativeWebViewAttached::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData QDeclarativeWebViewAttached::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QDeclarativeWebViewAttached::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_QDeclarativeWebViewAttached,
qt_meta_data_QDeclarativeWebViewAttached, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QDeclarativeWebViewAttached::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QDeclarativeWebViewAttached::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QDeclarativeWebViewAttached::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QDeclarativeWebViewAttached))
return static_cast<void*>(const_cast< QDeclarativeWebViewAttached*>(this));
return QObject::qt_metacast(_clname);
}
int QDeclarativeWebViewAttached::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
#ifndef QT_NO_PROPERTIES
if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< QString*>(_v) = windowObjectName(); break;
}
_id -= 1;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
switch (_id) {
case 0: setWindowObjectName(*reinterpret_cast< QString*>(_v)); break;
}
_id -= 1;
} else if (_c == QMetaObject::ResetProperty) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 1;
}
#endif // QT_NO_PROPERTIES
return _id;
}
static const uint qt_meta_data_QDeclarativeWebSettings[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
25, 14, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// properties: name, type, flags
32, 24, 0x0a095103,
51, 24, 0x0a095103,
67, 24, 0x0a095103,
83, 24, 0x0a095103,
103, 24, 0x0a095103,
121, 24, 0x0a095103,
143, 139, 0x02095103,
159, 139, 0x02095103,
182, 139, 0x02095103,
198, 139, 0x02095103,
224, 219, 0x01095103,
239, 219, 0x01095103,
257, 219, 0x01095103,
269, 219, 0x01095103,
284, 219, 0x01095103,
307, 219, 0x01095103,
332, 219, 0x01095103,
361, 219, 0x01095103,
384, 219, 0x01095103,
410, 219, 0x01095103,
423, 219, 0x01095103,
447, 219, 0x01095103,
477, 219, 0x01095103,
511, 219, 0x01095103,
539, 219, 0x01095103,
0 // eod
};
static const char qt_meta_stringdata_QDeclarativeWebSettings[] = {
"QDeclarativeWebSettings\0QString\0"
"standardFontFamily\0fixedFontFamily\0"
"serifFontFamily\0sansSerifFontFamily\0"
"cursiveFontFamily\0fantasyFontFamily\0"
"int\0minimumFontSize\0minimumLogicalFontSize\0"
"defaultFontSize\0defaultFixedFontSize\0"
"bool\0autoLoadImages\0javascriptEnabled\0"
"javaEnabled\0pluginsEnabled\0"
"privateBrowsingEnabled\0javascriptCanOpenWindows\0"
"javascriptCanAccessClipboard\0"
"developerExtrasEnabled\0linksIncludedInFocusChain\0"
"zoomTextOnly\0printElementBackgrounds\0"
"offlineStorageDatabaseEnabled\0"
"offlineWebApplicationCacheEnabled\0"
"localStorageDatabaseEnabled\0"
"localContentCanAccessRemoteUrls\0"
};
void QDeclarativeWebSettings::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData QDeclarativeWebSettings::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QDeclarativeWebSettings::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_QDeclarativeWebSettings,
qt_meta_data_QDeclarativeWebSettings, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QDeclarativeWebSettings::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QDeclarativeWebSettings::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QDeclarativeWebSettings::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QDeclarativeWebSettings))
return static_cast<void*>(const_cast< QDeclarativeWebSettings*>(this));
return QObject::qt_metacast(_clname);
}
int QDeclarativeWebSettings::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
#ifndef QT_NO_PROPERTIES
if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< QString*>(_v) = standardFontFamily(); break;
case 1: *reinterpret_cast< QString*>(_v) = fixedFontFamily(); break;
case 2: *reinterpret_cast< QString*>(_v) = serifFontFamily(); break;
case 3: *reinterpret_cast< QString*>(_v) = sansSerifFontFamily(); break;
case 4: *reinterpret_cast< QString*>(_v) = cursiveFontFamily(); break;
case 5: *reinterpret_cast< QString*>(_v) = fantasyFontFamily(); break;
case 6: *reinterpret_cast< int*>(_v) = minimumFontSize(); break;
case 7: *reinterpret_cast< int*>(_v) = minimumLogicalFontSize(); break;
case 8: *reinterpret_cast< int*>(_v) = defaultFontSize(); break;
case 9: *reinterpret_cast< int*>(_v) = defaultFixedFontSize(); break;
case 10: *reinterpret_cast< bool*>(_v) = autoLoadImages(); break;
case 11: *reinterpret_cast< bool*>(_v) = javascriptEnabled(); break;
case 12: *reinterpret_cast< bool*>(_v) = javaEnabled(); break;
case 13: *reinterpret_cast< bool*>(_v) = pluginsEnabled(); break;
case 14: *reinterpret_cast< bool*>(_v) = privateBrowsingEnabled(); break;
case 15: *reinterpret_cast< bool*>(_v) = javascriptCanOpenWindows(); break;
case 16: *reinterpret_cast< bool*>(_v) = javascriptCanAccessClipboard(); break;
case 17: *reinterpret_cast< bool*>(_v) = developerExtrasEnabled(); break;
case 18: *reinterpret_cast< bool*>(_v) = linksIncludedInFocusChain(); break;
case 19: *reinterpret_cast< bool*>(_v) = zoomTextOnly(); break;
case 20: *reinterpret_cast< bool*>(_v) = printElementBackgrounds(); break;
case 21: *reinterpret_cast< bool*>(_v) = offlineStorageDatabaseEnabled(); break;
case 22: *reinterpret_cast< bool*>(_v) = offlineWebApplicationCacheEnabled(); break;
case 23: *reinterpret_cast< bool*>(_v) = localStorageDatabaseEnabled(); break;
case 24: *reinterpret_cast< bool*>(_v) = localContentCanAccessRemoteUrls(); break;
}
_id -= 25;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
switch (_id) {
case 0: setStandardFontFamily(*reinterpret_cast< QString*>(_v)); break;
case 1: setFixedFontFamily(*reinterpret_cast< QString*>(_v)); break;
case 2: setSerifFontFamily(*reinterpret_cast< QString*>(_v)); break;
case 3: setSansSerifFontFamily(*reinterpret_cast< QString*>(_v)); break;
case 4: setCursiveFontFamily(*reinterpret_cast< QString*>(_v)); break;
case 5: setFantasyFontFamily(*reinterpret_cast< QString*>(_v)); break;
case 6: setMinimumFontSize(*reinterpret_cast< int*>(_v)); break;
case 7: setMinimumLogicalFontSize(*reinterpret_cast< int*>(_v)); break;
case 8: setDefaultFontSize(*reinterpret_cast< int*>(_v)); break;
case 9: setDefaultFixedFontSize(*reinterpret_cast< int*>(_v)); break;
case 10: setAutoLoadImages(*reinterpret_cast< bool*>(_v)); break;
case 11: setJavascriptEnabled(*reinterpret_cast< bool*>(_v)); break;
case 12: setJavaEnabled(*reinterpret_cast< bool*>(_v)); break;
case 13: setPluginsEnabled(*reinterpret_cast< bool*>(_v)); break;
case 14: setPrivateBrowsingEnabled(*reinterpret_cast< bool*>(_v)); break;
case 15: setJavascriptCanOpenWindows(*reinterpret_cast< bool*>(_v)); break;
case 16: setJavascriptCanAccessClipboard(*reinterpret_cast< bool*>(_v)); break;
case 17: setDeveloperExtrasEnabled(*reinterpret_cast< bool*>(_v)); break;
case 18: setLinksIncludedInFocusChain(*reinterpret_cast< bool*>(_v)); break;
case 19: setZoomTextOnly(*reinterpret_cast< bool*>(_v)); break;
case 20: setPrintElementBackgrounds(*reinterpret_cast< bool*>(_v)); break;
case 21: setOfflineStorageDatabaseEnabled(*reinterpret_cast< bool*>(_v)); break;
case 22: setOfflineWebApplicationCacheEnabled(*reinterpret_cast< bool*>(_v)); break;
case 23: setLocalStorageDatabaseEnabled(*reinterpret_cast< bool*>(_v)); break;
case 24: setLocalContentCanAccessRemoteUrls(*reinterpret_cast< bool*>(_v)); break;
}
_id -= 25;
} else if (_c == QMetaObject::ResetProperty) {
_id -= 25;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 25;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 25;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 25;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 25;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 25;
}
#endif // QT_NO_PROPERTIES
return _id;
}
QT_END_MOC_NAMESPACE
| lgpl-2.1 |
FedoraScientific/salome-geom | src/GEOM_SWIG/STEPPluginBuilder.py | 5041 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2014 CEA/DEN, EDF R&D, OPEN CASCADE
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.salome-platform.org/ or email : [email protected]
#
from GEOM import ISTEPOperations
# Engine Library Name
__libraryName__ = "STEPPluginEngine"
def GetSTEPPluginOperations(self):
anOp = self.GetPluginOperations(self.myStudyId, __libraryName__)
return anOp._narrow(ISTEPOperations)
## Export the given shape into a file with given name in STEP format.
# @param theObject Shape to be stored in the file.
# @param theFileName Name of the file to store the given shape in.
# @ingroup l2_import_export
def ExportSTEP(self, theObject, theFileName):
"""
Export the given shape into a file with given name in STEP format.
Parameters:
theObject Shape to be stored in the file.
theFileName Name of the file to store the given shape in.
"""
anOp = GetSTEPPluginOperations(self)
anOp.ExportSTEP(theObject, theFileName)
if anOp.IsDone() == 0:
raise RuntimeError, "Export : " + anOp.GetErrorCode()
pass
pass
## Import a shape from the STEP file with given name.
# @param theFileName The file, containing the shape.
# @param theIsIgnoreUnits If True, file length units will be ignored (set to 'meter')
# and result model will be scaled, if its units are not meters.
# If False (default), file length units will be taken into account.
# @param theName Object name; when specified, this parameter is used
# for result publication in the study. Otherwise, if automatic
# publication is switched on, default value is used for result name.
#
# @return New GEOM.GEOM_Object, containing the imported shape.
# If material names are imported it returns the list of
# objects. The first one is the imported object followed by
# material groups.
# @note Auto publishing is allowed for the shape itself. Imported
# material groups are not automatically published.
#
# @ref swig_Import_Export "Example"
# @ingroup l2_import_export
def ImportSTEP(self, theFileName, theIsIgnoreUnits = False, theName=None):
"""
Import a shape from the STEP file with given name.
Parameters:
theFileName The file, containing the shape.
ignoreUnits If True, file length units will be ignored (set to 'meter')
and result model will be scaled, if its units are not meters.
If False (default), file length units will be taken into account.
theName Object name; when specified, this parameter is used
for result publication in the study. Otherwise, if automatic
publication is switched on, default value is used for result name.
Returns:
New GEOM.GEOM_Object, containing the imported shape.
If material names are imported it returns the list of
objects. The first one is the imported object followed by
material groups.
Note:
Auto publishing is allowed for the shape itself. Imported
material groups are not automatically published.
"""
# Example: see GEOM_TestOthers.py
from salome.geom.geomBuilder import RaiseIfFailed
anOp = GetSTEPPluginOperations(self)
anIsIgnoreUnits = theIsIgnoreUnits
aName = theName
if isinstance( theIsIgnoreUnits, basestring ):
anIsIgnoreUnits = False
aName = theIsIgnoreUnits
pass
aListObj = anOp.ImportSTEP(theFileName,anIsIgnoreUnits)
RaiseIfFailed("ImportSTEP", anOp)
aNbObj = len(aListObj)
if aNbObj > 0:
self._autoPublish(aListObj[0], aName, "imported")
if aNbObj == 1:
return aListObj[0]
return aListObj
## Return length unit from given STEP file
# @param theFileName The file, containing the shape.
# @return String, containing the units name.
#
# @ref swig_Import_Export "Example"
# @ingroup l2_import_export
def GetSTEPUnit(self, theFileName):
"""
Return length units from given STEP file
Parameters:
theFileName The file, containing the shape.
Returns:
String, containing the units name.
"""
# Example: see GEOM_TestOthers.py
anOp = GetSTEPPluginOperations(self)
aUnitName = anOp.ReadValue( theFileName, "LEN_UNITS")
return aUnitName
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | libraries/libserializer/src/main/java/org/pentaho/reporting/libraries/serializer/methods/GeneralPathSerializer.java | 5322 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.libraries.serializer.methods;
import org.pentaho.reporting.libraries.serializer.SerializeMethod;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* A serialize method that handles java.awt.geom.GeneralPath objects.
*
* @author Thomas Morgner
*/
public class GeneralPathSerializer implements SerializeMethod {
/**
* Default constructor.
*/
public GeneralPathSerializer() {
}
/**
* The class of the object, which this object can serialize.
*
* @return the class of the object type, which this method handles.
*/
public Class getObjectClass() {
return GeneralPath.class;
}
/**
* Reads the object from the object input stream.
*
* @param in the object input stream from where to read the serialized data.
* @return the generated object.
* @throws java.io.IOException if reading the stream failed.
* @throws ClassNotFoundException if serialized object class cannot be found.
*/
public Object readObject( final ObjectInputStream in )
throws IOException, ClassNotFoundException {
final int winding = in.readInt();
final GeneralPath gp = new GeneralPath( winding );
// type will be -1 at the end of the GPath ..
int type = in.readInt();
while ( type >= 0 ) {
switch( type ) {
case PathIterator.SEG_MOVETO: {
final float x = in.readFloat();
final float y = in.readFloat();
gp.moveTo( x, y );
break;
}
case PathIterator.SEG_LINETO: {
final float x = in.readFloat();
final float y = in.readFloat();
gp.lineTo( x, y );
break;
}
case PathIterator.SEG_QUADTO: {
final float x1 = in.readFloat();
final float y1 = in.readFloat();
final float x2 = in.readFloat();
final float y2 = in.readFloat();
gp.quadTo( x1, y1, x2, y2 );
break;
}
case PathIterator.SEG_CUBICTO: {
final float x1 = in.readFloat();
final float y1 = in.readFloat();
final float x2 = in.readFloat();
final float y2 = in.readFloat();
final float x3 = in.readFloat();
final float y3 = in.readFloat();
gp.curveTo( x1, y1, x2, y2, x3, y3 );
break;
}
case PathIterator.SEG_CLOSE: {
break;
}
default:
throw new IOException( "Unexpected type encountered: " + type );
}
type = in.readInt();
}
return gp;
}
/**
* Writes a serializable object description to the given object output stream.
*
* @param o the to be serialized object.
* @param out the outputstream that should receive the object.
* @throws java.io.IOException if an I/O error occured.
*/
public void writeObject( final Object o, final ObjectOutputStream out )
throws IOException {
final GeneralPath gp = (GeneralPath) o;
final PathIterator it = gp.getPathIterator( new AffineTransform() );
out.writeInt( it.getWindingRule() );
while ( it.isDone() == false ) {
final float[] corrds = new float[ 6 ];
final int type = it.currentSegment( corrds );
out.writeInt( type );
switch( type ) {
case PathIterator.SEG_MOVETO: {
out.writeFloat( corrds[ 0 ] );
out.writeFloat( corrds[ 1 ] );
break;
}
case PathIterator.SEG_LINETO: {
out.writeFloat( corrds[ 0 ] );
out.writeFloat( corrds[ 1 ] );
break;
}
case PathIterator.SEG_QUADTO: {
out.writeFloat( corrds[ 0 ] );
out.writeFloat( corrds[ 1 ] );
out.writeFloat( corrds[ 2 ] );
out.writeFloat( corrds[ 3 ] );
break;
}
case PathIterator.SEG_CUBICTO: {
out.writeFloat( corrds[ 0 ] );
out.writeFloat( corrds[ 1 ] );
out.writeFloat( corrds[ 2 ] );
out.writeFloat( corrds[ 3 ] );
out.writeFloat( corrds[ 4 ] );
out.writeFloat( corrds[ 5 ] );
break;
}
case PathIterator.SEG_CLOSE: {
break;
}
default:
throw new IOException( "Unexpected type encountered: " + type );
}
it.next();
}
out.writeInt( -1 );
}
}
| lgpl-2.1 |
lukeu/TracInstant | src/main/java/com/github/tracinstant/app/download/Target.java | 2587 | /*
* Copyright 2011 the original author or authors.
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.tracinstant.app.download;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
public class Target {
public enum State {
IDLE, STARTED, ENDED, ERROR
}
private final Downloadable source;
private boolean alreadyExists;
private State state = State.IDLE;
private long bytesDownloaded = 0;
private String errorMessage = null;
private boolean selected = true;
public Target(Path localDir, Downloadable source) {
this.source = source;
if (localDir != null) {
updateTargetFile(localDir);
}
}
public void setTopFolder(Path localDir) {
updateTargetFile(localDir);
}
private void updateTargetFile(Path localDir) {
Path ticketDir = localDir.resolve(Integer.toString(source.getTicketNumber()));
alreadyExists = Files.exists(ticketDir.resolve(source.getRelativePath()));
}
public boolean isOverwriting() {
return alreadyExists;
}
public Downloadable getSource() {
return source;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public long getBytesDownloaded() {
return bytesDownloaded;
}
public void setBytesDownloaded(long bytesDownloaded) {
this.bytesDownloaded = bytesDownloaded;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public String toString() {
return "" + source.getTicketNumber() + File.separator + source.getRelativePath();
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean b) {
selected = b;
}
}
| lgpl-2.1 |
oregional/tiki | lib/wiki/semanticlib.php | 11008 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
class SemanticLib
{
private $knownTokens = false;
private $newTokens = false;
private function loadKnownTokens() // {{{
{
if ( is_array($this->knownTokens) )
return;
$tikilib = TikiLib::lib('tiki');
$this->knownTokens = array();
$result = $tikilib->query("SELECT token, label, invert_token FROM tiki_semantic_tokens");
while ( $row = $result->fetchRow() ) {
$token = $row['token'];
$this->knownTokens[$token] = $row;
}
ksort($this->knownTokens);
} // }}}
private function loadNewTokens() // {{{
{
if ( is_array($this->newTokens) )
return;
$db = TikiDb::get();
$result = $db->fetchAll("SELECT DISTINCT relation FROM tiki_object_relations WHERE relation LIKE 'tiki.link.%'");
$tokens = array();
foreach ( $result as $row ) {
$tokens[] = substr($row['relation'], strlen('tiki.link.'));
}
$this->loadKnownTokens();
$existing = array_keys($this->knownTokens);
$this->newTokens = array_diff($tokens, $existing);
} // }}}
function getToken( $name, $field = null ) // {{{
{
$this->loadKnownTokens();
if ( array_key_exists($name, $this->knownTokens) ) {
$data = $this->knownTokens[$name];
if ( is_null($field) )
return $data;
if ( array_key_exists($field, $data) )
return $data[$field];
}
return false;
} // }}}
function getInvert( $name, $field = null ) // {{{
{
if ( false !== $invert = $this->getToken($name, 'invert_token') ) {
if ( empty($invert) )
$invert = $name;
return $this->getToken($invert, $field);
}
return false;
} // }}}
function getTokens() // {{{
{
$this->loadKnownTokens();
return $this->knownTokens;
} // }}}
function getNewTokens() // {{{
{
$this->loadNewTokens();
return $this->newTokens;
} // }}}
function getAllTokens() // {{{
{
$this->loadKnownTokens();
$this->loadNewTokens();
return array_merge(array_keys($this->knownTokens), $this->newTokens);
} // }}}
function getLinksUsing( $token, $conditions = array() ) // {{{
{
$db = TikiDb::get();
$token = (array) $token;
$bindvars = array();
// Multiple tokens can be fetched at the same time
$values = array();
foreach ( $token as $name ) {
$values[] = "tiki.link.$name";
}
$mid = array( $db->in('relation', $values, $bindvars) );
// Filter on source and destination
foreach ( $conditions as $field => $value ) {
if ( $field == 'fromPage' ) {
$field = 'source_itemId';
} elseif ( $field == 'toPage' ) {
$field = 'target_itemId';
} else {
continue;
}
$mid[] = "`$field` = ?";
$bindvars[] = $value;
}
$mid = implode(' AND ', $mid);
$result = $db->query(
$q = "SELECT `source_itemId` `fromPage`, `target_itemId` `toPage`, GROUP_CONCAT(SUBSTR(`relation` FROM 11) SEPARATOR ',') `reltype` FROM tiki_object_relations WHERE $mid AND `source_type` = 'wiki page' AND `target_type` = 'wiki page' AND `relation` LIKE 'tiki.link.%' GROUP BY `fromPage`, `toPage` ORDER BY `fromPage`, `toPage`",
$bindvars
);
$links = array();
while ( $row = $result->fetchRow() ) {
$row['reltype'] = explode(',', $row['reltype']);
$links[] = $row;
}
return $links;
} // }}}
function replaceToken( $oldName, $newName, $label, $invert = null ) // {{{
{
$exists = ( false !== $this->getToken($oldName) );
if ( $oldName != $newName && false !== $this->getToken($newName) )
return tra('Semantic token already exists') . ": $newName";
if ( !$this->isValid($oldName) )
return tra('Invalid semantic token name') . ": $oldName";
if ( !$this->isValid($newName) )
return tra('Invalid semantic token name') . ": $newName";
if ( false === $this->getToken($invert) || $invert == $newName )
$invert = null;
$tikilib = TikiLib::lib('tiki');
if ( $exists ) {
$tikilib->query("DELETE FROM tiki_semantic_tokens WHERE token = ?", array( $oldName ));
}
if ( is_null($invert) ) {
$tikilib->query("INSERT INTO tiki_semantic_tokens (token, label) VALUES(?,?)", array( $newName, $label ));
} else {
$tikilib->query("INSERT INTO tiki_semantic_tokens (token, label, invert_token) VALUES(?,?,?)", array( $newName, $label, $invert ));
}
if ( $oldName != '' && $newName != $oldName ) {
$tikilib->query("UPDATE tiki_semantic_tokens SET invert_token = ? WHERE invert_token = ?", array( $newName, $oldName ));
$this->replaceReferences($oldName, $newName);
}
unset( $this->knownTokens[$oldName] );
$this->knownTokens[$newName] = array(
'token' => $newName,
'label' => $label,
'invert_token' => $invert,
);
ksort($this->knownTokens);
return true;
} // }}}
private function replaceReferences( $oldName, $newName = null ) // {{{
{
$tikilib = TikiLib::lib('tiki');
if ( ! $this->isValid($oldName) )
return tra('Invalid semantic token name') . ": $oldName";
if ( ! is_null($newName) && ! $this->isValid($newName) && $valid )
return tra('Invalid semantic token name') . ": $newName";
$links = $this->getLinksUsing($oldName);
$pagesDone = array();
foreach ( $links as $link ) {
// Page body only needs to be replaced once
if ( ! array_key_exists($link['fromPage'], $pagesDone) ) {
$info = $tikilib->get_page_info($link['fromPage']);
$data = $info['data'];
$data = str_replace("($oldName(", "($newName(", $data);
$query = "update `tiki_pages` set `data`=?,`page_size`=? where `pageName`=?";
$tikilib->query($query, array( $data,(int) strlen($data), $link['fromPage']));
$pagesDone[ $link['fromPage'] ] = true;
}
}
if ( $newName ) {
$tikilib->query('UPDATE tiki_object_relations SET relation = ? WHERE relation = ? AND source_type = "wiki page" AND target_type = "wiki page"', array( "tiki.link.$newName", "tiki.link.$oldName" ));
} else {
$tikilib->query('DELETE FROM tiki_object_relations WHERE relation = ? AND source_type = "wiki page" AND target_type = "wiki page"', array( "tiki.link.$oldName" ));
}
return true;
} // }}}
function cleanToken( $token ) // {{{
{
$this->replaceReferences($token);
$this->newTokens = array_diff($this->newTokens, array( $token ));
} // }}}
function removeToken( $token, $removeReferences = false ) // {{{
{
$tikilib = TikiLib::lib('tiki');
if ( false === $this->getToken($token) )
return tra("Semantic token not found") . ": $token";
$tikilib->query("DELETE FROM tiki_semantic_tokens WHERE token = ?", array( $token ));
unset($this->knownTokens[$token]);
if ( $removeReferences )
$this->replaceReferences($token, '');
elseif ( $this->newTokens !== false )
$this->newTokens[] = $token;
return true;
} // }}}
function renameToken( $oldName, $newName ) // {{{
{
$this->replaceReferences($oldName, $newName);
$this->newTokens = array_diff($this->newTokens, array( $oldName ));
if ( false === $this->getToken($newName) )
$this->newTokens[] = $newName;
} // }}}
function isValid( $token ) // {{{
{
return preg_match("/^[a-z0-9-]{1,15}\\z/", $token);
} // }}}
function getRelationList( $page ) // {{{
{
$wikilib = TikiLib::lib('wiki');
$tikilib = TikiLib::lib('tiki');
$relations = array();
$result = $tikilib->fetchAll("SELECT `target_itemId` `toPage`, SUBSTR(`relation` FROM 11) `reltype` FROM tiki_object_relations WHERE `source_itemId` = ? AND `source_type` = 'wiki page' AND `target_type` = 'wiki page' AND `relation` LIKE 'tiki.link.%'", array($page));
foreach ( $result as $row ) {
if ( false === $label = $this->getToken($row['reltype'], 'label'))
continue;
$label = tra($label);
if ( ! array_key_exists($label, $relations) )
$relations[$label] = array();
if ( ! array_key_exists($row['toPage'], $relations[$label]) )
$relations[$label][ $row['toPage'] ] = $wikilib->sefurl($row['toPage']);
}
$result = $tikilib->fetchAll("SELECT `source_itemId` `fromPage`, SUBSTR(`relation` FROM 11) `reltype` FROM tiki_object_relations WHERE `target_itemId` = ? AND `source_type` = 'wiki page' AND `target_type` = 'wiki page' AND `relation` LIKE 'tiki.link.%'", array($page));
foreach ( $result as $row ) {
if ( false === $label = $this->getInvert($row['reltype'], 'label'))
continue;
$label = tra($label);
if ( ! array_key_exists($label, $relations) )
$relations[$label] = array();
if ( ! array_key_exists($row['fromPage'], $relations[$label]) )
$relations[$label][ $row['fromPage'] ] = $wikilib->sefurl($row['fromPage']);
}
ksort($relations);
foreach ( $relations as &$set )
ksort($set);
return $relations;
} // }}}
function getAliasContaining( $query, $exact_match = false, $in_lang = NULL ) // {{{
{
global $prefs;
$tikilib = TikiLib::lib('tiki');
$orig_query = $query;
if (!$exact_match) {
$query = "%$query%";
}
$mid = "((`target_type` = 'wiki page' AND `target_itemId` LIKE ?)";
$bindvars = array($query);
$prefixes = explode(',', $prefs["wiki_prefixalias_tokens"]);
$haveprefixes = false;
foreach ($prefixes as $p) {
$p = trim($p);
if (strlen($p) > 0 && TikiLib::strtolower(substr($query, 0, strlen($p))) == TikiLib::strtolower($p)) {
$mid .= " OR ( `target_type` = 'wiki page' AND `target_itemId` LIKE ?)";
$bindvars[] = "$p%";
$haveprefixes = true;
}
}
$mid .= ") AND ( `relation` = 'tiki.link.alias' ";
if ( $haveprefixes ) {
$mid .= " OR `relation` = 'tiki.link.prefixalias' ";
}
$mid .= ")";
$querystring = "SELECT `source_itemId` `fromPage`, `target_itemId` `toPage` FROM `tiki_object_relations` WHERE $mid";
$aliases = $tikilib->fetchAll($querystring, $bindvars);
$aliases = $this->onlyKeepAliasesFromPageInLanguage($in_lang, $aliases);
return $aliases;
} // }}}
function onlyKeepAliasesFromPageInLanguage($language, $aliases)
{
$multilinguallib = TikiLib::lib('multilingual');
if (!$language) {
return $aliases;
}
$aliasesInCorrectLanguage = array();
foreach ($aliases as $index => $aliasInfo) {
$aliasLang = $multilinguallib->getLangOfPage($aliasInfo['fromPage']);
if ($aliasLang === $language) {
$aliasesInCorrectLanguage[] = $aliasInfo;
}
}
// echo "<pre>-- onlyKeepAliasesFromPageInLanguage: exiting</pre>\n";
return $aliasesInCorrectLanguage;
}
function getItemsFromTracker($page, $suffix)
{
$t_links = $this->getLinksUsing('trackerid', array( 'fromPage' => $page ));
$f_links = $this->getLinksUsing('titlefieldid', array( 'fromPage' => $page ));
$ret = array();
if (count($t_links) && count($f_links) && ctype_digit($t_links[0]['toPage']) && ctype_digit($f_links[0]['toPage'])) {
$trklib = TikiLib::lib('trk');
$items = $trklib->list_items($t_links[0]['toPage'], 0, -1, '', '', $f_links[0]['toPage'], '', '', '', $suffix);
foreach ($items["data"] as $i) {
$ret[] = $i["itemId"];
}
}
return $ret;
}
}
| lgpl-2.1 |
vrkansagara/web-doc-editor | js/ui/cmp/CheckEntitiesPrompt.js | 1124 | Ext.namespace('ui','ui.cmp');
ui.cmp.CheckEntitiesPrompt = Ext.extend(Ext.Window,
{
title : _('Check entities'),
iconCls : 'iconRun',
id : 'win-check-entities',
layout : 'fit',
width : 250,
height : 140,
resizable : false,
modal : true,
bodyStyle : 'padding:5px 5px 0; text-align: center;',
labelAlign : 'top',
closeAction: 'hide',
buttons : [{
id : 'win-check-entities-btn',
text : _('Go !'),
handler : function()
{
new ui.task.CheckEntitiesTask();
Ext.getCmp('win-check-entities').hide();
}
}],
initComponent : function()
{
Ext.apply(this,
{
items : [{
xtype : 'panel',
modal : false,
baseCls : 'x-plain',
bodyStyle : 'padding:5px 5px 0',
html : _('You\'re about to check all entities.<br><br>This action takes time.')
}]
});
ui.cmp.CheckEntitiesPrompt.superclass.initComponent.call(this);
}
}); | lgpl-2.1 |
naturalatlas/mapnik | include/mapnik/datasource.hpp | 4840 | /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_DATASOURCE_HPP
#define MAPNIK_DATASOURCE_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/params.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/query.hpp>
#include <mapnik/featureset.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/feature_style_processor_context.hpp>
#include <mapnik/datasource_geometry_type.hpp>
// stl
#include <map>
#include <string>
#include <memory>
namespace mapnik {
class MAPNIK_DECL datasource_exception : public std::exception
{
public:
datasource_exception(std::string const& message)
: message_(message)
{}
~datasource_exception() {}
virtual const char* what() const noexcept
{
return message_.c_str();
}
private:
std::string message_;
};
class MAPNIK_DECL datasource : private util::noncopyable
{
public:
enum datasource_t : std::uint8_t {
Vector,
Raster
};
datasource (parameters const& _params)
: params_(_params) {}
/*!
* @brief Get the configuration parameters of the data source.
*
* These vary depending on the type of data source.
*
* @return The configuration parameters of the data source.
*/
parameters const& params() const
{
return params_;
}
parameters & params()
{
return params_;
}
bool operator==(datasource const& rhs) const
{
return params_ == rhs.params();
}
bool operator!=(datasource const& rhs) const
{
return !(*this == rhs);
}
/*!
* @brief Get the type of the datasource
* @return The type of the datasource (Vector or Raster)
*/
virtual datasource_t type() const = 0;
virtual processor_context_ptr get_context(feature_style_context_map&) const { return processor_context_ptr(); }
virtual featureset_ptr features_with_context(query const& q, processor_context_ptr /*ctx*/) const
{
// default implementation without context use features method
return features(q);
}
virtual boost::optional<datasource_geometry_t> get_geometry_type() const = 0;
virtual featureset_ptr features(query const& q) const = 0;
virtual featureset_ptr features_at_point(coord2d const& pt, double tol = 0) const = 0;
virtual box2d<double> envelope() const = 0;
virtual layer_descriptor get_descriptor() const = 0;
virtual ~datasource() {}
protected:
parameters params_;
};
using datasource_name = const char* (*)();
using create_ds = datasource* (*) (parameters const&);
using destroy_ds = void (*) (datasource *);
class datasource_deleter
{
public:
void operator() (datasource* ds)
{
delete ds;
}
};
using datasource_ptr = std::shared_ptr<datasource>;
#ifdef MAPNIK_STATIC_PLUGINS
#define DATASOURCE_PLUGIN(classname)
#else
#define DATASOURCE_PLUGIN(classname) \
extern "C" MAPNIK_EXP const char * datasource_name() \
{ \
return classname::name(); \
} \
extern "C" MAPNIK_EXP datasource* create(parameters const& params) \
{ \
return new classname(params); \
} \
extern "C" MAPNIK_EXP void destroy(datasource *ds) \
{ \
delete ds; \
}
#endif
}
#endif // MAPNIK_DATASOURCE_HPP
| lgpl-2.1 |
mgo-tec/EasyWebSocket_SPIFFS | src/EasyWebSocket.cpp | 49026 | /*
EasyWebSocket.cpp - WebSocket for ESP-WROOM-02 ( esp8266 )
Beta version 1.48
Copyright (c) 2016 Mgo-tec
This library improvement collaborator is Mr.Visyeii.
This library is used by the Arduino IDE(Tested in ver1.6.12).
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.
Reference LGPL-2.1 license statement --> https://opensource.org/licenses/LGPL-2.1
Reference Blog --> https://www.mgo-tec.com
The esp8266 core for Arduino(Tested in ver2.3.0) --> https://github.com/esp8266/Arduino
Released under the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1
ESP8266WiFi.h - Included WiFi library for esp8266
WiFiServer.cpp - The library modification
Copyright (c) 2014 Ivan Grokhotkov.
This file is part of the esp8266 core for Arduino environment.
Released under the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1
Hash.h - Included library
Copyright (c) 2015 Markus Sattler.
This file is part of the esp8266 core for Arduino environment.
Released under the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1
FS.h(SPIFFS-File system) - Included library
-->https://github.com/esp8266/arduino-esp8266fs-plugin
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
Released under the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1
*/
#include "Arduino.h"
#include "EasyWebSocket.h"
#include "ESP8266WebServer.h"
const char* GUID_str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
WiFiClient __client;
WiFiServer server(80);
HTTPClientStatus1 _currentStatus;
uint32_t _statusChange;
EasyWebSocket::EasyWebSocket(){}
//********AP(Router) Connection****
void EasyWebSocket::AP_Connect(const char* ssid, const char* password){
Serial.begin(115200);
// Connect to WiFi network
Serial.println();
Serial.print(F("Connecting to "));
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
yield();
}
Serial.println("");
Serial.println(F("WiFi connected"));
// Start the server
_currentStatus = HC_NONE1;
server.begin();
Serial.println(F("Server started"));
// Print the IP address
Serial.println(WiFi.localIP());
delay(10);
_Upgrade_first_on = false;
}
void EasyWebSocket::SoftAP_setup(const char* ssid, const char* password){
Serial.begin(115200);
// Connect to WiFi network
Serial.println();
Serial.print(F("Connecting to "));
Serial.println(ssid);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
delay(1000);
IPAddress myIP = WiFi.softAPIP();
Serial.print(F("AP IP address: ")); Serial.println(myIP);
// Start the server
_currentStatus = HC_NONE1;
server.begin();
Serial.println(F("Server started"));
// Print the IP address
Serial.println(WiFi.localIP());
delay(10);
_Upgrade_first_on = false;
}
//*********handleClient***************
void EasyWebSocket::handleClient(){
if (_currentStatus == HC_NONE1) {
WiFiClient _local_client = server.available();
if (!_local_client) {
return;
}
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.println("New client");
#endif
__client = _local_client;
_currentStatus = HC_WAIT_READ1;
_statusChange = millis();
}
if (!__client.connected()) {
__client = WiFiClient();
_currentStatus = HC_NONE1;
return;
}
// Wait for data from client to become available
if (_currentStatus == HC_WAIT_READ1) {
if (!__client.available()) {
if (millis() - _statusChange > HTTP_MAX_DATA_WAIT) {
__client = WiFiClient();
_currentStatus = HC_NONE1;
}
yield();
return;
}
if (!__client.connected()) {
__client = WiFiClient();
_currentStatus = HC_NONE1;
return;
} else {
_currentStatus = HC_WAIT_CLOSE1;
_statusChange = millis();
return;
}
}
if (_currentStatus == HC_WAIT_CLOSE1) {
if (millis() - _statusChange > HTTP_MAX_CLOSE_WAIT) {
__client = WiFiClient();
_currentStatus = HC_NONE1;
} else {
yield();
return;
}
}
}
//********WebSocket Hand Shake ****************
void EasyWebSocket::EWS_HandShake(String res_html1, String res_html2, String res_html3, String res_html4, String res_html5, String res_html6, String res_html7){
String req;
String hash_req_key;
uint32_t LoopTime = millis();
if(!_WS_on){
handleClient();
}
if(__client){
LoopTime = millis();
while(!_WS_on){
if(millis()-LoopTime > 5000L){
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
Serial.println(F("-----------------------Received TimeOut 1"));
if(__client){
delay(10);
__client.stop();
Serial.println(F("---------------------TimeOut Client Stop 1"));
}
Serial.println(F("-----------------------The Handshake returns to the beginning 1"));
break;
}
delay(1);
switch(_Ini_html_on){
case false:
LoopTime = millis();
while(__client){
if(millis()-LoopTime > 5000L){
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
Serial.println(F("-----------------------Received TimeOut 2"));
if(__client){
delay(10);
__client.stop();
Serial.println(F("---------------------TimeOut Client Stop 2"));
}
Serial.println(F("-----------------------The Handshake returns to the beginning 2"));
break;
}
if(__client.available()){
req = __client.readStringUntil('\n');
if(req.indexOf("GET / HTTP") != -1){
Serial.println(F("-------------------HTTP Request from Browser"));
Serial.println(req);
while(req.indexOf("\r") != 0){
req = __client.readStringUntil('\n');
if(req.indexOf("Upgrade: websocket") != -1){
Serial.println(F("-------------------Connection: Upgrade HTTP Request"));
Serial.println(req);
_Ini_html_on = true;
_Upgrade_first_on = true;
EasyWebSocket::EWS_HTTP_Responce();
_PingLastTime = millis();
_PongLastTime = millis();
break;
}
if(req.indexOf("Android") != -1){
_Android_or_iPad = 'A';
}else if(req.indexOf("iPad") != -1){
_Android_or_iPad = 'i';
}else if(req.indexOf("iPhone") != -1){
_Android_or_iPad = 'P';
}
Serial.println(req);
yield();
}
req = "";
if(_Upgrade_first_on == true)break;
Serial.println(F("-------------------HTTP Response Send to Browser"));
delay(10);
__client.print(F("HTTP/1.1 200 OK\r\n"));
__client.print(F("Content-Type:text/html\r\n"));
__client.print(F("Connection:close\r\n\r\n"));
SPIFFS.begin();
File f1 = SPIFFS.open("/spiffs_01.txt", "r");
if(f1){
char c = f1.read();
char c_print_buff[256];
uint16_t index_count = 0;
c_print_buff[0] = c;
index_count++;
while(c!='\0'){
c= f1.read();
c_print_buff[index_count] = c;
if(c>0xDD) break;
index_count++;
if (index_count == 256){
__client.write((const char*)c_print_buff, 256);
Serial.print('.');
index_count = 0;
}
yield();
}
if (index_count > 0){
__client.write((const char*)c_print_buff, index_count);
index_count = 0;
}
Serial.println();
f1.close();
__client.print(res_html1);
__client.print(res_html2);
__client.print(res_html3);
__client.print(res_html4);
__client.print(res_html5);
__client.print(res_html6);
__client.print(res_html7);
}else{
f1.close();
Serial.println(F("ERROR.\r\n spiffs_01.txt file has not been uploaded to the flash in SPIFFS file system"));
__client.print(F("ERROR!!<br>spiffs_01.txt file has not been uploaded to the flash in SPIFFS file system"));
}
Serial.println(F("---------------------HTTP response complete"));
res_html1 = "";
res_html2 = "";
res_html3 = "";
res_html4 = "";
res_html5 = "";
res_html6 = "";
res_html7 = "";
__client.flush();
delay(10);
__client.stop();
delay(10);
Serial.println(F("\n--------------------GET HTTP client stop"));
req = "";
_Ini_html_on = true;
LoopTime = millis();
if(_Android_or_iPad == 'i'){
break;
}
}else if(req.indexOf("GET /favicon") != -1){
EasyWebSocket::Favicon_Response(req, 0, 1, 2);
break;
}
}
yield();
}
break;
case true:
switch(_WS_on){
case false:
EasyWebSocket::EWS_HTTP_Responce();
_PingLastTime = millis();
_PongLastTime = millis();
break;
case true:
Serial.println(F("-----------------WebSocket HandShake Complete!"));
LoopTime = millis();
break;
}
break;
}
yield();
}
}
}
//********WebSocket Hand Shake (for devided HTML header files & Auto Local IP address)****************
void EasyWebSocket::EWS_Dev_AutoLIP_HandShake_str(const char* HTML_head_file1, IPAddress res_LIP, const char* HTML_head_file2, String res_html1, String res_html2, String res_html3, String res_html4, String res_html5, String res_html6, String res_html7){
String req;
String hash_req_key;
uint32_t LoopTime = millis();
if(!_WS_on){
handleClient();
}
if(__client){
LoopTime = millis();
while(!_WS_on){
if(millis()-LoopTime > 5000L){
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
Serial.println(F("-----------------------Received TimeOut 1"));
if(__client){
delay(10);
__client.stop();
Serial.println(F("---------------------TimeOut Client Stop 1"));
}
Serial.println(F("-----------------------The Handshake returns to the beginning 1"));
break;
}
delay(1);
switch(_Ini_html_on){
case false:
LoopTime = millis();
while(__client){
if(millis()-LoopTime > 5000L){
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
Serial.println(F("-----------------------Received TimeOut 2"));
if(__client){
delay(10);
__client.stop();
Serial.println(F("---------------------TimeOut Client Stop 2"));
}
Serial.println(F("-----------------------The Handshake returns to the beginning 2"));
break;
}
if(__client.available()){
req = __client.readStringUntil('\n');
if(req.indexOf("GET / HTTP") != -1){
Serial.println(F("-------------------HTTP Request from Browser"));
Serial.println(req);
while(req.indexOf("\r") != 0){
req = __client.readStringUntil('\n');
if(req.indexOf("Upgrade: websocket") != -1){
Serial.println(F("-------------------Connection: Upgrade HTTP Request"));
Serial.println(req);
_Ini_html_on = true;
_Upgrade_first_on = true;
EasyWebSocket::EWS_HTTP_Responce();
_PingLastTime = millis();
_PongLastTime = millis();
break;
}
if(req.indexOf("Android") != -1){
_Android_or_iPad = 'A';
}else if(req.indexOf("iPad") != -1){
_Android_or_iPad = 'i';
}else if(req.indexOf("iPhone") != -1){
_Android_or_iPad = 'P';
}
Serial.println(req);
yield();
}
req = "";
if(_Upgrade_first_on == true)break;
Serial.println(F("-------------------HTTP Response Send to Browser"));
delay(10);
__client.print(F("HTTP/1.1 200 OK\r\n"));
__client.print(F("Content-Type:text/html\r\n"));
__client.print(F("Connection:close\r\n\r\n"));
SPIFFS.begin();
File HTML_head_F1 = SPIFFS.open(HTML_head_file1, "r");
if (HTML_head_F1 == NULL) {
Serial.printf("%s File not found\n",HTML_head_file1);
__client.print(F("ERROR!!<br>"));
__client.print(F("HTML_head file has not been uploaded to the flash in SD card"));
return;
}else{
Serial.printf("%s File found. OK!\n",HTML_head_file1);
}
File HTML_head_F2 = SPIFFS.open(HTML_head_file2, "r");
if (HTML_head_F2 == NULL) {
Serial.printf("%s File not found\n",HTML_head_file2);
__client.print(F("ERROR!!<br>"));
__client.print(F("HTML_head file has not been uploaded to the flash in SD card"));
return;
}else{
Serial.printf("%s File found. OK!\n",HTML_head_file2);
}
size_t totalSizeH1 = HTML_head_F1.size();
size_t totalSizeH2 = HTML_head_F2.size();
__client.write(HTML_head_F1, HTTP_DOWNLOAD_UNIT_SIZE);
__client.print(res_LIP);
__client.write(HTML_head_F2, HTTP_DOWNLOAD_UNIT_SIZE);
__client.print(res_html1);
__client.print(res_html2);
__client.print(res_html3);
__client.print(res_html4);
__client.print(res_html5);
__client.print(res_html6);
__client.print(res_html7);
HTML_head_F1.close();
HTML_head_F2.close();
Serial.println(F("---------------------HTTP response complete"));
__client.flush();
delay(5);
__client.stop();
delay(5);
Serial.println(F("\n--------------------GET HTTP client stop"));
req = "";
_Ini_html_on = true;
LoopTime = millis();
if(_Android_or_iPad == 'i'){
break;
}
}else if(req.indexOf("GET /favicon") != -1){
EasyWebSocket::Favicon_Response(req, 0, 1, 2);
break;
}
}
yield();
}
break;
case true:
switch(_WS_on){
case false:
EasyWebSocket::EWS_HTTP_Responce();
_PingLastTime = millis();
_PongLastTime = millis();
break;
case true:
Serial.println(F("-----------------WebSocket HandShake Complete!"));
LoopTime = millis();
break;
}
break;
}
yield();
}
}
}
//************HTTP Response**************************
void EasyWebSocket::EWS_HTTP_Responce(){
String req;
String hash_req_key;
uint32_t LoopTime = millis();
if(_Upgrade_first_on != true){
handleClient();
}
while(__client){
if(millis()-LoopTime > 5000L){
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
Serial.println(F("-----------------------Received TimeOut 3"));
if(__client){
delay(10);
__client.stop();
Serial.println(F("---------------------TimeOut Client Stop 3"));
}
Serial.println(F("-----------------------The Handshake returns to the beginning 3"));
break;
}
if(__client.available()){
req = __client.readStringUntil('\n');
Serial.println(req);
if (_Upgrade_first_on == true || req.indexOf("Upgrade: websocket") != -1){
Serial.println(F("---------------------Websocket Requests received"));
Serial.println(req);
while(req.indexOf("\r") != 0){
req = __client.readStringUntil('\n');
Serial.println(req);
if(req.indexOf("Sec-WebSocket-Key")>=0){
hash_req_key = req.substring(req.indexOf(':')+2,req.indexOf('\r'));
Serial.println();
Serial.print(F("hash_req_key ="));
Serial.println(hash_req_key);
}
yield();
}
delay(10);
req ="";
char h_resp_key[29];
EasyWebSocket::Hash_Key(hash_req_key, h_resp_key);
Serial.print(F("h_resp_key = "));
Serial.println(h_resp_key);
String str;
str = "HTTP/1.1 101 Switching Protocols\r\n";
str += "Upgrade: websocket\r\n";
str += "Connection: Upgrade\r\n";
str += "Sec-WebSocket-Accept: ";
for(uint8_t i=0; i<28; i++){
str += h_resp_key[i];
}
str += "\r\n\r\n";
Serial.println(F("\n--------------------WebSocket HTTP Response Send"));
Serial.println(str);
__client.print(str);
str = "";
_WS_on = true;
Serial.println(F("-------------------WebSocket Response Complete!"));
break;
}else if(req.indexOf("favicon") != -1){
EasyWebSocket::Favicon_Response(req, 0, 0, 0);
LoopTime = millis();
}else if(req.indexOf("apple-touch-icon") != -1){
Serial.println();
Serial.println(F("---------------------GET apple-touch-icon Request"));
Serial.print(req);
while(__client.available()){
Serial.write(__client.read());
yield();
}
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println();
Serial.println(F("---------------------apple-touch-icon_Client Stop"));
LoopTime = millis();
}
}
yield();
}
}
//************Hash sha1 base64 encord**************************
void EasyWebSocket::Hash_Key(String h_req_key, char* h_resp_key){
char Base64[65] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
'='
};
uint8_t hash_six[27];
uint8_t dummy_h1, dummy_h2;
uint8_t bb;
uint8_t i, j;
i=0;
j=0;
String merge_str;
merge_str = h_req_key + String(GUID_str);
Serial.println(F("--------------------Hash key Generation"));
Serial.print(F("merge_str ="));
Serial.println(merge_str);
Serial.print(F("SHA1:"));
Serial.println(sha1(merge_str));
uint8_t hash[20];
sha1(merge_str, &hash[0]);
for( i = 0; i < 20; i++) {
hash_six[j] = hash[i]>>2;
hash_six[j+1] = hash[i+1] >> 4;
bitWrite(hash_six[j+1], 4, bitRead(hash[i],0));
bitWrite(hash_six[j+1], 5, bitRead(hash[i],1));
if(j+2 < 26){
hash_six[j+2] = hash[i+2] >> 6;
bitWrite(hash_six[j+2], 2, bitRead(hash[i+1],0));
bitWrite(hash_six[j+2], 3, bitRead(hash[i+1],1));
bitWrite(hash_six[j+2], 4, bitRead(hash[i+1],2));
bitWrite(hash_six[j+2], 5, bitRead(hash[i+1],3));
}else if(j+2 == 26){
dummy_h1 = 0;
dummy_h2 = 0;
dummy_h2 = hash[i+1] << 4;
dummy_h2 = dummy_h2 >>2;
hash_six[j+2] = dummy_h1 | dummy_h2;
}
if( j+3 < 27 ){
hash_six[j+3] = hash[i+2];
bitWrite(hash_six[j+3], 6, 0);
bitWrite(hash_six[j+3], 7, 0);
}else if(j+3 == 27){
hash_six[j+3] = '=';
}
h_resp_key[j] = Base64[hash_six[j]];
h_resp_key[j+1] = Base64[hash_six[j+1]];
h_resp_key[j+2] = Base64[hash_six[j+2]];
if(j+3==27){
h_resp_key[j+3] = Base64[64];
break;
}else{
h_resp_key[j+3] = Base64[hash_six[j+3]];
}
i = i + 2;
j = j + 4;
}
h_resp_key[28] = '\0';
Serial.print(F("hash_six = "));
for(i=0; i<28; i++){
Serial.print(hash_six[i],BIN);
Serial.print('_');
}
Serial.println();
}
void EasyWebSocket::EWS_ESP8266_Str_SEND(String str, String id)
{
str += '|' + id + '|';
__client.write(B10000001);
__client.write(str.length());
__client.print(str);
}
//***********************************************************************
String EasyWebSocket::EWS_ESP8266CharReceive(uint16_t pTime){
uint8_t b=0;
uint8_t data_len;
uint8_t mask[4];
uint8_t i;
String str_close = "_close";
if(_WS_on){
if(pTime > 0){
if(millis()-_PingLastTime > pTime){
EasyWebSocket::EWS_PING_SEND();
_PingLastTime = millis();
}
if((millis() - _PongLastTime) > (pTime + 500)){
if(__client){
if(__client.available()){
Serial.println("client.available --- client.stop");
char ccc;
while(__client.available()){
ccc = __client.read();
Serial.print(ccc);
yield();
}
}else{
Serial.println("Client Not available.");
}
}else{
Serial.println("Client No Handle.");
}
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println();
Serial.println(F("-----------------Ping Non-Response Client.STOP"));
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
_currentStatus = HC_NONE1; //Added 2016.12.06
return str_close;
}
}
}
if(__client.available()){
b = __client.read();
if(b == B10000001 || b == B10001010){
switch (b){
case B10000001:
_PingLastTime = millis();
_PongLastTime = millis();
break;
case B10001010:
_PongLastTime = millis();
Serial.println(F("Pong Receive**********"));
break;
}
b = __client.read();
data_len = b - B10000000;
for(i=0; i<4; i++){
mask[i] = __client.read();
}
uint8_t m_data[data_len];
char data_c[data_len + 1];
for(i = 0; i<data_len; i++){
m_data[i] = __client.read();
data_c[i] = mask[i%4]^m_data[i];
yield();
}
data_c[data_len] = '\0';
return String(data_c);
}else if(b == B10001000){
Serial.println(F("------------------Close Command Received"));
b = __client.read();
Serial.println(b,BIN);
data_len = b - B10000000;
if(data_len == 0){
while(__client.available()){
b = __client.read();
yield();
}
Serial.println("Closing HandShake OK!");
}else{
for(i=0; i<4; i++){
mask[i] = __client.read();
}
uint8_t m_data2[data_len];
char data_c2[data_len + 1];
for(i = 0; i<data_len; i++){
m_data2[i] = __client.read();
data_c2[i] = mask[i%4]^m_data2[i];
// Serial.println(data_c2[i],BIN);
}
data_c2[data_len] = '\0';
Serial.print(F("Closing Message CODE( from client ) = "));
uint16_t closing_code = data_c2[0]<<8 | data_c2[1];
Serial.println(closing_code);
Serial.print(F("Closing Message = "));
if(data_len > 2){
for(int i=2; i<data_len; i++){
if((data_c2[i]>=0x20) && (data_c2[i]<=0x7E)){
Serial.write(data_c2[i]);
}else{
Serial.print(data_c2[i],HEX);
Serial.print(',');
}
}
}else{
Serial.print(F("Non"));
}
Serial.println();
}
delay(1);
__client.write(B10001000);
delay(1);
Serial.println(F("------------------Close Command Send"));
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println();
Serial.println(F("------------------Client.STOP"));
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
if(__client){
Serial.println(F("Client = true."));
while(__client){
if(__client.available()){
String req = __client.readStringUntil('\n');
Serial.println(req);
if(req.indexOf("GET /favicon") != -1){
Favicon_Response(req, 0, 0, 0);
break;
}
}
yield();
}
}else{
Serial.println(F("Client = false."));
}
return str_close;
}
}else{
return String('\0');
}
}
//********************************************************
String EasyWebSocket::EWS_ESP8266_Binary_Receive(){
uint8_t b=0;
uint8_t data_len;
uint8_t mask[4];
uint16_t i;
uint32_t iii;
String str_close = "_close";
if(__client.available()){
b = __client.read();
if(b == B10000001 || b == B10000010 || b == B10001010){
//B10000001 Text frame
//B10000010 Binary frame
//B10001010 Pong frame
switch (b){
case B10000001:
Serial.println("WebSocket Text Receive*********");
_PingLastTime = millis();
_PongLastTime = millis();
break;
case B10000010:
Serial.println("WebSocket Binary Receive*********");
_PingLastTime = millis();
_PongLastTime = millis();
break;
case B10001010:
_PongLastTime = millis();
Serial.println(F("Pong Receive**********"));
break;
}
b = __client.read();
if(b >= B10000000){
Serial.println("Mask Bit Received--------");
}else{
Serial.println("UnMask Bit Received-------");
}
data_len = b - B10000000;
Serial.print("data_len =" );
Serial.println(data_len);
uint8_t data_ext_len[8];
uint16_t data_len16 = 0;
uint32_t data_len32 = 0;
if(data_len == 126){
__client.read(data_ext_len, 2);
data_len16 = data_ext_len[0]<<8 | data_ext_len[1];
Serial.print("data_len16 =" );
Serial.println(data_len16);
}else if(data_len ==127){
__client.read(data_ext_len, 8);
Serial.println("data_ext_len[i]-----------");
for(i=0;i<8;i++){
Serial.println(data_ext_len[i]);
}
for(i=4; i<8; i++){
data_len32 = data_ext_len[i]<<(8*(7-i)) | data_len32;
}
//data_len32 = data_ext_len[0]<<56 | data_ext_len[1]<<48 | data_ext_len[2]<<40 | data_ext_len[3]<<32 | data_ext_len[4]<<24 | data_ext_len[5]<<16 | data_ext_len[6]<<8 | data_ext_len[7];
if(data_len32 >= 0xffffffff){
Serial.print("data_len32 overload!----------");
}else{
Serial.print("data_len32 =" );
Serial.print(data_len32); //シリアルでは64bitはオーバーロードしてしまうので注意
Serial.println();
}
}
for(i=0; i<4; i++){
mask[i] = __client.read();
}
uint32_t Max_len;
if(data_len32 > 0){
Max_len = data_len32;
}else if(data_len16>0){
Max_len = data_len16;
}else{
Max_len = data_len;
}
/*
uint8_t m_data[Max_len];
uint8_t data_b[Max_len + 1];
for(i = 0; i<Max_len; i++){
m_data[i] = __client.read();
data_b[i] = mask[i%4]^m_data[i];
}
*/
uint8_t mbit;
for(iii = 0; iii<Max_len; iii++){
mbit = mask[iii%4]^__client.read();
if(iii>(Max_len-5)){
if((iii % 16) == 0){
Serial.printf("%02x", mbit);
}else if((iii % 16) == 15){
Serial.printf(" %02x\n", mbit);
}else{
Serial.printf(" %02x", mbit);
}
}
}
Serial.print("\ni max = ");
Serial.println(iii);
return "Websocket Binary Receive Comprete !";
}else if(b == B10001000){
Serial.println(F("------------------Close Command Received"));
b = __client.read();
Serial.println(b,BIN);
data_len = b - B10000000;
if(data_len == 0){
while(__client.available()){
b = __client.read();
yield();
}
Serial.println("Closing HandShake OK!");
}else{
for(i=0; i<4; i++){
mask[i] = __client.read();
}
uint8_t m_data2[data_len];
char data_c2[data_len + 1];
for(i = 0; i<data_len; i++){
m_data2[i] = __client.read();
data_c2[i] = mask[i%4]^m_data2[i];
// Serial.println(data_c2[i],BIN);
}
data_c2[data_len] = '\0';
// Serial.println(data_c2);
Serial.println("Closing Message ??");
}
delay(1);
__client.write(B10001000);
delay(1);
Serial.println(F("------------------Close Command Send"));
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println();
Serial.println(F("------------------Client.STOP"));
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
while(__client){
if(__client.available()){
String req = __client.readStringUntil('\n');
Serial.println(req);
if(req.indexOf("GET /favicon") != -1){
EasyWebSocket::Favicon_Response(req, 0, 0, 0);
break;
}
}
yield();
}
return str_close;
}
}else{
return String('\0');
}
}
void EasyWebSocket::EWS_PING_SEND(){
__client.write(B10001001);
__client.write(4);
__client.print(F("Ping"));
Serial.println();
Serial.println(F("Ping Send-----------"));
}
String EasyWebSocket::EWS_Body_style(String text_color, String bg_color){
String str;
str = "<body style='color:";
str += text_color;
str += "; background:";
str += bg_color;
str += ";'>\r\n";
return str;
}
String EasyWebSocket::EWS_OnOff_Button(String button_id, uint16_t width, uint16_t height, uint8_t font_size, String f_color, String b_color){
String str;
str = "<input type='button' value='OFF' onClick=\"OnOffBt(this,'";
str += button_id;
str += "');\"";
str += " style='width:";
str += String(width);
str += "px; ";
str += "height:";
str += String(height);
str += "px; font-size:";
str += String(font_size);
str += "px; color:";
str += f_color;
str += "; background-color:";
str += b_color;
str += ";' >\r\n";
return str;
}
String EasyWebSocket::EWS_On_Momentary_Button(String button_id, String text, uint16_t width, uint16_t height, uint8_t font_size, String f_color, String b_color){
String str;
str = "<input type='button' value='";
str += text;
str += "' onClick=\"doSend(100,'";
str += button_id;
str += "'); data_tmp = 0;\"";
str += " style='width:";
str += String(width);
str += "px; ";
str += "height:";
str += String(height);
str += "px; font-size:";
str += String(font_size);
str += "px; color:";
str += f_color;
str += "; background-color:";
str += b_color;
str += ";' >\r\n";
return str;
}
String EasyWebSocket::EWS_Touch_Slider_BT(String slider_id, String vbox_id){
String str;
str += "<input type='range' ontouchmove=\"doSend(this.value,'";
str += slider_id;
str += "'); document.getElementById('";
str += vbox_id;
str += "').value=this.value;\">\r\n";
return str;
}
String EasyWebSocket::EWS_Touch_Slider_T(String slider_id, String txt_id){
String str;
str += "<input type='range' ontouchmove=\"doSend(this.value,'";
str += slider_id;
str += "'); document.getElementById('";
str += txt_id;
str += "').innerHTML=this.value;\">\r\n";
return str;
}
String EasyWebSocket::EWS_Mouse_Slider_BT(String slider_id, String vbox_id){
String str;
str += "<input type='range' onMousemove=\"doSend(this.value,'";
str += slider_id;
str += "'); document.getElementById('";
str += vbox_id;
str += "').value=this.value;\">\r\n";
return str;
}
String EasyWebSocket::EWS_Mouse_Slider_T(String slider_id, String txt_id){
String str;
str += "<input type='range' onMousemove=\"doSend(this.value,'";
str += slider_id;
str += "'); document.getElementById('";
str += txt_id;
str += "').innerHTML=this.value;\">\r\n";
return str;
}
String EasyWebSocket::EWS_Sl_BoxText(String vbox_id, uint16_t width, uint16_t height, uint8_t font_size, String color){
String str;
str = "<input type='number' id='";
str += vbox_id;
str += "' style='width:";
str += String(width);
str += "px; ";
str += "height:";
str += String(height);
str += "px; font-size:";
str += String(font_size);
str += "px; color:";
str += String(color);
str += ";' >\r\n";
return str;
}
String EasyWebSocket::EWS_Sl_Text(String text_id, uint8_t font_size, String color){
String str;
str = "<span id='";
str += text_id;
str += "' style='font-size:";
str += String(font_size);
str += "px; color:";
str += String(color);
str += ";' ></span>\r\n";
return str;
}
String EasyWebSocket::EWS_BrowserReceiveTextTag(String id, uint8_t font_size, String fnt_col){
String str;
str = "<span id='" + id;
str += "' style='font-size:";
str += String(font_size);
str += "px; color:" + fnt_col + ";'></span>\r\n";
return str;
}
String EasyWebSocket::EWS_BrowserReceiveTextTag2(String id, String name, String b_color, uint8_t font_size, String fnt_col){
String str;
str = "<fieldset style='border-style: solid; border-color:";
str += b_color;
str += ";'>\r\n";
str += "<legend style='font-style: italic; color:";
str += b_color;
str += ";'>\r\n";
str += name;
str += "</legend><span id='";
str += id;
str += "' style='font-size:";
str += String(font_size);
str += "px; color:" + fnt_col + ";'></span></fieldset>\r\n";
return str;
}
String EasyWebSocket::EWS_Close_Button(String name, uint16_t width, uint16_t height, uint8_t font_size){
String str;
str = "<input type='button' value='";
str += name;
str += "' style='width:";
str += String(width);
str += "px; ";
str += "height:";
str += String(height);
str += "px; font-size:";
str += String(font_size);
str += "px;' onclick='WS_close()'>\r\n";
return str;
}
String EasyWebSocket::EWS_Close_Button2(String name, String BG_col, uint16_t width, uint16_t height, String font_col, uint8_t font_size){
String str;
str = "<input type='button' value='";
str += name;
str += "' style='background-color:";
str += BG_col;
str += "; width:";
str += String(width);
str += "px; height:";
str += String(height);
str += "px; color:";
str += font_col;
str += "; font-size:";
str += String(font_size);
str += "px; border-radius:10px;' onclick='WS_close()'>\r\n";
return str;
}
String EasyWebSocket::EWS_Window_ReLoad_Button(String name, uint16_t width, uint16_t height, uint8_t font_size){
String str;
str = "<input type='button' value='";
str += name;
str += "' style='width:";
str += String(width);
str += "px; ";
str += "height:";
str += String(height);
str += "px; font-size:";
str += String(font_size);
str += "px;' onclick='window.location.reload()'>\r\n";
return str;
}
String EasyWebSocket::EWS_Window_ReLoad_Button2(String name, String BG_col, uint16_t width, uint16_t height, String font_col, uint8_t font_size){
String str;
str = "<input type='button' value='";
str += name;
str += "' style='background-color:";
str += BG_col;
str += "; width:";
str += String(width);
str += "px; height:";
str += String(height);
str += "px; color:";
str += font_col;
str += "; font-size:";
str += String(font_size);
str += "px; border-radius:10px;' onclick='window.location.reload()'>\r\n";
return str;
}
String EasyWebSocket::EWS_WebSocket_Reconnection_Button(String name, uint16_t width, uint16_t height, uint8_t font_size){
String str;
str = "<input type='button' value='";
str += name;
str += "' style='width:";
str += String(width);
str += "px; ";
str += "height:";
str += String(height);
str += "px; font-size:";
str += String(font_size);
str += "px;' onclick='init();'>\r\n";
return str;
}
String EasyWebSocket::EWS_WebSocket_Reconnection_Button2(String name, String BG_col, uint16_t width, uint16_t height, String font_col, uint8_t font_size){
String str;
str = "<input type='button' value='";
str += name;
str += "' style='background-color:";
str += BG_col;
str += "; width:";
str += String(width);
str += "px; height:";
str += String(height);
str += "px; color:";
str += font_col;
str += "; font-size:";
str += String(font_size);
str += "px; border-radius:10px;' onclick='init();'>\r\n";
return str;
}
String EasyWebSocket::EWS_BrowserSendRate(){
String str;
str += "<form name='fRate'>\r\n";
str += " <select id='selRate'>\r\n";
str += " <option value=0>0ms</option>\r\n";
str += " <option value=5>5ms</option>\r\n";
str += " <option value=10>10ms</option>\r\n";
str += " <option value=15>15ms</option>\r\n";
str += " <option value=20>20ms</option>\r\n";
str += " <option value=25>25ms</option>\r\n";
str += " <option value=30>30ms</option>\r\n";
str += " <option value=35>35ms</option>\r\n";
str += " <option value=40>40ms</option>\r\n";
str += " <option value=45>45ms</option>\r\n";
str += " <option value=50>50ms</option>\r\n";
str += " </select>\r\n";
str += " <input type='button' value='Rate Exec' onclick='onButtonRate();' />\r\n";
str += " Transfer Rate= <span id='RateTxt'>0</span>ms\r\n";
str += "</form>\r\n";
return str;
}
String EasyWebSocket::EWS_Status_Text(uint8_t font_size, String color){
String str;
str = "<span id='__wsStatus__' style='font-size:";
str += String(font_size);
str += "px; color:";
str += String(color);
str += ";' ></span>\r\n";
return str;
}
String EasyWebSocket::EWS_Status_Text2(String name, String b_color, uint8_t font_size, String f_color){
String str;
str = "<fieldset style='border-style: solid; border-color:";
str += b_color;
str += ";'>\r\n";
str += "<legend style='font-style: italic; color:";
str += b_color;
str += ";'>\r\n";
str += name;
str += "</legend><span id='__wsStatus__' style='font-size:";
str += String(font_size);
str += "px; color:";
str += f_color;
str += ";' ></span></fieldset>\r\n";
return str;
}
String EasyWebSocket::EWS_Canvas_Slider_T(String slider_id, uint16_t width, uint16_t height, String frame_col, String fill_col){
String str;
str = "<canvas id='" + slider_id + "' width='" + String(width) + "' height='" + String(height) + "'></canvas>\r\n";
str += "<script type='text/javascript'>\r\n";
str += " fnc_" + slider_id + "();\r\n";
str += " function fnc_" + slider_id + "(){\r\n";
str += " var c_w = " + String(width) + ";\r\n";
str += " var c_h = " + String(height) + ";\r\n";
str += " var line_width = 5;\r\n";
str += " var canvas2 = document.getElementById('" + slider_id + "');\r\n";
str += " var ctx2 = canvas2.getContext('2d');\r\n";
str += " ctx2.clearRect(0, 0, c_w, c_h);\r\n";
str += " ctx2.beginPath();\r\n";
str += " ctx2.lineWidth = line_width;\r\n";
str += " ctx2.strokeStyle = '" + frame_col + "';\r\n";
str += " ctx2.strokeRect(0,0,c_w,c_h);\r\n";
str += " canvas2.addEventListener('touchmove', slider_" + slider_id + ", false);\r\n";
str += " canvas2.addEventListener('touchstart', slider_" + slider_id + ", false);\r\n";
str += " function slider_" + slider_id + "(event3) {\r\n";
str += " event3.preventDefault();\r\n";
str += " event3.stopPropagation();\r\n";
str += " var evt555=event3.touches[0];\r\n";
str += " var OffSet2 = evt555.target.getBoundingClientRect();\r\n";
str += " var ex = evt555.clientX - OffSet2.left;\r\n";
str += " if( ex < 0 ){ex = 0;}\r\n";
str += " else if(ex>c_w){ex = c_w;}\r\n";
str += " var e_cl_X = Math.floor(ex);\r\n";
str += " ctx2.clearRect(0, 0, c_w, c_h);\r\n";
str += " ctx2.beginPath();\r\n";
str += " ctx2.fillStyle = '" + fill_col + "';\r\n";
str += " ctx2.rect(0,0, e_cl_X, c_h);\r\n";
str += " ctx2.fill();\r\n";
str += " ctx2.beginPath();\r\n";
str += " ctx2.lineWidth = line_width;\r\n";
str += " ctx2.strokeStyle = '" + frame_col + "';\r\n";
str += " ctx2.strokeRect(0,0,c_w,c_h);\r\n";
str += " doSend(String(e_cl_X), '" + slider_id + "');\r\n";
str += " };\r\n";
str += " };\r\n";
str += "</script>\r\n";
return str;
}
String EasyWebSocket::EWS_TextBox_Send(String id, String txt, String BT_txt){
String str;
str = "<form>\r\n";
str += "<input type='text' id='" + id + "' value='" + txt + "'>\r\n";
str += "<input type='button' value='" + BT_txt + "' onclick='doSend_TextBox(\"" + id + "\");'>\r\n";
str += "</form>\r\n";
return str;
}
String EasyWebSocket::EWS_Web_Get(char* host, String target_ip, uint8_t char_tag, String Final_tag, String Begin_tag, String End_tag, String Paragraph){
String str1;
String str2;
String str3;
String ret_str = "";
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println(F("--------------------WebSocket Client Stop"));
if (__client.connect(host, 80)) {
Serial.print(host); Serial.print(F("-------------"));
Serial.println(F("connected"));
Serial.println(F("--------------------WEB HTTP GET Request"));
str1 = "GET " + target_ip + " HTTP/1.1\r\n" + "Host: " + String(host)+"\r\n";
char cstr1[str1.length()+1];
str1.toCharArray(cstr1, str1.length()+1);
const char* cstr2 = "Content-Type: text/html; charset=UTF-8\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nContent-Language: ja\r\nAccept-Language: ja\r\nAccept-Charset: UTF-8\r\nConnection: close\r\n\r\n";
__client.write((const char*)cstr1, str1.length());
__client.write((const char*)cstr2, strlen(cstr2));
Serial.println(str1);
}else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
String dummy_str;
uint16_t from, to;
if(__client){
Serial.println(F("--------------------WEB HTTP Response"));
while(__client.connected()){
while (__client.available()) {
if(dummy_str.indexOf(Final_tag) < 0){
dummy_str = __client.readStringUntil(char_tag);
if(dummy_str.indexOf(Begin_tag) != -1){
from = dummy_str.indexOf(Begin_tag) + Begin_tag.length();
to = dummy_str.indexOf(End_tag);
ret_str += Paragraph;
ret_str += dummy_str.substring(from,to);
ret_str += " ";
}
dummy_str = "";
}else{
break;
}
yield();
}
yield();
}
}
ret_str += "\0";
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println(F("--------------------Client Stop"));
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
return ret_str;
}
void EasyWebSocket::EWS_Web_Get2(char* host, String target_ip, uint8_t char_tag, String Final_tag, String Begin_tag, String End_tag, String Paragraph, char RetChar[][500], uint8_t* RetCharCount){
String str1;
String str2;
String str3;
String ret_str = "";
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println(F("--------------------WebSocket Client Stop"));
if (__client.connect(host, 80)) {
Serial.print(host); Serial.print(F("-------------"));
Serial.println(F("connected"));
Serial.println(F("--------------------WEB HTTP GET Request"));
str1 = "GET " + target_ip + " HTTP/1.1\r\n" + "Host: " + String(host)+"\r\n";
char cstr1[str1.length()+1];
str1.toCharArray(cstr1, str1.length()+1);
const char* cstr2 = "Content-Type: text/html; charset=UTF-8\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nContent-Language: ja\r\nAccept-Language: ja\r\nAccept-Charset: UTF-8\r\nConnection: close\r\n\r\n\0";
__client.write((const char*)cstr1, str1.length());
__client.write((const char*)cstr2, strlen(cstr2));
Serial.println(str1);
}else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
String dummy_str;
uint16_t from, to;
uint8_t c_cnt = 0;
uint16_t i=0;
char c;
if(__client){
Serial.println(F("--------------------WEB HTTP Response"));
while(__client.connected()){
while (__client.available()) {
if(dummy_str.indexOf(Final_tag) < 0){
dummy_str = __client.readStringUntil(char_tag);
dummy_str += "\0";
if(dummy_str.indexOf(Begin_tag) >= 0){
Serial.print("Begin tag in-------------RetCharCount=");Serial.println(c_cnt);
i = 0;
while(i<499){
c = __client.read();
if(c == '\n' || c == '<' || c >= 0xF0 || c < 0x20 || c == '\0') break;
Serial.print(c);
RetChar[c_cnt][i] = c;
i++;
yield();
}
RetChar[c_cnt][i] = '\0';
Serial.println();
Serial.print("RetChar--------------------------");Serial.println(i);
c_cnt++;
if(c_cnt>2){
while(__client.available()){
__client.read();
yield();
}
}
}
dummy_str = "";
}else{
break;
}
yield();
}
yield();
}
}
*RetCharCount = c_cnt;
ret_str = "";
delay(10);
__client.stop();
delay(10);
__client.flush();
Serial.println(F("--------------------Client Stop"));
_WS_on = false;
_Ini_html_on = false;
_Upgrade_first_on = false;
}
//**************************************************************
void EasyWebSocket::Favicon_Response(String str, uint8_t ws, uint8_t ini_htm, uint8_t up_f)
{
Serial.println(F("-----------------------Favicon GET Request Received"));
Serial.println(str);
while(__client.available()){
Serial.write(__client.read());
yield();
}
delay(1);
__client.print(F("HTTP/1.1 404 Not Found\r\n"));
__client.print(F("Connection:close\r\n\r\n"));
delay(5);
__client.stop();
delay(5);
__client.flush();
Serial.println(F("-----------------Client.stop (by Favicon Request)"));
switch(ws){
case 1:
_WS_on = true;
break;
case 2:
_WS_on = false;
break;
}
switch(ini_htm){
case 1:
_Ini_html_on = true;
break;
case 2:
_Ini_html_on = false;
break;
}
switch(up_f){
case 1:
_Upgrade_first_on = true;
break;
case 2:
_Upgrade_first_on = false;
break;
}
}
//**************************************************************
String EasyWebSocket::Color_Picker(uint16_t top_px, uint16_t left_px, String default_col, String ID){
String str = "";
str += "<div style='position: relative; top:";
str += String(top_px);
str += "px; left:";
str += String(left_px);
str += "px; width:50px; height:0px'>\r\n";
str += "<input type='color' value='" + default_col + "' id='" + ID +"' ";
str += "onchange='Color_Picker_Send(100, \"" + ID + "\", this.value);'>\r\n";
str += "</div>\r\n";
return str;
}
| lgpl-2.1 |
PaperMC/PaperGradle | src/main/java/net/minecraftforge/gradle/patcher/PatcherProject.java | 12806 | /*
* A Gradle plugin for the PaperMC build process.
* Copyright (C) 2016-2018 PaperMC
*
* 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-1301
* USA
*/
package net.minecraftforge.gradle.patcher;
import com.google.common.base.Strings;
import groovy.lang.Closure;
import java.io.File;
import java.io.Serializable;
import net.minecraftforge.gradle.util.GradleConfigurationException;
import org.gradle.api.Project;
import static net.minecraftforge.gradle.patcher.PatcherConstants.DEFAULT_RES_DIR;
import static net.minecraftforge.gradle.patcher.PatcherConstants.DEFAULT_SRC_DIR;
import static net.minecraftforge.gradle.patcher.PatcherConstants.DEFAULT_TEST_RES_DIR;
import static net.minecraftforge.gradle.patcher.PatcherConstants.DEFAULT_TEST_SRC_DIR;
public class PatcherProject implements Serializable {
private static final long serialVersionUID = 1L;
private final transient Project project;
private final String name;
private final String capName;
private String patchAfter = "clean";
private String genPatchesFrom;
private File rootDir;
private File patchDir;
private File sourcesDir;
private File resourcesDir;
private File testSourcesDir;
private File testResourcesDir;
private boolean genMcpPatches = false;
private boolean applyMcpPatches = false;
private boolean s2sKeepImports = true;
PatcherProject(final String name, final PatcherPlugin plugin) {
this.name = name;
this.project = plugin.project;
rootDir = project.getProjectDir();
// make capName
final char char1 = name.charAt(0);
capName = Character.toUpperCase(char1) + name.substring(1);
}
private String getName() {
return name;
}
public String getCapName() {
return capName;
}
/**
* @return NULL if only applies to clean
*/
public String getPatchAfter() {
return patchAfter;
}
/**
* Sets the project after which this project will apply its patches.
* All patches apply on top of the clean project anyways.
*
* @param patchAfter project to patch after
*/
private void setPatchAfter(final String patchAfter) {
if (Strings.isNullOrEmpty(patchAfter)) {
this.patchAfter = "clean";
} else {
this.patchAfter = patchAfter;
}
}
/**
* Sets the project after which this project will apply its patches
* All patches apply on top of the clean project anyways.
*
* @param patcher project to patch after
*/
private void setPatchAfter(final PatcherProject patcher) {
this.patchAfter = patcher.getName();
}
/**
* Sets the project after which this project will apply its patches
* All patches apply on top of the clean project anyways.
*
* @param patchAfter project to patch after
*/
public void patchAfter(final String patchAfter) {
setPatchAfter(patchAfter);
}
/**
* Sets the project after which this project will apply its patches
* All patches apply on top of the clean project anyways.
*
* @param patcher project to patch after
*/
public void patchAfter(final PatcherProject patcher) {
setPatchAfter(patcher);
}
/**
* @return NULL to not generate patches, "clean" to generate from the clean project.
*/
public String getGenPatchesFrom() {
return genPatchesFrom;
}
/**
* The project from witch the patches for this project will be generated.
* By default, patches are not generated at all.
* To generate patches against the "clean" project, specify "clean" ast the argument.
*
* @param generateFrom Project to generate patches from
*/
private void setGenPatchesFrom(final String generateFrom) {
this.genPatchesFrom = generateFrom;
}
/**
* The project from witch the patches for this project will be generated.
* By default, patches are not generated at all.
* To generate patches against the "clean" project, specify "clean" ast the argument.
*
* @param patcher Project to generate patches from
*/
private void setGenPatchesFrom(final PatcherProject patcher) {
this.genPatchesFrom = patcher.getName();
}
/**
* The project from witch the patches for this project will be generated.
* By default, patches are not generated at all.
* To generate patches against the "clean" project, specify "clean" ast the argument.
*
* @param generateFrom Project to generate patches from
*/
public void genPatchesFrom(final String generateFrom) {
setGenPatchesFrom(generateFrom);
}
protected boolean doesGenPatches() {
return genPatchesFrom != null;
}
/**
* The project from witch the patches for this project will be generated.
* By default, patches are not generated at all.
* To generate patches against the "clean" project, specify "clean" ast the argument.
*
* @param patcher Project to generate patches from
*/
public void generateFrom(final PatcherProject patcher) {
setGenPatchesFrom(patcher);
}
private File getRootDir() {
return rootDir;
}
/**
* The root directory of the project. This may or may not be actually used depending on the other directories.
*
* @param rootDir root directory of the project
*/
private void setRootDir(final Object rootDir) {
this.rootDir = project.file(rootDir);
}
/**
* The root directory of the project. This may or may not be actually used depending on the other directories.
*
* @param rootDir root directory of the project
*/
public void rootDir(final Object rootDir) {
setRootDir(rootDir);
}
private File getPatchDir() {
return patchDir;
}
/**
* The directory where the patches are found, and to whitch generated patches should be saved.
* By default this is rootDir/patches
*
* @param patchDir patch directory of the project
*/
private void setPatchDir(final Object patchDir) {
this.patchDir = project.file(patchDir);
}
/**
* The directory where the patches are found, and to witch generated patches should be saved.
* By default this is rootDir/patches
*
* @param patchDir patch directory of the project
*/
public void patchDir(final Object patchDir) {
setPatchDir(patchDir);
}
private File getSourcesDir() {
return getFile(sourcesDir, DEFAULT_SRC_DIR);
}
/**
* The directory where the non-patch sources for this project are.
* By default this is rootDir/src/main/java
*
* @param sourcesDir non-MC source directory of the project
*/
private void setSourcesDir(final Object sourcesDir) {
this.sourcesDir = project.file(sourcesDir);
}
/**
* The directory where the non-patch sources for this project are.
* By default this is rootDir/src/main/java
*
* @param sourcesDir non-MC source directory of the project
*/
public void sourcesDir(final Object sourcesDir) {
setSourcesDir(sourcesDir);
}
private File getResourcesDir() {
return getFile(resourcesDir, DEFAULT_RES_DIR);
}
/**
* The directory where the non-patch resources for this project are.
* By default this is rootDir/src/main/resources
*
* @param resourcesDir non-MC resource directory of the project
*/
private void setResourcesDir(final Object resourcesDir) {
this.resourcesDir = project.file(resourcesDir);
}
/**
* The directory where the non-patch resources for this project are.
* By default this is rootDir/src/main/resources
*
* @param resourcesDir non-MC resource directory of the project
*/
public void resourcesDir(final Object resourcesDir) {
setResourcesDir(resourcesDir);
}
private File getTestSourcesDir() {
return getFile(testSourcesDir, DEFAULT_TEST_SRC_DIR);
}
/**
* The directory where the test sourcess for this project are.
* By default this is rootDir/src/test/sources
*
* @param testSourcesDir test source directory of the project
*/
public void setTestSourcesDir(final Object testSourcesDir) {
this.testSourcesDir = project.file(testSourcesDir);
}
/**
* The directory where the test sourcess for this project are.
* By default this is rootDir/src/test/sources
*
* @param testSourcesDir test source directory of the project
*/
public void testSourcesDir(final Object testSourcesDir) {
setSourcesDir(testSourcesDir);
}
private File getTestResourcesDir() {
return getFile(testResourcesDir, DEFAULT_TEST_RES_DIR);
}
/**
* The directory where the non-patch resources for this project are.
* By default this is rootDir/src/test/resources
*
* @param testResourcesDir test resource directory of the project
*/
private void setTestResourcesDir(final Object testResourcesDir) {
this.testResourcesDir = project.file(testResourcesDir);
}
/**
* The directory where the non-patch resources for this project are.
* By default this is rootDir/src/test/resources
*
* @param testResourcesDir test resource directory of the project
*/
public void testResourcesDir(final Object testResourcesDir) {
setTestResourcesDir(testResourcesDir);
}
// ------------------------
// HELPERS
// ------------------------
/**
* Validates the object to ensure its been configured correctly and isnt missing something.
*/
protected void validate() {
if (rootDir == null) {
throw new GradleConfigurationException("PatchDir not specified for project '" + name + "'");
}
}
private File getFile(final File field, final String defaultPath) {
if (field == null && rootDir != null) {
return new File(getRootDir(), defaultPath);
} else {
return field;
}
}
public boolean isGenMcpPatches() {
return genMcpPatches;
}
public void setGenMcpPatches(final boolean genMcpPatches) {
this.genMcpPatches = genMcpPatches;
}
public boolean isApplyMcpPatches() {
return applyMcpPatches;
}
public void setApplyMcpPatches(final boolean applyMcpPatches) {
this.applyMcpPatches = applyMcpPatches;
}
public boolean isS2sKeepImports() {
return s2sKeepImports;
}
public void setS2sKeepImports(final boolean value) {
this.s2sKeepImports = value;
}
// ------------------------
// DELAYED GETTERS
// ------------------------
@SuppressWarnings("serial")
protected Closure<File> getDelayedSourcesDir() {
return new Closure<File>(PatcherProject.class) {
public File call() {
return getSourcesDir();
}
};
}
@SuppressWarnings("serial")
protected Closure<File> getDelayedResourcesDir() {
return new Closure<File>(PatcherProject.class) {
public File call() {
return getResourcesDir();
}
};
}
@SuppressWarnings("serial")
protected Closure<File> getDelayedTestSourcesDir() {
return new Closure<File>(PatcherProject.class) {
public File call() {
return getTestSourcesDir();
}
};
}
@SuppressWarnings("serial")
protected Closure<File> getDelayedTestResourcesDir() {
return new Closure<File>(PatcherProject.class) {
public File call() {
return getTestResourcesDir();
}
};
}
@SuppressWarnings("serial")
protected Closure<File> getDelayedPatchDir() {
return new Closure<File>(PatcherProject.class) {
public File call() {
return getPatchDir();
}
};
}
}
| lgpl-2.1 |
jochenvdv/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.java | 7407 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.TokenUtils;
/**
* Checks for multiple occurrences of the same string literal within a
* single file.
*
* @author Daniel Grenner
*/
@FileStatefulCheck
public class MultipleStringLiteralsCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "multiple.string.literal";
/**
* The found strings and their positions.
* {@code <String, ArrayList>}, with the ArrayList containing StringInfo
* objects.
*/
private final Map<String, List<StringInfo>> stringMap = new HashMap<>();
/**
* Marks the TokenTypes where duplicate strings should be ignored.
*/
private final BitSet ignoreOccurrenceContext = new BitSet();
/**
* The allowed number of string duplicates in a file before an error is
* generated.
*/
private int allowedDuplicates = 1;
/**
* Pattern for matching ignored strings.
*/
private Pattern ignoreStringsRegexp;
/**
* Construct an instance with default values.
*/
public MultipleStringLiteralsCheck() {
setIgnoreStringsRegexp(Pattern.compile("^\"\"$"));
ignoreOccurrenceContext.set(TokenTypes.ANNOTATION);
}
/**
* Sets the maximum allowed duplicates of a string.
* @param allowedDuplicates The maximum number of duplicates.
*/
public void setAllowedDuplicates(int allowedDuplicates) {
this.allowedDuplicates = allowedDuplicates;
}
/**
* Sets regular expression pattern for ignored strings.
* @param ignoreStringsRegexp
* regular expression pattern for ignored strings
* @noinspection WeakerAccess
*/
public final void setIgnoreStringsRegexp(Pattern ignoreStringsRegexp) {
if (ignoreStringsRegexp == null || ignoreStringsRegexp.pattern().isEmpty()) {
this.ignoreStringsRegexp = null;
}
else {
this.ignoreStringsRegexp = ignoreStringsRegexp;
}
}
/**
* Adds a set of tokens the check is interested in.
* @param strRep the string representation of the tokens interested in
*/
public final void setIgnoreOccurrenceContext(String... strRep) {
ignoreOccurrenceContext.clear();
for (final String s : strRep) {
final int type = TokenUtils.getTokenId(s);
ignoreOccurrenceContext.set(type);
}
}
@Override
public int[] getDefaultTokens() {
return getAcceptableTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[] {TokenTypes.STRING_LITERAL};
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
@Override
public void visitToken(DetailAST ast) {
if (!isInIgnoreOccurrenceContext(ast)) {
final String currentString = ast.getText();
if (ignoreStringsRegexp == null || !ignoreStringsRegexp.matcher(currentString).find()) {
List<StringInfo> hitList = stringMap.get(currentString);
if (hitList == null) {
hitList = new ArrayList<>();
stringMap.put(currentString, hitList);
}
final int line = ast.getLineNo();
final int col = ast.getColumnNo();
hitList.add(new StringInfo(line, col));
}
}
}
/**
* Analyses the path from the AST root to a given AST for occurrences
* of the token types in {@link #ignoreOccurrenceContext}.
*
* @param ast the node from where to start searching towards the root node
* @return whether the path from the root node to ast contains one of the
* token type in {@link #ignoreOccurrenceContext}.
*/
private boolean isInIgnoreOccurrenceContext(DetailAST ast) {
boolean isInIgnoreOccurrenceContext = false;
for (DetailAST token = ast;
token.getParent() != null;
token = token.getParent()) {
final int type = token.getType();
if (ignoreOccurrenceContext.get(type)) {
isInIgnoreOccurrenceContext = true;
break;
}
}
return isInIgnoreOccurrenceContext;
}
@Override
public void beginTree(DetailAST rootAST) {
stringMap.clear();
}
@Override
public void finishTree(DetailAST rootAST) {
for (Map.Entry<String, List<StringInfo>> stringListEntry : stringMap.entrySet()) {
final List<StringInfo> hits = stringListEntry.getValue();
if (hits.size() > allowedDuplicates) {
final StringInfo firstFinding = hits.get(0);
final int line = firstFinding.getLine();
final int col = firstFinding.getCol();
log(line, col, MSG_KEY, stringListEntry.getKey(), hits.size());
}
}
}
/**
* This class contains information about where a string was found.
*/
private static final class StringInfo {
/**
* Line of finding.
*/
private final int line;
/**
* Column of finding.
*/
private final int col;
/**
* Creates information about a string position.
* @param line int
* @param col int
*/
StringInfo(int line, int col) {
this.line = line;
this.col = col;
}
/**
* The line where a string was found.
* @return int Line of the string.
*/
private int getLine() {
return line;
}
/**
* The column where a string was found.
* @return int Column of the string.
*/
private int getCol() {
return col;
}
}
}
| lgpl-2.1 |
orpiske/nus | src/base/nskiplist.hpp | 13452 | // LICENSE: (Please see the file COPYING for details)
//
// NUS - Nemesis Utilities System: A C++ application development framework
// Copyright (C) 2006, 2008 Otavio Rodolfo Piske
//
// This file is part of NUS
//
// 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 version 2.1
// of the License.
//
// 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-1301 USA
//
#ifndef NSKIPLIST_HPP
#define NSKIPLIST_HPP
/**
\file nskiplist.hpp Template class implementation for NSkipList
\example ex_nskiplist.cpp
*/
/**
\brief NSkipList provides a skip-list based container class
\note Items used in the NSkipList class must implement the following operators:
=, ==, < and >.
\todo This class must not accept a max height bigger than 32 (ie. sizeof(int))
*/
template <typename T>
class DllDeclSpec NSkipList {
public:
class iterator;
/**
\brief Const iterator for NList objects
*/
typedef const iterator const_iterator;
/**
\brief Constructs a NSkipList object with a pre-defined max height
*/
NSkipList(void);
/**
\brief Constructs a NSkipList object with a defined max height
\param max Max height of the skip list (between 16 and 32)
\throw NException If given a value smaller than 16 or bigger than 32
*/
NSkipList(nint32 max);
/**
\brief Destroys a NSkipList object freeing resources used
*/
~NSkipList(void);
/**
\brief Checks whether the skip-list is empty
\return true if it is empty or false otherwise
*/
bool isEmpty(void) const;
/**
\brief Gets the max height of the skip list
\return The max height of the skip list
*/
nint32 getHeight(void) const;
/**
\brief Gets the current height of the skip list
\return The current height of the skip list
*/
nint32 getCurrentHeight(void) const;
/**
\brief Removes the item defined by key from the list. If it is
not found it will be silently ignored
\param key Item to be removed from the list
\return true if succeeded removing the item of false otherwise
*/
bool erase(const T &key);
/**
\brief Checks whether a item exists in the list
\param key The item to be checked
\return true if the item exists or false otherwise
\note It returns true if key's operator==(const T &key) function
returns true for any member already on the list
*/
bool contains(const T &key) const;
/**
\brief Gets the size of the list
\return The size of the list
*/
nuint64 size(void) const;
/**
\brief Gets the size of the list
\return The size of the list
*/
nuint64 count(void) const;
/**
\brief Returns an iterator pointing to the first item in
the list
\return An iterator pointing to the first item in the
list
*/
iterator begin(void) ;
/**
\brief Returns an iterator pointing to the first item in
the list
\return A const iterator pointing to the first item in the
list
*/
const_iterator constBegin(void) const;
/**
\brief Returns an iterator pointing to the last item in
the list
\return An iterator pointing to the last item in the
list
*/
iterator end(void);
/**
\brief Returns an iterator pointing to the last item in
the list
\return A const iterator pointing to the last item in the
list
*/
const_iterator constEnd(void) const;
/**
\brief Finds a node containing key
\param key The key to be searched
\return An iterator pointing to key or end() if not found
*/
iterator find(const T &key);
/**
\brief Finds a node containing key
\param key The key to be searched
\return A const iterator pointing to key or end() if not found
*/
const_iterator find_const(const T &key) const;
/**
\brief Inserts the data defined by key in the list. If it is
already in the list it will be silently ignored
\param key Item to be added to the list
\return An iterator pointing to key of end() if already exists
*/
iterator insert(const T &key);
/**
\brief Removes all nodes from the list
*/
void clear(void);
private:
static const nint32 DEFAULT_HEIGHT;
NSkipNode<T> *m_head; // Head node;
NSkipNode<T> **m_fix; // Update array;
NSkipNode<T> *m_curl; // Current link
nint32 m_maxh; // Max height;
nint32 m_curh; // Current height;
nuint64 m_size; // Size at level 0;
// For the PRNG
nint32 m_reset;
nint32 m_bits;
NSkipNode<T> *locate(const T &key) const;
nint32 rlevel(void);
void reset(void);
NSkipNode<T> *findPtr(const T &key);
NSkipList(const NSkipList &);
NSkipList &operator=(const NSkipList &);
};
template <typename T>
const nint32 NSkipList<T>::DEFAULT_HEIGHT = 24;
template <typename T>
NSkipList<T>::NSkipList(void)
: m_head(NULL),
m_fix(NULL),
m_curl(NULL),
m_maxh(DEFAULT_HEIGHT),
m_curh(0),
m_size(0),
m_reset(0),
m_bits(0)
{
m_head = new NSkipNode<T>(m_maxh + 1);
m_fix = new NSkipNode<T>*[m_maxh];
}
template <typename T>
NSkipList<T>::NSkipList(nint32 max)
: m_head(NULL),
m_fix(NULL),
m_curl(NULL),
m_maxh(max),
m_curh(0),
m_size(0),
m_reset(0),
m_bits(0)
{
if (m_maxh < 16 || m_maxh > 32 ) {
throw NException("Skiplist value must be between 16 and 32",
NException::BASE,
NException::EX_OUT_OF_BOUNDS);
}
m_head = new NSkipNode<T>(m_maxh + 1);
m_fix = new NSkipNode<T>*[m_maxh];
}
template <typename T>
NSkipList<T>::~NSkipList(void) {
clear();
delete m_head;
delete[] m_fix;
}
/**
\brief Selects a random height for a node.
\return Returns a random height for a node.
\note Please note that the generated random height will be between
*/
template <typename T>
nint32 NSkipList<T>::rlevel(void) {
nint32 h = 0; //random height;
nint32 found = 0;
for (h = 0; found == 0; h++) {
if (m_reset == 0) {
m_bits = nrand();
m_reset = sizeof(nint32) * CHAR_BIT - 1;
}
found = m_bits & 1;
m_bits = m_bits >> 1;
m_reset--;
}
if (h >= m_maxh) {
h = m_maxh - 1;
}
return h;
}
template <typename T>
bool NSkipList<T>::isEmpty(void) const {
if (!m_head) {
return true;
}
return false;
}
template <typename T>
nint32 NSkipList<T>::getHeight(void) const {
return m_curh;
}
/**
\brief Finds the immediatelly smaller node than 'key'.
\return A node that's smaller than key or m_head if not found
*/
template <typename T>
NSkipNode<T> *NSkipList<T>::locate(const T &key) const {
NSkipNode<T> *node = m_head;
T tmp;
for (int i = m_curh; i >= 0; i--) {
while (node->next[i] != NULL) {
tmp = node->next[i]->data;
if (key <= tmp) {
break;
}
node = node->next[i];
}
m_fix[i] = node;
}
return node;
}
template <typename T>
bool NSkipList<T>::contains(const T &key) const {
NSkipNode<T> *node = m_head;
T tmp;
for (int i = m_curh; i >= 0; i--) {
while (node->next[i] != NULL) {
tmp = node->next[i]->data;
if (key == tmp) {
return true;
}
node = node->next[i];
}
m_fix[i] = node;
}
return false;
}
template <typename T>
void NSkipList<T>::reset(void) {
m_curl = m_head->next[0];
}
template <typename T>
bool NSkipList<T>::erase(const T &key) {
NSkipNode<T> *node = NULL;
node = findPtr(key);
if (!node) {
return false;
}
// Navigate through the nodes updating the "next" pointer of the
// immediatelly smaller node.
for (int i = 0; i < m_curh; i++) {
if (m_fix[i]->next[i] != node) {
break;
}
m_fix[i]->next[i] = node->next[i];
}
// Updates the current height
while (m_curh > 0) {
if (m_head && m_head->next && m_head->next[m_curh - 1] != NULL) {
break;
}
m_curh--;
}
m_size--;
// Resets the "current" node pointer to match the current height.
reset();
delete node;
return true;
}
template <typename T>
nuint64 NSkipList<T>::size(void) const {
return count();
}
template <typename T>
nuint64 NSkipList<T>::count(void) const {
return m_size;
}
/**
\brief NSkipList::iterator is the iterator object for NSkipList
*/
template <typename T>
class NSkipList<T>::iterator {
public:
/**
\brief Constructs a NSkipList::iterator
*/
iterator(NSkipNode<T> *node)
: m_node(node)
{}
/**
\brief Copy-constructs a NSkipList::iterator
\param other The object to be copied
*/
iterator(const iterator &other): m_node(NULL) {
m_node = other.m_node;
}
/**
\brief Copies an iterator
\param rhs The iterator to be copied
\return A reference to the current object
*/
iterator &operator=(const iterator &rhs) {
m_node = rhs.m_node;
return *this;
}
/**
\brief Test whether two iterator's items differs
\param rhs The iterator with the item to be tested
\return true if differs or false otherwise
*/
bool operator!=(const iterator &rhs) const {
if (!m_node || !rhs.m_node) {
if (!m_node && !rhs.m_node) {
return false;
}
return true;
}
if (m_node->data != rhs.m_node->data) {
return true;
}
return false;
}
/**
\brief Test whether two iterator's items are equal
\param rhs The iterator with the item to be tested
\return true if equals or false otherwise
*/
bool operator==(const iterator &rhs) const {
if (!m_node || !rhs.m_node) {
if (!m_node && !rhs.m_node) {
return true;
}
return false;
}
if (m_node->data == rhs.m_node->data) {
return true;
}
return false;
}
/**
\brief Moves foward
\return An iterator pointing to the next item
*/
iterator operator++(int) {
iterator tmp(*this);
inc();
return tmp;
}
/**
\brief Moves foward
\return A const iterator pointing to the next item
*/
const iterator &operator++(void) const {
iterator tmp(*this);
m_node = m_node->next[0];
return *this;
}
/**
\brief Moves foward
\return A const iterator pointing to the next item
*/
const iterator operator++(int) const {
iterator tmp(*this);
++(*this);
return tmp;
}
/**
\brief Gets the content of the iterator's item
\return A reference to the content of the iterator's item
*/
T& operator*(void) {
return m_node->data;
}
/**
\brief Gets the content of the iterator's item
\return A const referecence to the content of the iterator's item
*/
const T& operator*(void) const {
return m_node->data;
}
/**
\brief Gets the address of the iterator's item
\return A pointer to the address of the iterator's item
*/
T* operator->(void) {
return &m_node->data;
}
/**
\brief Gets the address of the iterator's item
\return A const-pointer to the address of the iterator's item
*/
const T* operator->(void) const {
return &m_node->data;
}
private:
mutable NSkipNode<T> *m_node;
iterator inc(void) {
iterator tmp(*this);
m_node = m_node->next[0];
return tmp;
}
};
template <typename T>
typename NSkipList<T>::iterator NSkipList<T>::begin(void) {
if (m_head && m_head->next[0]) {
return typename NSkipList<T>::iterator(m_head->next[0]);
}
return typename NSkipList<T>::iterator(NULL);
}
template <typename T>
NSKIPLIST_CONST NSkipList<T>::constBegin(void) const {
if (m_head && m_head->next[0]) {
return typename NSkipList<T>::const_iterator(m_head->next[0]);
}
return typename NSkipList<T>::const_iterator(NULL);
}
template <typename T>
typename NSkipList<T>::iterator NSkipList<T>::end(void) {
return typename NSkipList<T>::iterator(NULL);
}
template <typename T>
NSKIPLIST_CONST NSkipList<T>::constEnd(void) const {
return typename NSkipList<T>::const_iterator(NULL);
}
template <typename T>
NSkipNode<T> *NSkipList<T>::findPtr(const T &key) {
NSkipNode<T> *node = m_head;
T tmp;
node = locate(key);
if (!node) {
return NULL;
}
node = node->next[0];
if (node && key == node->data) {
return node;
}
return NULL;
}
template <typename T>
typename NSkipList<T>::iterator NSkipList<T>::find(const T &key) {
return typename NSkipList<T>::iterator(find(key));
}
template <typename T>
NSKIPLIST_CONST NSkipList<T>::find_const(const T &key) const {
return typename NSkipList<T>::const_iterator(find(key));
}
template <typename T>
typename NSkipList<T>::iterator NSkipList<T>::insert(const T &key) {
nint32 height = 0;
NSkipNode<T> *node = NULL;
if (contains(key)) {
return typename NSkipList<T>::iterator(NULL);
}
height = rlevel();
node = new NSkipNode<T>(height, key);
if (height > m_curh) {
m_curh++;
height = m_curh;
m_fix[height] = m_head;
}
while (--height >= 0) {
node->next[height] = m_fix[height]->next[height];
m_fix[height]->next[height] = node;
}
m_size++;
return typename NSkipList<T>::iterator(node);
}
template <typename T>
void NSkipList<T>::clear(void) {
NSkipNode<T> *node = NULL;
NSkipNode<T> *save = NULL;
if (!m_head || !m_head->next) {
return;
}
node = m_head->next[0];
while (node) {
save = node->next[0];
delete node;
node = save;
}
}
#endif // NSKIPLIST_HPP
| lgpl-2.1 |
drdrsh/JmolOVR | src/javajs/util/OC.java | 8845 | package javajs.util;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javajs.J2SIgnoreImport;
import javajs.api.BytePoster;
import javajs.api.JmolObjectInterface;
/**
*
* A generic output method. JmolOutputChannel can be used to:
*
* add characters to a StringBuffer
* using fileName==null, append() and toString()
*
* add bytes utilizing ByteArrayOutputStream
* using writeBytes(), writeByteAsInt(), append()*, and bytesAsArray()
* *append() can be used as long as os==ByteArrayOutputStream
* or it is not used before one of the writeByte methods.
*
* output characters to a FileOutputStream
* using os==FileOutputStream, asWriter==true, append(), and closeChannel()
*
* output bytes to a FileOutputStream
* using os==FileOutputStream, writeBytes(), writeByteAsInt(), append(), and closeChannel()
*
* post characters or bytes to a remote server
* using fileName=="http://..." or "https://...",
* writeBytes(), writeByteAsInt(), append(), and closeChannel()
*
* send characters or bytes to a JavaScript function
* when JavaScript and (typeof fileName == "function")
*
* if fileName equals ";base64,", then the data are base64-encoded
* prior to writing, and closeChannel() returns the data.
*
* @author hansonr Bob Hanson [email protected] 9/2013
*
*
*/
@J2SIgnoreImport({ java.io.FileOutputStream.class })
public class OC extends OutputStream {
private BytePoster bytePoster; // only necessary for writing to http:// or https://
private String fileName;
private BufferedWriter bw;
private boolean isLocalFile;
private int byteCount;
private boolean isCanceled;
private boolean closed;
private OutputStream os;
private SB sb;
private String type;
private boolean isBase64;
private OutputStream os0;
private byte[] bytes; // preset bytes; output only
public OC setParams(BytePoster bytePoster, String fileName,
boolean asWriter, OutputStream os) {
this.bytePoster = bytePoster;
this.fileName = fileName;
isBase64 = ";base64,".equals(fileName);
if (isBase64) {
fileName = null;
os0 = os;
os = null;
}
this.os = os;
isLocalFile = (fileName != null && !isRemote(fileName));
if (asWriter && !isBase64 && os != null)
bw = new BufferedWriter(new OutputStreamWriter(os));
return this;
}
public OC setBytes(byte[] b) {
bytes = b;
return this;
}
public String getFileName() {
return fileName;
}
public String getName() {
return (fileName == null ? null : fileName.substring(fileName.lastIndexOf("/") + 1));
}
public int getByteCount() {
return byteCount;
}
/**
*
* @param type user-identified type (PNG, JPG, etc)
*/
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
/**
* will go to string buffer if bw == null and os == null
*
* @param s
* @return this, for chaining like a standard StringBuffer
*
*/
public OC append(String s) {
try {
if (bw != null) {
bw.write(s);
} else if (os == null) {
if (sb == null)
sb = new SB();
sb.append(s);
} else {
byte[] b = s.getBytes();
os.write(b, 0, b.length);
byteCount += b.length;
return this;
}
} catch (IOException e) {
// ignore
}
byteCount += s.length(); // not necessarily exactly correct if unicode
return this;
}
public void reset() {
sb = null;
initOS();
}
private void initOS() {
if (sb != null) {
String s = sb.toString();
reset();
append(s);
return;
}
try {
/**
* @j2sNative
*
* this.os = null;
*/
{
if (os instanceof FileOutputStream) {
os.close();
os = new FileOutputStream(fileName);
} else {
os = null;
}
}
if (os == null)
os = new ByteArrayOutputStream();
if (bw != null) {
bw.close();
bw = new BufferedWriter(new OutputStreamWriter(os));
}
} catch (Exception e) {
// not perfect here.
System.out.println(e.toString());
}
byteCount = 0;
}
/**
* @j2sOverride
*/
@Override
public void write(byte[] buf, int i, int len) {
if (os == null)
initOS();
try {
os.write(buf, i, len);
} catch (IOException e) {
}
byteCount += len;
}
/**
* @param b
*/
public void writeByteAsInt(int b) {
if (os == null)
initOS();
/**
* @j2sNative
*
* this.os.writeByteAsInt(b);
*
*/
{
try {
os.write(b);
} catch (IOException e) {
}
}
byteCount++;
}
/**
* Will break JavaScript if used.
*
* @j2sIgnore
*
* @param b
*/
@Override
@Deprecated
public void write(int b) {
// required by standard ZipOutputStream -- do not use, as it will break JavaScript methods
if (os == null)
initOS();
try {
os.write(b);
} catch (IOException e) {
}
byteCount++;
}
// /**
// * Will break if used; no equivalent in JavaScript.
// *
// * @j2sIgnore
// *
// * @param b
// */
// @Override
// @Deprecated
// public void write(byte[] b) {
// // not used in JavaScript due to overloading problem there
// write(b, 0, b.length);
// }
public void cancel() {
isCanceled = true;
closeChannel();
}
@SuppressWarnings({ "null", "unused" })
public String closeChannel() {
if (closed)
return null;
// can't cancel file writers
try {
if (bw != null) {
bw.flush();
bw.close();
} else if (os != null) {
os.flush();
os.close();
}
if (os0 != null && isCanceled) {
os0.flush();
os0.close();
}
} catch (Exception e) {
// ignore closing issues
}
if (isCanceled) {
closed = true;
return null;
}
if (fileName == null) {
if (isBase64) {
String s = getBase64();
if (os0 != null) {
os = os0;
append(s);
}
sb = new SB();
sb.append(s);
isBase64 = false;
return closeChannel();
}
return (sb == null ? null : sb.toString());
}
closed = true;
JmolObjectInterface jmol = null;
Object _function = null;
/**
* @j2sNative
*
* jmol = Jmol; _function = (typeof this.fileName == "function" ?
* this.fileName : null);
*
*/
{
if (!isLocalFile) {
String ret = postByteArray(); // unsigned applet could do this
if (ret.startsWith("java.net"))
byteCount = -1;
return ret;
}
}
if (jmol != null) {
Object data = (sb == null ? toByteArray() : sb.toString());
if (_function == null)
jmol._doAjax(fileName, null, data);
else
jmol._apply(fileName, data);
}
return null;
}
public boolean isBase64() {
return isBase64;
}
public String getBase64() {
return Base64.getBase64(toByteArray()).toString();
}
public byte[] toByteArray() {
return (bytes != null ? bytes : os instanceof ByteArrayOutputStream ? ((ByteArrayOutputStream)os).toByteArray() : null);
}
@Override
@Deprecated
public void close() {
closeChannel();
}
@Override
public String toString() {
if (bw != null)
try {
bw.flush();
} catch (IOException e) {
// TODO
}
if (sb != null)
return closeChannel();
return byteCount + " bytes";
}
private String postByteArray() {
byte[] bytes = (sb == null ? toByteArray() : sb.toString().getBytes());
return bytePoster.postByteArray(fileName, bytes);
}
public final static String[] urlPrefixes = { "http:", "https:", "sftp:", "ftp:",
"file:" };
// note that SFTP is not supported
public final static int URL_LOCAL = 4;
public static boolean isRemote(String fileName) {
if (fileName == null)
return false;
int itype = urlTypeIndex(fileName);
return (itype >= 0 && itype != URL_LOCAL);
}
public static boolean isLocal(String fileName) {
if (fileName == null)
return false;
int itype = urlTypeIndex(fileName);
return (itype < 0 || itype == URL_LOCAL);
}
public static int urlTypeIndex(String name) {
if (name == null)
return -2; // local unsigned applet
for (int i = 0; i < urlPrefixes.length; ++i) {
if (name.startsWith(urlPrefixes[i])) {
return i;
}
}
return -1;
}
}
| lgpl-2.1 |
ManolitoOctaviano/Language-Identification | src/java/de/danielnaber/languagetool/tagging/disambiguation/rules/fr/FrenchRuleDisambiguator.java | 1231 | /* LanguageTool, a natural language style checker
* Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de)
*
* 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 St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package de.danielnaber.languagetool.tagging.disambiguation.rules.fr;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.tagging.disambiguation.rules.AbstractRuleDisambiguator;
public class FrenchRuleDisambiguator extends AbstractRuleDisambiguator {
@Override
protected Language getLanguage() {
return Language.FRENCH;
}
}
| lgpl-2.1 |
ssdxiao/kimchi | plugins/__init__.py | 777 | #
# Project Kimchi
#
# Copyright IBM, Corp. 2014
#
# 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-1301 USA
| lgpl-2.1 |
rjamesnw/v8dotnet | Source/V8.NET-Proxy/FunctionTemplateProxy.cpp | 6817 | #include "ProxyTypes.h"
// ------------------------------------------------------------------------------------------------------------------------
FunctionTemplateProxy::FunctionTemplateProxy(V8EngineProxy* engineProxy, uint16_t* className, ManagedJSFunctionCallback managedCallback)
:ProxyBase(FunctionTemplateProxyClass), _EngineProxy(engineProxy), _EngineID(engineProxy->_EngineID)
{
// The function template will call the local "InvocationCallbackProxy" function, which then translates the call for the managed side.
_FunctionTemplate = CopyablePersistent<FunctionTemplate>(NewFunctionTemplate(InvocationCallbackProxy, NewExternal(this)));
_FunctionTemplate->SetClassName(NewUString(className));
_InstanceTemplate = new ObjectTemplateProxy(_EngineProxy, _FunctionTemplate->InstanceTemplate());
_PrototypeTemplate = new ObjectTemplateProxy(_EngineProxy, _FunctionTemplate->PrototypeTemplate());
SetManagedCallback(managedCallback);
}
V8EngineProxy* FunctionTemplateProxy::EngineProxy() { return _EngineID >= 0 && !V8EngineProxy::IsDisposed(_EngineID) ? _EngineProxy : nullptr; }
FunctionTemplateProxy::~FunctionTemplateProxy()
{
if (Type != 0) // (type is 0 if this class was wiped with 0's {if used in a marshalling test})
{
// Note: the '_InstanceTemplate' and '_PrototypeTemplate' instances are not deleted because the managed GC will do that later.
_InstanceTemplate = nullptr;
_PrototypeTemplate = nullptr;
if (!V8EngineProxy::IsDisposed(_EngineID))
{
BEGIN_ISOLATE_SCOPE(_EngineProxy);
BEGIN_CONTEXT_SCOPE(_EngineProxy);
if (!_FunctionTemplate.IsEmpty())
_FunctionTemplate.Reset();
END_CONTEXT_SCOPE;
END_ISOLATE_SCOPE;
}
_EngineProxy = nullptr;
}
}
// ------------------------------------------------------------------------------------------------------------------------
void FunctionTemplateProxy::SetManagedCallback(ManagedJSFunctionCallback managedCallback) { _ManagedCallback = managedCallback; }
// ------------------------------------------------------------------------------------------------------------------------
void FunctionTemplateProxy::InvocationCallbackProxy(const FunctionCallbackInfo<Value>& args)
{
auto proxy = (ProxyBase*)args.Data().As<External>()->Value();
V8EngineProxy *engine;
ManagedJSFunctionCallback callback;
if (proxy->GetType() == FunctionTemplateProxyClass)
{
engine = ((FunctionTemplateProxy*)proxy)->_EngineProxy;
callback = ((FunctionTemplateProxy*)proxy)->_ManagedCallback;
}
else if (proxy->GetType() == ObjectTemplateProxyClass)
{
engine = ((ObjectTemplateProxy*)proxy)->_EngineProxy;
callback = ((ObjectTemplateProxy*)proxy)->_ManagedCallback;
}
else throw exception("'args.Data()' is not recognized.");
if (callback != nullptr) // (note: '_ManagedCallback' may not be set on the proxy, and thus 'callback' may be null)
{
auto argLength = args.Length();
auto _args = argLength > 0 ? new HandleProxy*[argLength] : nullptr;
for (auto i = 0; i < argLength; i++)
_args[i] = engine->GetHandleProxy(args[i]);
auto _this = engine->GetHandleProxy(args.This()); // (was args.Holder())
engine->_InCallbackScope++;
HandleProxy* result = nullptr;
try {
result = callback(0, args.IsConstructCall(), _this, _args, argLength);
}
catch (...) { ThrowException(NewString("'InvocationCallbackProxy' caused an error - perhaps the GC collected the delegate?")); }
engine->_InCallbackScope--;
if (result != nullptr) {
if (result->IsError())
args.GetReturnValue().Set(ThrowException(Exception::Error(result->Handle()->ToString(args.GetIsolate()))));
else
args.GetReturnValue().Set(result->Handle()); // (note: the returned value was created via p/invoke calls from the managed side, so the managed side is expected to tracked and free this handle when done)
result->TryDispose();
}
// ... do this LAST, as the result may be one of the arguments returned, or even '_this' itself ...
if (_this != nullptr)
_this->TryDispose();
for (auto i = 0; i < argLength; i++)
_args[i]->TryDispose();
// (result == null == undefined [which means the managed side didn't return anything])
}
}
// ------------------------------------------------------------------------------------------------------------------------
ObjectTemplateProxy* FunctionTemplateProxy::GetInstanceTemplateProxy()
{
return _InstanceTemplate;
}
// ------------------------------------------------------------------------------------------------------------------------
ObjectTemplateProxy* FunctionTemplateProxy::GetPrototypeTemplateProxy()
{
return _PrototypeTemplate;
}
// ------------------------------------------------------------------------------------------------------------------------
HandleProxy* FunctionTemplateProxy::GetFunction()
{
auto obj = _FunctionTemplate->GetFunction(_EngineProxy->Context());
auto proxyVal = _EngineProxy->GetHandleProxy(obj.ToLocalChecked());
return proxyVal;
}
// ------------------------------------------------------------------------------------------------------------------------
HandleProxy* FunctionTemplateProxy::CreateInstance(int32_t managedObjectID, int32_t argCount, HandleProxy** args)
{
Handle<Value>* hArgs = new Handle<Value>[argCount];
for (int i = 0; i < argCount; i++)
hArgs[i] = args[i]->Handle();
auto obj = _FunctionTemplate->GetFunction(_EngineProxy->Context()).ToLocalChecked()->NewInstance(_EngineProxy->Context(), argCount, hArgs).ToLocalChecked();
delete[] hArgs; // TODO: (does "disposed" still need to be called here for each item?)
if (managedObjectID == -1)
managedObjectID = _EngineProxy->GetNextNonTemplateObjectID();
auto proxyVal = _EngineProxy->GetHandleProxy(obj);
proxyVal->_ObjectID = managedObjectID;
//??auto count = obj->InternalFieldCount();
obj->SetAlignedPointerInInternalField(0, this); // (stored a reference to the proxy instance for the call-back functions)
obj->SetInternalField(1, NewExternal((void*)(int64_t)managedObjectID)); // (stored a reference to the managed object for the call-back functions)
obj->SetPrivate(_EngineProxy->Context(), NewPrivateString("ManagedObjectID"), NewInteger(managedObjectID)); // (won't be used on template created objects [fields are faster], but done anyhow for consistency)
return proxyVal;
}
// ------------------------------------------------------------------------------------------------------------------------
void FunctionTemplateProxy::Set(const uint16_t *name, HandleProxy *value, v8::PropertyAttribute attributes)
{
if (value != nullptr)
_FunctionTemplate->Set(NewUString(name), value->Handle(), attributes); // TODO: Check how this affects objects created from templates!
}
// ------------------------------------------------------------------------------------------------------------------------
| lgpl-2.1 |
community-ssu/qt-mobility | tests/auto/qgeoinfosources_wince/tst_qgeoinfosources_wince.cpp | 6394 | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QTest>
#include <QMetaType>
#include <QSignalSpy>
#include <QObject>
#include <qgeopositioninfosource.h>
#include <qgeopositioninfo.h>
#include <qgeosatelliteinfosource.h>
#include <qgeosatelliteinfo.h>
#include "../qlocationtestutils_p.h"
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QGeoPositionInfo)
Q_DECLARE_METATYPE(QList<QGeoSatelliteInfo>)
class tst_QGeoInfoSourcesWinCE : public QObject
{
Q_OBJECT
public:
tst_QGeoInfoSourcesWinCE(QObject *parent = 0);
private slots:
void initTestCase();
void positioningMethods();
void simultaneousUpdates();
void satTriggerTimeoutSignal();
private:
QGeoPositionInfoSource *posSource;
QGeoSatelliteInfoSource *satSource;
};
tst_QGeoInfoSourcesWinCE::tst_QGeoInfoSourcesWinCE(QObject *parent) : QObject(parent) {}
void tst_QGeoInfoSourcesWinCE::initTestCase()
{
posSource = QGeoPositionInfoSource::createDefaultSource(this);
satSource = QGeoSatelliteInfoSource::createDefaultSource(this);
if (posSource == 0 || satSource == 0)
QSKIP("These tests require valid default sources for position and satellite data on WinCE.",
SkipAll);
qRegisterMetaType<QGeoPositionInfo>();
qRegisterMetaType<QList<QGeoSatelliteInfo> >();
}
void tst_QGeoInfoSourcesWinCE::positioningMethods()
{
if (posSource == 0)
QSKIP("This test requires a valid default source for position data on WinCE.",
SkipAll);
QCOMPARE(posSource->supportedPositioningMethods(),
QGeoPositionInfoSource::SatellitePositioningMethods);
posSource->setPreferredPositioningMethods(QGeoPositionInfoSource::AllPositioningMethods);
QCOMPARE(posSource->preferredPositioningMethods(),
QGeoPositionInfoSource::SatellitePositioningMethods);
posSource->setPreferredPositioningMethods(QGeoPositionInfoSource::SatellitePositioningMethods);
QCOMPARE(posSource->preferredPositioningMethods(),
QGeoPositionInfoSource::SatellitePositioningMethods);
posSource->setPreferredPositioningMethods(QGeoPositionInfoSource::NonSatellitePositioningMethods);
QCOMPARE(posSource->preferredPositioningMethods(),
QGeoPositionInfoSource::SatellitePositioningMethods);
}
void tst_QGeoInfoSourcesWinCE::simultaneousUpdates()
{
if (posSource == 0 || satSource == 0)
QSKIP("This test requires valid default sources for position and satellite data on WinCE.",
SkipAll);
QSignalSpy spyPos(posSource, SIGNAL(positionUpdated(const QGeoPositionInfo&)));
QSignalSpy spySatView(satSource,
SIGNAL(satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &)));
QSignalSpy spySatUse(satSource,
SIGNAL(satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &)));
posSource->setUpdateInterval(0);
posSource->startUpdates();
satSource->startUpdates();
EXPECT_FAIL_WINCE_SEE_MOBILITY_337;
QTRY_VERIFY_WITH_TIMEOUT((spyPos.count() > 0) && (spySatView.count() > 0)
&& (spySatUse.count() > 0), 20000);
spyPos.clear();
spySatView.clear();
spySatUse.clear();
for (int i = 0; i < 2; i++) {
EXPECT_FAIL_WINCE_SEE_MOBILITY_337;
QTRY_VERIFY_WITH_TIMEOUT((spyPos.count() > 0) && (spySatView.count() > 0)
&& (spySatUse.count() > 0), 10000);
spyPos.clear();
spySatView.clear();
spySatUse.clear();
}
posSource->stopUpdates();
satSource->stopUpdates();
}
// this is to provide code coverage for request timeouts
// - the fact that this will timeout is potentitally specific to the Win CE backend
// - a test for position timeouts would have been added, but the minimumInterval behaviours
// make a timeout harder to force
void tst_QGeoInfoSourcesWinCE::satTriggerTimeoutSignal()
{
QSignalSpy spyTimeout(satSource, SIGNAL(requestTimeout()));
satSource->requestUpdate(1);
QTRY_COMPARE_WITH_TIMEOUT(spyTimeout.count(), 1, 2000);
}
QTEST_MAIN(tst_QGeoInfoSourcesWinCE)
#include "tst_qgeoinfosources_wince.moc"
| lgpl-2.1 |
house13/CardBox | projects/games/sagashi/src/java/com/samskivert/sagashi/data/SagashiMarshaller.java | 1483 | //
// Sagashi - A word finding game for the Game Gardens platform
// http://github.com/threerings/game-gardens/blob/master/projects/games/sagashi/LICENSE
package com.samskivert.sagashi.data;
import javax.annotation.Generated;
import com.samskivert.sagashi.client.SagashiService;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.InvocationService;
import com.threerings.presents.data.InvocationMarshaller;
/**
* Provides the implementation of the {@link SagashiService} interface
* that marshalls the arguments and delivers the request to the provider
* on the server. Also provides an implementation of the response listener
* interfaces that marshall the response arguments and deliver them back
* to the requesting client.
*/
@Generated(value={"com.threerings.presents.tools.GenServiceTask"},
comments="Derived from SagashiService.java.")
public class SagashiMarshaller extends InvocationMarshaller
implements SagashiService
{
/** The method id used to dispatch {@link #submitWord} requests. */
public static final int SUBMIT_WORD = 1;
// from interface SagashiService
public void submitWord (Client arg1, String arg2, InvocationService.ResultListener arg3)
{
InvocationMarshaller.ResultMarshaller listener3 = new InvocationMarshaller.ResultMarshaller();
listener3.listener = arg3;
sendRequest(arg1, SUBMIT_WORD, new Object[] {
arg2, listener3
});
}
}
| lgpl-2.1 |
gytis/narayana | ArjunaJTS/jtax/classes/com/arjuna/ats/internal/jta/utils/jtaxI18NLogger.java | 15540 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and/or its affiliates,
* and individual contributors as indicated by the @author tags.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2010,
* @author JBoss, by Red Hat.
*/
package com.arjuna.ats.internal.jta.utils;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import static org.jboss.logging.annotations.Message.Format.MESSAGE_FORMAT;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* i18n log messages for the jtax module.
*
* @author Jonathan Halliday ([email protected]) 2010-06
*/
@MessageLogger(projectCode = "ARJUNA")
public interface jtaxI18NLogger {
/*
Message IDs are unique and non-recyclable.
Don't change the purpose of existing messages.
(tweak the message text or params for clarification if you like).
Allocate new messages by following instructions at the bottom of the file.
*/
@Message(id = 24001, value = "XA recovery committing {0}", format = MESSAGE_FORMAT)
@LogMessage(level = INFO)
public void info_jtax_recovery_jts_orbspecific_commit(String arg0);
@Message(id = 24002, value = "XA recovery rolling back {0}", format = MESSAGE_FORMAT)
@LogMessage(level = INFO)
public void info_jtax_recovery_jts_orbspecific_rollback(String arg0);
// @Message(id = 24003, value = "{0} caught exception during construction: {1}", format = MESSAGE_FORMAT)
// @LogMessage(level = WARN)
// public void warn_jtax_resources_jts_orbspecific_consterror(String arg0, String arg1);
@Message(id = 24004, value = "Caught the following error while trying to single phase complete resource", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_coperror(@Cause() Throwable arg0);
@Message(id = 24005, value = "Committing of resource state failed.", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_createstate();
@Message(id = 24006, value = "{0} caused an error from resource {1} in transaction {2}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_generror(String arg0, String arg1, String arg2, @Cause() Throwable arg3);
@Message(id = 24007, value = "You have chosen to disable the Multiple Last Resources warning. You will see it only once.", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_lastResource_disableWarning();
@Message(id = 24008, value = "Adding multiple last resources is disallowed. Current resource is {0}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_lastResource_disallow(String arg0);
@Message(id = 24009, value = "Multiple last resources have been added to the current transaction. This is transactionally unsafe and should not be relied upon. Current resource is {0}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_lastResource_multipleWarning(String arg0);
@Message(id = 24010, value = "You have chosen to enable multiple last resources in the transaction manager. This is transactionally unsafe and should not be relied upon.", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_lastResource_startupWarning();
@Message(id = 24011, value = "Reading state caught exception", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_loadstateread(@Cause() Throwable arg0);
@Message(id = 24012, value = "Could not find new XAResource to use for recovering non-serializable XAResource {0}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_norecoveryxa(String arg0);
@Message(id = 24013, value = "{0} caught NotPrepared exception during recovery phase!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_notprepared(String arg0);
@Message(id = 24014, value = "{0} - null or invalid transaction!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_nulltransaction(String arg0);
@Message(id = 24015, value = "XAResource prepare failed on resource {0} for transaction {1} with: {2}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_preparefailed(String arg0, String arg1, String arg2, @Cause() Throwable arg3);
@Message(id = 24016, value = "Recovery of resource failed when trying to call {0} got exception", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_recfailed(String arg0, @Cause() Throwable arg1);
@Message(id = 24017, value = "Attempted shutdown of resource failed with exception", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_remconn(@Cause() Throwable arg0);
@Message(id = 24018, value = "Exception on attempting to resource XAResource", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_restoreerror1(@Cause() Throwable arg0);
@Message(id = 24019, value = "Unexpected exception on attempting to resource XAResource", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_restoreerror2(@Cause() Throwable arg0);
@Message(id = 24020, value = "Could not serialize a serializable XAResource!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_saveState();
@Message(id = 24021, value = "{0} caught unexpected exception during recovery phase!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_unexpected(String arg0, @Cause() Throwable arg1);
@Message(id = 24022, value = "Updating of resource state failed.", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_updatestate();
@Message(id = 24023, value = "{0} caused an XA error: {1} from resource {2} in transaction {3}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_xaerror(String arg0, String arg1, String arg2, String arg3, @Cause() Throwable arg4);
@Message(id = 24024, value = "thread is already associated with a transaction and subtransaction support is not enabled!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_alreadyassociated();
@Message(id = 24025, value = "Delist of resource failed with exception", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_delistfailed(@Cause() Throwable arg0);
@Message(id = 24026, value = "Ending suspended RMs failed when rolling back the transaction!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_endsuspendfailed1();
@Message(id = 24027, value = "Ending suspended RMs failed when rolling back the transaction, but transaction rolled back.", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_endsuspendfailed2();
@Message(id = 24028, value = "illegal resource state:", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_illegalstate();
@Message(id = 24029, value = "Transaction is not active.", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_inactivetx();
// @Message(id = 24030, value = "invalid transaction!", format = MESSAGE_FORMAT)
// @LogMessage(level = WARN)
// public void warn_jtax_transaction_jts_invalidtx();
@Message(id = 24031, value = "Invalid transaction.", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_invalidtx2();
@Message(id = 24032, value = "Work already active!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_jca_busy();
@Message(id = 24033, value = "failed to load Last Resource Optimisation Interface {0}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_lastResourceOptimisationInterface(String arg0);
@Message(id = 24034, value = "Could not enlist resource because the transaction is marked for rollback.", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_markedrollback();
@Message(id = 24035, value = "No such transaction!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_nosuchtx();
@Message(id = 24036, value = "Current transaction is not a TransactionImple", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_nottximple();
@Message(id = 24037, value = "no transaction!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_notx();
@Message(id = 24038, value = "no transaction! Caught:", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_notxe();
// @Message(id = 24039, value = "No such transaction.", format = MESSAGE_FORMAT)
// @LogMessage(level = WARN)
// public void warn_jtax_transaction_jts_nox();
@Message(id = 24040, value = "paramater is null!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_nullparam();
// @Message(id = 24041, value = "{0} could not register transaction: {1}", format = MESSAGE_FORMAT)
// @LogMessage(level = WARN)
// public void warn_jtax_transaction_jts_regerror(String arg0, String arg1);
@Message(id = 24042, value = "is already suspended!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_ressusp();
@Message(id = 24043, value = "An error occurred while checking if this is a new resource manager:", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_rmerror(@Cause() Throwable arg0);
@Message(id = 24044, value = "{0} could not mark the transaction as rollback only", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_rollbackerror(String arg0, @Cause() Throwable arg1);
// @Message(id = 24045, value = "setRollbackOnly called from:", format = MESSAGE_FORMAT)
// @LogMessage(level = WARN)
// public void warn_jtax_transaction_jts_setrollback();
@Message(id = 24046, value = "{0} returned XA error {1} for transaction {2}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_starterror(String arg0, String arg1, String arg2, @Cause() Throwable arg3);
// @Message(id = 24047, value = "Not allowed to terminate subordinate transaction directly.", format = MESSAGE_FORMAT)
// @LogMessage(level = WARN)
// public void warn_jtax_transaction_jts_subordinate_invalidstate();
@Message(id = 24048, value = "Synchronizations are not allowed!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_syncerror();
@Message(id = 24049, value = "cleanup synchronization failed to register:", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_syncproblem(@Cause() Throwable arg0);
@Message(id = 24050, value = "The transaction implementation threw a RollbackException", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_syncrollbackexception();
@Message(id = 24051, value = "The transaction implementation threw a SystemException", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_systemexception();
@Message(id = 24052, value = "Active thread error:", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_threaderror(@Cause() Throwable arg0);
@Message(id = 24053, value = "{0} attempt to delist unknown resource!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_unknownres(String arg0);
@Message(id = 24054, value = "The current transaction does not match this transaction!", format = MESSAGE_FORMAT)
public String get_jtax_transaction_jts_wrongstatetx();
@Message(id = 24055, value = "Could not call end on a suspended resource!", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_xaenderror();
@Message(id = 24056, value = "{0} caught XA exception: {1}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_xaerror(String arg0, String arg1, @Cause() Throwable arg2);
@Message(id = 24057, value = "{0} setTransactionTimeout on XAResource {2} threw: {1}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_transaction_jts_timeouterror(String arg0, String arg1, String arg2, @Cause() Throwable arg3);
@Message(id = 24058, value = "Could not deserialize class. Will wait for bottom up recovery", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_could_not_load_class_will_wait_for_bottom_up(@Cause() ClassNotFoundException cnfe);
@Message(id = 24059, value = "Inflow recovery is not supported for JTS mode", format = MESSAGE_FORMAT)
String get_not_supported();
@Message(id = 24060, value = "Could not end XA resource {0}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
void warn_could_not_end_xar(XAResource xar, @Cause() XAException e1);
@Message(id = 24061, value = "Could not enlist XA resource {0} with params {1}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
void warn_could_not_enlist_xar(XAResource xar, Object[] params, @Cause() Exception e1);
@Message(id = 24062, value = "ORB '{0}' occured on one phase commit for xid {1}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_orbspecific_cant_commit_onephase(Xid xid, Class<? extends Throwable> corbaException, @Cause() Throwable e);
@Message(id = 24063, value = "Can't save state of xid {0}", format = MESSAGE_FORMAT)
@LogMessage(level = WARN)
public void warn_jtax_resources_jts_cant_save_state(Xid xid, @Cause() Throwable e);
/*
Allocate new messages directly above this notice.
- id: use the next id number in sequence. Don't reuse ids.
The first two digits of the id(XXyyy) denote the module
all message in this file should have the same prefix.
- value: default (English) version of the log message.
- level: according to severity semantics defined at http://docspace.corp.redhat.com/docs/DOC-30217
Debug and trace don't get i18n. Everything else MUST be i18n.
By convention methods with String return type have prefix get_,
all others are log methods and have prefix <level>_
*/
}
| lgpl-2.1 |
savoirfairelinux/ring-lrc | src/dbus/videomanager.cpp | 2333 | /****************************************************************************
* Copyright (C) 2012-2021 Savoir-faire Linux Inc. *
* Author : Emmanuel Lepage Vallee <[email protected]> *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "videomanager.h"
#include "../globalinstances.h"
#include "../interfaces/dbuserrorhandleri.h"
VideoManagerInterface&
VideoManager::instance()
{
#ifdef ENABLE_LIBWRAP
static auto interface = new VideoManagerInterface();
#else
if (!dbus_metaTypeInit)
registerCommTypes();
static auto interface = new VideoManagerInterface("cx.ring.Ring",
"/cx/ring/Ring/VideoManager",
QDBusConnection::sessionBus());
if (!interface->connection().isConnected()) {
GlobalInstances::dBusErrorHandler().connectionError(
"Error : jamid not connected. Service " + interface->service()
+ " not connected. From video manager interface.");
}
if (!interface->isValid()) {
GlobalInstances::dBusErrorHandler().invalidInterfaceError(
"Error : jamid is not available, make sure it is running");
}
#endif
return *interface;
}
| lgpl-2.1 |
mattalexx/dbal | lib/Doctrine/DBAL/Driver/IBMDB2/DB2Driver.php | 3862 | <?php
/*
* 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Driver\IBMDB2;
use Doctrine\DBAL\Driver,
Doctrine\DBAL\Connection;
/**
* IBM DB2 Driver
*
* @since 2.0
* @author Benjamin Eberlei <[email protected]>
*/
class DB2Driver implements Driver
{
/**
* Attempts to create a connection with the database.
*
* @param array $params All connection parameters passed by the user.
* @param string $username The username to use when connecting.
* @param string $password The password to use when connecting.
* @param array $driverOptions The driver options to use when connecting.
* @return \Doctrine\DBAL\Driver\Connection The database connection.
*/
public function connect(array $params, $username = null, $password = null, array $driverOptions = array())
{
if ( ! isset($params['protocol'])) {
$params['protocol'] = 'TCPIP';
}
if ($params['host'] !== 'localhost' && $params['host'] != '127.0.0.1') {
// if the host isn't localhost, use extended connection params
$params['dbname'] = 'DRIVER={IBM DB2 ODBC DRIVER}' .
';DATABASE=' . $params['dbname'] .
';HOSTNAME=' . $params['host'] .
';PROTOCOL=' . $params['protocol'] .
';UID=' . $username .
';PWD=' . $password .';';
if (isset($params['port'])) {
$params['dbname'] .= 'PORT=' . $params['port'];
}
$username = null;
$password = null;
}
return new DB2Connection($params, $username, $password, $driverOptions);
}
/**
* Gets the DatabasePlatform instance that provides all the metadata about
* the platform this driver connects to.
*
* @return \Doctrine\DBAL\Platforms\AbstractPlatform The database platform.
*/
public function getDatabasePlatform()
{
return new \Doctrine\DBAL\Platforms\DB2Platform;
}
/**
* Gets the SchemaManager that can be used to inspect and change the underlying
* database schema of the platform this driver connects to.
*
* @param \Doctrine\DBAL\Connection $conn
* @return \Doctrine\DBAL\SchemaManager
*/
public function getSchemaManager(Connection $conn)
{
return new \Doctrine\DBAL\Schema\DB2SchemaManager($conn);
}
/**
* Gets the name of the driver.
*
* @return string The name of the driver.
*/
public function getName()
{
return 'ibm_db2';
}
/**
* Get the name of the database connected to for this driver.
*
* @param \Doctrine\DBAL\Connection $conn
* @return string $database
*/
public function getDatabase(\Doctrine\DBAL\Connection $conn)
{
$params = $conn->getParams();
return $params['dbname'];
}
}
| lgpl-2.1 |
4thAce/evilhow | lib/pear/PEAR/Registry.php | 73386 | <?php
/**
* PEAR_Registry
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to [email protected] so we can mail you a copy immediately.
*
* @category pear
* @package PEAR
* @author Stig Bakken <[email protected]>
* @author Tomas V. V. Cox <[email protected]>
* @author Greg Beaver <[email protected]>
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: Id: Registry.php,v 1.166 2007/06/16 18:41:59 cellog Exp
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
*/
/**
* for PEAR_Error
*/
require_once 'PEAR.php';
require_once 'PEAR/DependencyDB.php';
define('PEAR_REGISTRY_ERROR_LOCK', -2);
define('PEAR_REGISTRY_ERROR_FORMAT', -3);
define('PEAR_REGISTRY_ERROR_FILE', -4);
define('PEAR_REGISTRY_ERROR_CONFLICT', -5);
define('PEAR_REGISTRY_ERROR_CHANNEL_FILE', -6);
/**
* Administration class used to maintain the installed package database.
* @category pear
* @package PEAR
* @author Stig Bakken <[email protected]>
* @author Tomas V. V. Cox <[email protected]>
* @author Greg Beaver <[email protected]>
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: 1.6.1
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 1.4.0a1
*/
class PEAR_Registry extends PEAR
{
// {{{ properties
/**
* File containing all channel information.
* @var string
*/
var $channels = '';
/** Directory where registry files are stored.
* @var string
*/
var $statedir = '';
/** File where the file map is stored
* @var string
*/
var $filemap = '';
/** Directory where registry files for channels are stored.
* @var string
*/
var $channelsdir = '';
/** Name of file used for locking the registry
* @var string
*/
var $lockfile = '';
/** File descriptor used during locking
* @var resource
*/
var $lock_fp = null;
/** Mode used during locking
* @var int
*/
var $lock_mode = 0; // XXX UNUSED
/** Cache of package information. Structure:
* array(
* 'package' => array('id' => ... ),
* ... )
* @var array
*/
var $pkginfo_cache = array();
/** Cache of file map. Structure:
* array( '/path/to/file' => 'package', ... )
* @var array
*/
var $filemap_cache = array();
/**
* @var false|PEAR_ChannelFile
*/
var $_pearChannel;
/**
* @var false|PEAR_ChannelFile
*/
var $_peclChannel;
/**
* @var PEAR_DependencyDB
*/
var $_dependencyDB;
/**
* @var PEAR_Config
*/
var $_config;
// }}}
// {{{ constructor
/**
* PEAR_Registry constructor.
*
* @param string (optional) PEAR install directory (for .php files)
* @param PEAR_ChannelFile PEAR_ChannelFile object representing the PEAR channel, if
* default values are not desired. Only used the very first time a PEAR
* repository is initialized
* @param PEAR_ChannelFile PEAR_ChannelFile object representing the PECL channel, if
* default values are not desired. Only used the very first time a PEAR
* repository is initialized
*
* @access public
*/
function PEAR_Registry($pear_install_dir = PEAR_INSTALL_DIR, $pear_channel = false,
$pecl_channel = false)
{
parent::PEAR();
$ds = DIRECTORY_SEPARATOR;
$this->install_dir = $pear_install_dir;
$this->channelsdir = $pear_install_dir.$ds.'.channels';
$this->statedir = $pear_install_dir.$ds.'.registry';
$this->filemap = $pear_install_dir.$ds.'.filemap';
$this->lockfile = $pear_install_dir.$ds.'.lock';
$this->_pearChannel = $pear_channel;
$this->_peclChannel = $pecl_channel;
$this->_config = false;
}
function hasWriteAccess()
{
if (!file_exists($this->install_dir)) {
$dir = $this->install_dir;
while ($dir && $dir != '.') {
$olddir = $dir;
$dir = dirname($dir); // cd ..
if ($dir != '.' && file_exists($dir)) {
if (is_writeable($dir)) {
return true;
} else {
return false;
}
}
if ($dir == $olddir) { // this can happen in safe mode
return @is_writable($dir);
}
}
return false;
}
return is_writeable($this->install_dir);
}
function setConfig(&$config)
{
$this->_config = &$config;
}
function _initializeChannelDirs()
{
static $running = false;
if (!$running) {
$running = true;
$ds = DIRECTORY_SEPARATOR;
if (!is_dir($this->channelsdir) ||
!file_exists($this->channelsdir . $ds . 'pear.php.net.reg') ||
!file_exists($this->channelsdir . $ds . 'pecl.php.net.reg') ||
!file_exists($this->channelsdir . $ds . '__uri.reg')) {
if (!file_exists($this->channelsdir . $ds . 'pear.php.net.reg')) {
$pear_channel = $this->_pearChannel;
if (!is_a($pear_channel, 'PEAR_ChannelFile') || !$pear_channel->validate()) {
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$pear_channel = new PEAR_ChannelFile;
$pear_channel->setName('pear.php.net');
$pear_channel->setAlias('pear');
$pear_channel->setServer('pear.php.net');
$pear_channel->setSummary('PHP Extension and Application Repository');
$pear_channel->setDefaultPEARProtocols();
$pear_channel->setBaseURL('REST1.0', 'http://pear.php.net/rest/');
$pear_channel->setBaseURL('REST1.1', 'http://pear.php.net/rest/');
} else {
$pear_channel->setName('pear.php.net');
$pear_channel->setAlias('pear');
}
$pear_channel->validate();
$this->_addChannel($pear_channel);
}
if (!file_exists($this->channelsdir . $ds . 'pecl.php.net.reg')) {
$pecl_channel = $this->_peclChannel;
if (!is_a($pecl_channel, 'PEAR_ChannelFile') || !$pecl_channel->validate()) {
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$pecl_channel = new PEAR_ChannelFile;
$pecl_channel->setName('pecl.php.net');
$pecl_channel->setAlias('pecl');
$pecl_channel->setServer('pecl.php.net');
$pecl_channel->setSummary('PHP Extension Community Library');
$pecl_channel->setDefaultPEARProtocols();
$pecl_channel->setBaseURL('REST1.0', 'http://pecl.php.net/rest/');
$pecl_channel->setBaseURL('REST1.1', 'http://pecl.php.net/rest/');
$pecl_channel->setValidationPackage('PEAR_Validator_PECL', '1.0');
} else {
$pecl_channel->setName('pecl.php.net');
$pecl_channel->setAlias('pecl');
}
$pecl_channel->validate();
$this->_addChannel($pecl_channel);
}
if (!file_exists($this->channelsdir . $ds . '__uri.reg')) {
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$private = new PEAR_ChannelFile;
$private->setName('__uri');
$private->addFunction('xmlrpc', '1.0', '****');
$private->setSummary('Pseudo-channel for static packages');
$this->_addChannel($private);
}
$this->_rebuildFileMap();
}
$running = false;
}
}
function _initializeDirs()
{
$ds = DIRECTORY_SEPARATOR;
// XXX Compatibility code should be removed in the future
// rename all registry files if any to lowercase
if (!OS_WINDOWS && file_exists($this->statedir) && is_dir($this->statedir) &&
$handle = opendir($this->statedir)) {
$dest = $this->statedir . $ds;
while (false !== ($file = readdir($handle))) {
if (preg_match('/^.*[A-Z].*\.reg\\z/', $file)) {
rename($dest . $file, $dest . strtolower($file));
}
}
closedir($handle);
}
$this->_initializeChannelDirs();
if (!file_exists($this->filemap)) {
$this->_rebuildFileMap();
}
$this->_initializeDepDB();
}
function _initializeDepDB()
{
if (!isset($this->_dependencyDB)) {
static $initializing = false;
if (!$initializing) {
$initializing = true;
if (!$this->_config) { // never used?
if (OS_WINDOWS) {
$file = 'pear.ini';
} else {
$file = '.pearrc';
}
$this->_config = &new PEAR_Config($this->statedir . DIRECTORY_SEPARATOR .
$file);
$this->_config->setRegistry($this);
$this->_config->set('php_dir', $this->install_dir);
}
$this->_dependencyDB = &PEAR_DependencyDB::singleton($this->_config);
if (PEAR::isError($this->_dependencyDB)) {
// attempt to recover by removing the dep db
if (file_exists($this->_config->get('php_dir', null, 'pear.php.net') .
DIRECTORY_SEPARATOR . '.depdb')) {
@unlink($this->_config->get('php_dir', null, 'pear.php.net') .
DIRECTORY_SEPARATOR . '.depdb');
}
$this->_dependencyDB = &PEAR_DependencyDB::singleton($this->_config);
if (PEAR::isError($this->_dependencyDB)) {
echo $this->_dependencyDB->getMessage();
echo 'Unrecoverable error';
exit(1);
}
}
$initializing = false;
}
}
}
// }}}
// {{{ destructor
/**
* PEAR_Registry destructor. Makes sure no locks are forgotten.
*
* @access private
*/
function _PEAR_Registry()
{
parent::_PEAR();
if (is_resource($this->lock_fp)) {
$this->_unlock();
}
}
// }}}
// {{{ _assertStateDir()
/**
* Make sure the directory where we keep registry files exists.
*
* @return bool TRUE if directory exists, FALSE if it could not be
* created
*
* @access private
*/
function _assertStateDir($channel = false)
{
if ($channel && $this->_getChannelFromAlias($channel) != 'pear.php.net') {
return $this->_assertChannelStateDir($channel);
}
static $init = false;
if (!file_exists($this->statedir)) {
if (!$this->hasWriteAccess()) {
return false;
}
require_once 'System.php';
if (!System::mkdir(array('-p', $this->statedir))) {
return $this->raiseError("could not create directory '{$this->statedir}'");
}
$init = true;
} elseif (!is_dir($this->statedir)) {
return $this->raiseError('Cannot create directory ' . $this->statedir . ', ' .
'it already exists and is not a directory');
}
$ds = DIRECTORY_SEPARATOR;
if (!file_exists($this->channelsdir)) {
if (!file_exists($this->channelsdir . $ds . 'pear.php.net.reg') ||
!file_exists($this->channelsdir . $ds . 'pecl.php.net.reg') ||
!file_exists($this->channelsdir . $ds . '__uri.reg')) {
$init = true;
}
} elseif (!is_dir($this->channelsdir)) {
return $this->raiseError('Cannot create directory ' . $this->channelsdir . ', ' .
'it already exists and is not a directory');
}
if ($init) {
static $running = false;
if (!$running) {
$running = true;
$this->_initializeDirs();
$running = false;
$init = false;
}
} else {
$this->_initializeDepDB();
}
return true;
}
// }}}
// {{{ _assertChannelStateDir()
/**
* Make sure the directory where we keep registry files exists for a non-standard channel.
*
* @param string channel name
* @return bool TRUE if directory exists, FALSE if it could not be
* created
*
* @access private
*/
function _assertChannelStateDir($channel)
{
$ds = DIRECTORY_SEPARATOR;
if (!$channel || $this->_getChannelFromAlias($channel) == 'pear.php.net') {
if (!file_exists($this->channelsdir . $ds . 'pear.php.net.reg')) {
$this->_initializeChannelDirs();
}
return $this->_assertStateDir($channel);
}
$channelDir = $this->_channelDirectoryName($channel);
if (!is_dir($this->channelsdir) ||
!file_exists($this->channelsdir . $ds . 'pear.php.net.reg')) {
$this->_initializeChannelDirs();
}
if (!file_exists($channelDir)) {
if (!$this->hasWriteAccess()) {
return false;
}
require_once 'System.php';
if (!System::mkdir(array('-p', $channelDir))) {
return $this->raiseError("could not create directory '" . $channelDir .
"'");
}
} elseif (!is_dir($channelDir)) {
return $this->raiseError("could not create directory '" . $channelDir .
"', already exists and is not a directory");
}
return true;
}
// }}}
// {{{ _assertChannelDir()
/**
* Make sure the directory where we keep registry files for channels exists
*
* @return bool TRUE if directory exists, FALSE if it could not be
* created
*
* @access private
*/
function _assertChannelDir()
{
if (!file_exists($this->channelsdir)) {
if (!$this->hasWriteAccess()) {
return false;
}
require_once 'System.php';
if (!System::mkdir(array('-p', $this->channelsdir))) {
return $this->raiseError("could not create directory '{$this->channelsdir}'");
}
} elseif (!is_dir($this->channelsdir)) {
return $this->raiseError("could not create directory '{$this->channelsdir}" .
"', it already exists and is not a directory");
}
if (!file_exists($this->channelsdir . DIRECTORY_SEPARATOR . '.alias')) {
if (!$this->hasWriteAccess()) {
return false;
}
require_once 'System.php';
if (!System::mkdir(array('-p', $this->channelsdir . DIRECTORY_SEPARATOR . '.alias'))) {
return $this->raiseError("could not create directory '{$this->channelsdir}/.alias'");
}
} elseif (!is_dir($this->channelsdir . DIRECTORY_SEPARATOR . '.alias')) {
return $this->raiseError("could not create directory '{$this->channelsdir}" .
"/.alias', it already exists and is not a directory");
}
return true;
}
// }}}
// {{{ _packageFileName()
/**
* Get the name of the file where data for a given package is stored.
*
* @param string channel name, or false if this is a PEAR package
* @param string package name
*
* @return string registry file name
*
* @access public
*/
function _packageFileName($package, $channel = false)
{
if ($channel && $this->_getChannelFromAlias($channel) != 'pear.php.net') {
return $this->_channelDirectoryName($channel) . DIRECTORY_SEPARATOR .
strtolower($package) . '.reg';
}
return $this->statedir . DIRECTORY_SEPARATOR . strtolower($package) . '.reg';
}
// }}}
// {{{ _channelFileName()
/**
* Get the name of the file where data for a given channel is stored.
* @param string channel name
* @return string registry file name
*/
function _channelFileName($channel, $noaliases = false)
{
if (!$noaliases) {
if (file_exists($this->_getChannelAliasFileName($channel))) {
$channel = implode('', file($this->_getChannelAliasFileName($channel)));
}
}
return $this->channelsdir . DIRECTORY_SEPARATOR . str_replace('/', '_',
strtolower($channel)) . '.reg';
}
// }}}
// {{{ getChannelAliasFileName()
/**
* @param string
* @return string
*/
function _getChannelAliasFileName($alias)
{
return $this->channelsdir . DIRECTORY_SEPARATOR . '.alias' .
DIRECTORY_SEPARATOR . str_replace('/', '_', strtolower($alias)) . '.txt';
}
// }}}
// {{{ _getChannelFromAlias()
/**
* Get the name of a channel from its alias
*/
function _getChannelFromAlias($channel)
{
if (!$this->_channelExists($channel)) {
if ($channel == 'pear.php.net') {
return 'pear.php.net';
}
if ($channel == 'pecl.php.net') {
return 'pecl.php.net';
}
if ($channel == '__uri') {
return '__uri';
}
return false;
}
$channel = strtolower($channel);
if (file_exists($this->_getChannelAliasFileName($channel))) {
// translate an alias to an actual channel
return implode('', file($this->_getChannelAliasFileName($channel)));
} else {
return $channel;
}
}
// }}}
// {{{ _getChannelFromAlias()
/**
* Get the alias of a channel from its alias or its name
*/
function _getAlias($channel)
{
if (!$this->_channelExists($channel)) {
if ($channel == 'pear.php.net') {
return 'pear';
}
if ($channel == 'pecl.php.net') {
return 'pecl';
}
return false;
}
$channel = $this->_getChannel($channel);
if (PEAR::isError($channel)) {
return $channel;
}
return $channel->getAlias();
}
// }}}
// {{{ _channelDirectoryName()
/**
* Get the name of the file where data for a given package is stored.
*
* @param string channel name, or false if this is a PEAR package
* @param string package name
*
* @return string registry file name
*
* @access public
*/
function _channelDirectoryName($channel)
{
if (!$channel || $this->_getChannelFromAlias($channel) == 'pear.php.net') {
return $this->statedir;
} else {
$ch = $this->_getChannelFromAlias($channel);
if (!$ch) {
$ch = $channel;
}
return $this->statedir . DIRECTORY_SEPARATOR . strtolower('.channel.' .
str_replace('/', '_', $ch));
}
}
// }}}
// {{{ _openPackageFile()
function _openPackageFile($package, $mode, $channel = false)
{
if (!$this->_assertStateDir($channel)) {
return null;
}
if (!in_array($mode, array('r', 'rb')) && !$this->hasWriteAccess()) {
return null;
}
$file = $this->_packageFileName($package, $channel);
if (!file_exists($file) && $mode == 'r' || $mode == 'rb') {
return null;
}
$fp = @fopen($file, $mode);
if (!$fp) {
return null;
}
return $fp;
}
// }}}
// {{{ _closePackageFile()
function _closePackageFile($fp)
{
fclose($fp);
}
// }}}
// {{{ _openChannelFile()
function _openChannelFile($channel, $mode)
{
if (!$this->_assertChannelDir()) {
return null;
}
if (!in_array($mode, array('r', 'rb')) && !$this->hasWriteAccess()) {
return null;
}
$file = $this->_channelFileName($channel);
if (!file_exists($file) && $mode == 'r' || $mode == 'rb') {
return null;
}
$fp = @fopen($file, $mode);
if (!$fp) {
return null;
}
return $fp;
}
// }}}
// {{{ _closePackageFile()
function _closeChannelFile($fp)
{
fclose($fp);
}
// }}}
// {{{ _rebuildFileMap()
function _rebuildFileMap()
{
if (!class_exists('PEAR_Installer_Role')) {
require_once 'PEAR/Installer/Role.php';
}
$channels = $this->_listAllPackages();
$files = array();
foreach ($channels as $channel => $packages) {
foreach ($packages as $package) {
$version = $this->_packageInfo($package, 'version', $channel);
$filelist = $this->_packageInfo($package, 'filelist', $channel);
if (!is_array($filelist)) {
continue;
}
foreach ($filelist as $name => $attrs) {
if (isset($attrs['attribs'])) {
$attrs = $attrs['attribs'];
}
// it is possible for conflicting packages in different channels to
// conflict with data files/doc files
if ($name == 'dirtree') {
continue;
}
if (isset($attrs['role']) && !in_array($attrs['role'],
PEAR_Installer_Role::getInstallableRoles())) {
// these are not installed
continue;
}
if (isset($attrs['role']) && !in_array($attrs['role'],
PEAR_Installer_Role::getBaseinstallRoles())) {
$attrs['baseinstalldir'] = $package;
}
if (isset($attrs['baseinstalldir'])) {
$file = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name;
} else {
$file = $name;
}
$file = preg_replace(',^/+,', '', $file);
if ($channel != 'pear.php.net') {
if (!isset($files[$attrs['role']])) {
$files[$attrs['role']] = array();
}
$files[$attrs['role']][$file] = array(strtolower($channel),
strtolower($package));
} else {
if (!isset($files[$attrs['role']])) {
$files[$attrs['role']] = array();
}
$files[$attrs['role']][$file] = strtolower($package);
}
}
}
}
$this->_assertStateDir();
if (!$this->hasWriteAccess()) {
return false;
}
$fp = @fopen($this->filemap, 'wb');
if (!$fp) {
return false;
}
$this->filemap_cache = $files;
fwrite($fp, serialize($files));
fclose($fp);
return true;
}
// }}}
// {{{ _readFileMap()
function _readFileMap()
{
if (!file_exists($this->filemap)) {
return array();
}
$fp = @fopen($this->filemap, 'r');
if (!$fp) {
return $this->raiseError('PEAR_Registry: could not open filemap "' . $this->filemap . '"', PEAR_REGISTRY_ERROR_FILE, null, null, $php_errormsg);
}
clearstatcache();
$rt = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
$fsize = filesize($this->filemap);
fclose($fp);
$data = file_get_contents($this->filemap);
set_magic_quotes_runtime($rt);
$tmp = unserialize($data);
if (!$tmp && $fsize > 7) {
return $this->raiseError('PEAR_Registry: invalid filemap data', PEAR_REGISTRY_ERROR_FORMAT, null, null, $data);
}
$this->filemap_cache = $tmp;
return true;
}
// }}}
// {{{ _lock()
/**
* Lock the registry.
*
* @param integer lock mode, one of LOCK_EX, LOCK_SH or LOCK_UN.
* See flock manual for more information.
*
* @return bool TRUE on success, FALSE if locking failed, or a
* PEAR error if some other error occurs (such as the
* lock file not being writable).
*
* @access private
*/
function _lock($mode = LOCK_EX)
{
if (!eregi('Windows 9', php_uname())) {
if ($mode != LOCK_UN && is_resource($this->lock_fp)) {
// XXX does not check type of lock (LOCK_SH/LOCK_EX)
return true;
}
if (!$this->_assertStateDir()) {
if ($mode == LOCK_EX) {
return $this->raiseError('Registry directory is not writeable by the current user');
} else {
return true;
}
}
$open_mode = 'w';
// XXX People reported problems with LOCK_SH and 'w'
if ($mode === LOCK_SH || $mode === LOCK_UN) {
if (!file_exists($this->lockfile)) {
touch($this->lockfile);
}
$open_mode = 'r';
}
if (!is_resource($this->lock_fp)) {
$this->lock_fp = @fopen($this->lockfile, $open_mode);
}
if (!is_resource($this->lock_fp)) {
return $this->raiseError("could not create lock file" .
(isset($php_errormsg) ? ": " . $php_errormsg : ""));
}
if (!(int)flock($this->lock_fp, $mode)) {
switch ($mode) {
case LOCK_SH: $str = 'shared'; break;
case LOCK_EX: $str = 'exclusive'; break;
case LOCK_UN: $str = 'unlock'; break;
default: $str = 'unknown'; break;
}
return $this->raiseError("could not acquire $str lock ($this->lockfile)",
PEAR_REGISTRY_ERROR_LOCK);
}
}
return true;
}
// }}}
// {{{ _unlock()
function _unlock()
{
$ret = $this->_lock(LOCK_UN);
if (is_resource($this->lock_fp)) {
fclose($this->lock_fp);
}
$this->lock_fp = null;
return $ret;
}
// }}}
// {{{ _packageExists()
function _packageExists($package, $channel = false)
{
return file_exists($this->_packageFileName($package, $channel));
}
// }}}
// {{{ _channelExists()
/**
* Determine whether a channel exists in the registry
* @param string Channel name
* @param bool if true, then aliases will be ignored
* @return boolean
*/
function _channelExists($channel, $noaliases = false)
{
$a = file_exists($this->_channelFileName($channel, $noaliases));
if (!$a && $channel == 'pear.php.net') {
return true;
}
if (!$a && $channel == 'pecl.php.net') {
return true;
}
return $a;
}
// }}}
// {{{ _addChannel()
/**
* @param PEAR_ChannelFile Channel object
* @param donotuse
* @param string Last-Modified HTTP tag from remote request
* @return boolean|PEAR_Error True on creation, false if it already exists
*/
function _addChannel($channel, $update = false, $lastmodified = false)
{
if (!is_a($channel, 'PEAR_ChannelFile')) {
return false;
}
if (!$channel->validate()) {
return false;
}
if (file_exists($this->_channelFileName($channel->getName()))) {
if (!$update) {
return false;
}
$checker = $this->_getChannel($channel->getName());
if (PEAR::isError($checker)) {
return $checker;
}
if ($channel->getAlias() != $checker->getAlias()) {
if (file_exists($this->_getChannelAliasFileName($checker->getAlias()))) {
@unlink($this->_getChannelAliasFileName($checker->getAlias()));
}
}
} else {
if ($update && !in_array($channel->getName(), array('pear.php.net', 'pecl.php.net'))) {
return false;
}
}
$ret = $this->_assertChannelDir();
if (PEAR::isError($ret)) {
return $ret;
}
$ret = $this->_assertChannelStateDir($channel->getName());
if (PEAR::isError($ret)) {
return $ret;
}
if ($channel->getAlias() != $channel->getName()) {
if (file_exists($this->_getChannelAliasFileName($channel->getAlias())) &&
$this->_getChannelFromAlias($channel->getAlias()) != $channel->getName()) {
$channel->setAlias($channel->getName());
}
if (!$this->hasWriteAccess()) {
return false;
}
$fp = @fopen($this->_getChannelAliasFileName($channel->getAlias()), 'w');
if (!$fp) {
return false;
}
fwrite($fp, $channel->getName());
fclose($fp);
}
if (!$this->hasWriteAccess()) {
return false;
}
$fp = @fopen($this->_channelFileName($channel->getName()), 'wb');
if (!$fp) {
return false;
}
$info = $channel->toArray();
if ($lastmodified) {
$info['_lastmodified'] = $lastmodified;
} else {
$info['_lastmodified'] = date('r');
}
fwrite($fp, serialize($info));
fclose($fp);
return true;
}
// }}}
// {{{ _deleteChannel()
/**
* Deletion fails if there are any packages installed from the channel
* @param string|PEAR_ChannelFile channel name
* @return boolean|PEAR_Error True on deletion, false if it doesn't exist
*/
function _deleteChannel($channel)
{
if (!is_string($channel)) {
if (is_a($channel, 'PEAR_ChannelFile')) {
if (!$channel->validate()) {
return false;
}
$channel = $channel->getName();
} else {
return false;
}
}
if ($this->_getChannelFromAlias($channel) == '__uri') {
return false;
}
if ($this->_getChannelFromAlias($channel) == 'pecl.php.net') {
return false;
}
if (!$this->_channelExists($channel)) {
return false;
}
if (!$channel || $this->_getChannelFromAlias($channel) == 'pear.php.net') {
return false;
}
$channel = $this->_getChannelFromAlias($channel);
if ($channel == 'pear.php.net') {
return false;
}
$test = $this->_listChannelPackages($channel);
if (count($test)) {
return false;
}
$test = @rmdir($this->_channelDirectoryName($channel));
if (!$test) {
return false;
}
$file = $this->_getChannelAliasFileName($this->_getAlias($channel));
if (file_exists($file)) {
$test = @unlink($file);
if (!$test) {
return false;
}
}
$file = $this->_channelFileName($channel);
$ret = true;
if (file_exists($file)) {
$ret = @unlink($file);
}
return $ret;
}
// }}}
// {{{ _isChannelAlias()
/**
* Determine whether a channel exists in the registry
* @param string Channel Alias
* @return boolean
*/
function _isChannelAlias($alias)
{
return file_exists($this->_getChannelAliasFileName($alias));
}
// }}}
// {{{ _packageInfo()
/**
* @param string|null
* @param string|null
* @param string|null
* @return array|null
* @access private
*/
function _packageInfo($package = null, $key = null, $channel = 'pear.php.net')
{
if ($package === null) {
if ($channel === null) {
$channels = $this->_listChannels();
$ret = array();
foreach ($channels as $channel) {
$channel = strtolower($channel);
$ret[$channel] = array();
$packages = $this->_listPackages($channel);
foreach ($packages as $package) {
$ret[$channel][] = $this->_packageInfo($package, null, $channel);
}
}
return $ret;
}
$ps = $this->_listPackages($channel);
if (!count($ps)) {
return array();
}
return array_map(array(&$this, '_packageInfo'),
$ps, array_fill(0, count($ps), null),
array_fill(0, count($ps), $channel));
}
$fp = $this->_openPackageFile($package, 'r', $channel);
if ($fp === null) {
return null;
}
$rt = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
clearstatcache();
$this->_closePackageFile($fp);
$data = file_get_contents($this->_packageFileName($package, $channel));
set_magic_quotes_runtime($rt);
$data = unserialize($data);
if ($key === null) {
return $data;
}
// compatibility for package.xml version 2.0
if (isset($data['old'][$key])) {
return $data['old'][$key];
}
if (isset($data[$key])) {
return $data[$key];
}
return null;
}
// }}}
// {{{ _channelInfo()
/**
* @param string Channel name
* @param bool whether to strictly retrieve info of channels, not just aliases
* @return array|null
*/
function _channelInfo($channel, $noaliases = false)
{
if (!$this->_channelExists($channel, $noaliases)) {
return null;
}
$fp = $this->_openChannelFile($channel, 'r');
if ($fp === null) {
return null;
}
$rt = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
clearstatcache();
$this->_closeChannelFile($fp);
$data = file_get_contents($this->_channelFileName($channel));
set_magic_quotes_runtime($rt);
$data = unserialize($data);
return $data;
}
// }}}
// {{{ _listChannels()
function _listChannels()
{
$channellist = array();
if (!file_exists($this->channelsdir) || !is_dir($this->channelsdir)) {
return array('pear.php.net', 'pecl.php.net', '__uri');
}
$dp = opendir($this->channelsdir);
while ($ent = readdir($dp)) {
if ($ent{0} == '.' || substr($ent, -4) != '.reg') {
continue;
}
if ($ent == '__uri.reg') {
$channellist[] = '__uri';
continue;
}
$channellist[] = str_replace('_', '/', substr($ent, 0, -4));
}
closedir($dp);
if (!in_array('pear.php.net', $channellist)) {
$channellist[] = 'pear.php.net';
}
if (!in_array('pecl.php.net', $channellist)) {
$channellist[] = 'pecl.php.net';
}
if (!in_array('__uri', $channellist)) {
$channellist[] = '__uri';
}
natsort($channellist);
return $channellist;
}
// }}}
// {{{ _listPackages()
function _listPackages($channel = false)
{
if ($channel && $this->_getChannelFromAlias($channel) != 'pear.php.net') {
return $this->_listChannelPackages($channel);
}
if (!file_exists($this->statedir) || !is_dir($this->statedir)) {
return array();
}
$pkglist = array();
$dp = opendir($this->statedir);
if (!$dp) {
return $pkglist;
}
while ($ent = readdir($dp)) {
if ($ent{0} == '.' || substr($ent, -4) != '.reg') {
continue;
}
$pkglist[] = substr($ent, 0, -4);
}
closedir($dp);
return $pkglist;
}
// }}}
// {{{ _listChannelPackages()
function _listChannelPackages($channel)
{
$pkglist = array();
if (!file_exists($this->_channelDirectoryName($channel)) ||
!is_dir($this->_channelDirectoryName($channel))) {
return array();
}
$dp = opendir($this->_channelDirectoryName($channel));
if (!$dp) {
return $pkglist;
}
while ($ent = readdir($dp)) {
if ($ent{0} == '.' || substr($ent, -4) != '.reg') {
continue;
}
$pkglist[] = substr($ent, 0, -4);
}
closedir($dp);
return $pkglist;
}
// }}}
function _listAllPackages()
{
$ret = array();
foreach ($this->_listChannels() as $channel) {
$ret[$channel] = $this->_listPackages($channel);
}
return $ret;
}
/**
* Add an installed package to the registry
* @param string package name
* @param array package info (parsed by PEAR_Common::infoFrom*() methods)
* @return bool success of saving
* @access private
*/
function _addPackage($package, $info)
{
if ($this->_packageExists($package)) {
return false;
}
$fp = $this->_openPackageFile($package, 'wb');
if ($fp === null) {
return false;
}
$info['_lastmodified'] = time();
fwrite($fp, serialize($info));
$this->_closePackageFile($fp);
if (isset($info['filelist'])) {
$this->_rebuildFileMap();
}
return true;
}
/**
* @param PEAR_PackageFile_v1|PEAR_PackageFile_v2
* @return bool
* @access private
*/
function _addPackage2($info)
{
if (!is_a($info, 'PEAR_PackageFile_v1') && !is_a($info, 'PEAR_PackageFile_v2')) {
return false;
}
if (!$info->validate()) {
if (class_exists('PEAR_Common')) {
$ui = PEAR_Frontend::singleton();
if ($ui) {
foreach ($info->getValidationWarnings() as $err) {
$ui->log($err['message'], true);
}
}
}
return false;
}
$channel = $info->getChannel();
$package = $info->getPackage();
$save = $info;
if ($this->_packageExists($package, $channel)) {
return false;
}
if (!$this->_channelExists($channel, true)) {
return false;
}
$info = $info->toArray(true);
if (!$info) {
return false;
}
$fp = $this->_openPackageFile($package, 'wb', $channel);
if ($fp === null) {
return false;
}
$info['_lastmodified'] = time();
fwrite($fp, serialize($info));
$this->_closePackageFile($fp);
$this->_rebuildFileMap();
return true;
}
/**
* @param string Package name
* @param array parsed package.xml 1.0
* @param bool this parameter is only here for BC. Don't use it.
* @access private
*/
function _updatePackage($package, $info, $merge = true)
{
$oldinfo = $this->_packageInfo($package);
if (empty($oldinfo)) {
return false;
}
$fp = $this->_openPackageFile($package, 'w');
if ($fp === null) {
return false;
}
if (is_object($info)) {
$info = $info->toArray();
}
$info['_lastmodified'] = time();
$newinfo = $info;
if ($merge) {
$info = array_merge($oldinfo, $info);
} else {
$diff = $info;
}
fwrite($fp, serialize($info));
$this->_closePackageFile($fp);
if (isset($newinfo['filelist'])) {
$this->_rebuildFileMap();
}
return true;
}
/**
* @param PEAR_PackageFile_v1|PEAR_PackageFile_v2
* @return bool
* @access private
*/
function _updatePackage2($info)
{
if (!$this->_packageExists($info->getPackage(), $info->getChannel())) {
return false;
}
$fp = $this->_openPackageFile($info->getPackage(), 'w', $info->getChannel());
if ($fp === null) {
return false;
}
$save = $info;
$info = $save->getArray(true);
$info['_lastmodified'] = time();
fwrite($fp, serialize($info));
$this->_closePackageFile($fp);
$this->_rebuildFileMap();
return true;
}
/**
* @param string Package name
* @param string Channel name
* @return PEAR_PackageFile_v1|PEAR_PackageFile_v2|null
* @access private
*/
function &_getPackage($package, $channel = 'pear.php.net')
{
$info = $this->_packageInfo($package, null, $channel);
if ($info === null) {
return $info;
}
$a = $this->_config;
if (!$a) {
$this->_config = &new PEAR_Config;
$this->_config->set('php_dir', $this->statedir);
}
if (!class_exists('PEAR_PackageFile')) {
require_once 'PEAR/PackageFile.php';
}
$pkg = &new PEAR_PackageFile($this->_config);
$pf = &$pkg->fromArray($info);
return $pf;
}
/**
* @param string channel name
* @param bool whether to strictly retrieve channel names
* @return PEAR_ChannelFile|PEAR_Error
* @access private
*/
function &_getChannel($channel, $noaliases = false)
{
$ch = false;
if ($this->_channelExists($channel, $noaliases)) {
$chinfo = $this->_channelInfo($channel, $noaliases);
if ($chinfo) {
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$ch = &PEAR_ChannelFile::fromArrayWithErrors($chinfo);
}
}
if ($ch) {
if ($ch->validate()) {
return $ch;
}
foreach ($ch->getErrors(true) as $err) {
$message = $err['message'] . "\n";
}
$ch = PEAR::raiseError($message);
return $ch;
}
if ($this->_getChannelFromAlias($channel) == 'pear.php.net') {
// the registry is not properly set up, so use defaults
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$pear_channel = new PEAR_ChannelFile;
$pear_channel->setName('pear.php.net');
$pear_channel->setAlias('pear');
$pear_channel->setSummary('PHP Extension and Application Repository');
$pear_channel->setDefaultPEARProtocols();
$pear_channel->setBaseURL('REST1.0', 'http://pear.php.net/rest/');
$pear_channel->setBaseURL('REST1.1', 'http://pear.php.net/rest/');
return $pear_channel;
}
if ($this->_getChannelFromAlias($channel) == 'pecl.php.net') {
// the registry is not properly set up, so use defaults
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$pear_channel = new PEAR_ChannelFile;
$pear_channel->setName('pecl.php.net');
$pear_channel->setAlias('pecl');
$pear_channel->setSummary('PHP Extension Community Library');
$pear_channel->setDefaultPEARProtocols();
$pear_channel->setBaseURL('REST1.0', 'http://pecl.php.net/rest/');
$pear_channel->setBaseURL('REST1.1', 'http://pecl.php.net/rest/');
$pear_channel->setValidationPackage('PEAR_Validator_PECL', '1.0');
return $pear_channel;
}
if ($this->_getChannelFromAlias($channel) == '__uri') {
// the registry is not properly set up, so use defaults
if (!class_exists('PEAR_ChannelFile')) {
require_once 'PEAR/ChannelFile.php';
}
$private = new PEAR_ChannelFile;
$private->setName('__uri');
$private->addFunction('xmlrpc', '1.0', '****');
$private->setSummary('Pseudo-channel for static packages');
return $private;
}
return $ch;
}
// {{{ packageExists()
/**
* @param string Package name
* @param string Channel name
* @return bool
*/
function packageExists($package, $channel = 'pear.php.net')
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_packageExists($package, $channel);
$this->_unlock();
return $ret;
}
// }}}
// {{{ channelExists()
/**
* @param string channel name
* @param bool if true, then aliases will be ignored
* @return bool
*/
function channelExists($channel, $noaliases = false)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_channelExists($channel, $noaliases);
$this->_unlock();
return $ret;
}
// }}}
// {{{ isAlias()
/**
* Determines whether the parameter is an alias of a channel
* @param string
* @return bool
*/
function isAlias($alias)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_isChannelAlias($alias);
$this->_unlock();
return $ret;
}
// }}}
// {{{ packageInfo()
/**
* @param string|null
* @param string|null
* @param string
* @return array|null
*/
function packageInfo($package = null, $key = null, $channel = 'pear.php.net')
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_packageInfo($package, $key, $channel);
$this->_unlock();
return $ret;
}
// }}}
// {{{ channelInfo()
/**
* Retrieve a raw array of channel data.
*
* Do not use this, instead use {@link getChannel()} for normal
* operations. Array structure is undefined in this method
* @param string channel name
* @param bool whether to strictly retrieve information only on non-aliases
* @return array|null|PEAR_Error
*/
function channelInfo($channel = null, $noaliases = false)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_channelInfo($channel, $noaliases);
$this->_unlock();
return $ret;
}
// }}}
/**
* @param string
*/
function channelName($channel)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_getChannelFromAlias($channel);
$this->_unlock();
return $ret;
}
/**
* @param string
*/
function channelAlias($channel)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_getAlias($channel);
$this->_unlock();
return $ret;
}
// {{{ listPackages()
function listPackages($channel = false)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_listPackages($channel);
$this->_unlock();
return $ret;
}
// }}}
// {{{ listAllPackages()
function listAllPackages()
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_listAllPackages();
$this->_unlock();
return $ret;
}
// }}}
// {{{ listChannel()
function listChannels()
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = $this->_listChannels();
$this->_unlock();
return $ret;
}
// }}}
// {{{ addPackage()
/**
* Add an installed package to the registry
* @param string|PEAR_PackageFile_v1|PEAR_PackageFile_v2 package name or object
* that will be passed to {@link addPackage2()}
* @param array package info (parsed by PEAR_Common::infoFrom*() methods)
* @return bool success of saving
*/
function addPackage($package, $info)
{
if (is_object($info)) {
return $this->addPackage2($info);
}
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$ret = $this->_addPackage($package, $info);
$this->_unlock();
if ($ret) {
if (!class_exists('PEAR_PackageFile_v1')) {
require_once 'PEAR/PackageFile/v1.php';
}
$pf = new PEAR_PackageFile_v1;
$pf->setConfig($this->_config);
$pf->fromArray($info);
$this->_dependencyDB->uninstallPackage($pf);
$this->_dependencyDB->installPackage($pf);
}
return $ret;
}
// }}}
// {{{ addPackage2()
function addPackage2($info)
{
if (!is_object($info)) {
return $this->addPackage($info['package'], $info);
}
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$ret = $this->_addPackage2($info);
$this->_unlock();
if ($ret) {
$this->_dependencyDB->uninstallPackage($info);
$this->_dependencyDB->installPackage($info);
}
return $ret;
}
// }}}
// {{{ updateChannel()
/**
* For future expandibility purposes, separate this
* @param PEAR_ChannelFile
*/
function updateChannel($channel, $lastmodified = null)
{
if ($channel->getName() == '__uri') {
return false;
}
return $this->addChannel($channel, $lastmodified, true);
}
// }}}
// {{{ deleteChannel()
/**
* Deletion fails if there are any packages installed from the channel
* @param string|PEAR_ChannelFile channel name
* @return boolean|PEAR_Error True on deletion, false if it doesn't exist
*/
function deleteChannel($channel)
{
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$ret = $this->_deleteChannel($channel);
$this->_unlock();
if ($ret && is_a($this->_config, 'PEAR_Config')) {
$this->_config->setChannels($this->listChannels());
}
return $ret;
}
// }}}
// {{{ addChannel()
/**
* @param PEAR_ChannelFile Channel object
* @param string Last-Modified header from HTTP for caching
* @return boolean|PEAR_Error True on creation, false if it already exists
*/
function addChannel($channel, $lastmodified = false, $update = false)
{
if (!is_a($channel, 'PEAR_ChannelFile')) {
return false;
}
if (!$channel->validate()) {
return false;
}
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$ret = $this->_addChannel($channel, $update, $lastmodified);
$this->_unlock();
if (!$update && $ret && is_a($this->_config, 'PEAR_Config')) {
$this->_config->setChannels($this->listChannels());
}
return $ret;
}
// }}}
// {{{ deletePackage()
function deletePackage($package, $channel = 'pear.php.net')
{
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$file = $this->_packageFileName($package, $channel);
if (file_exists($file)) {
$ret = @unlink($file);
} else {
$ret = false;
}
$this->_rebuildFileMap();
$this->_unlock();
$p = array('channel' => $channel, 'package' => $package);
$this->_dependencyDB->uninstallPackage($p);
return $ret;
}
// }}}
// {{{ updatePackage()
function updatePackage($package, $info, $merge = true)
{
if (is_object($info)) {
return $this->updatePackage2($info, $merge);
}
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$ret = $this->_updatePackage($package, $info, $merge);
$this->_unlock();
if ($ret) {
if (!class_exists('PEAR_PackageFile_v1')) {
require_once 'PEAR/PackageFile/v1.php';
}
$pf = new PEAR_PackageFile_v1;
$pf->setConfig($this->_config);
$pf->fromArray($this->packageInfo($package));
$this->_dependencyDB->uninstallPackage($pf);
$this->_dependencyDB->installPackage($pf);
}
return $ret;
}
// }}}
// {{{ updatePackage2()
function updatePackage2($info)
{
if (!is_object($info)) {
return $this->updatePackage($info['package'], $info, $merge);
}
if (!$info->validate(PEAR_VALIDATE_DOWNLOADING)) {
return false;
}
if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
return $e;
}
$ret = $this->_updatePackage2($info);
$this->_unlock();
if ($ret) {
$this->_dependencyDB->uninstallPackage($info);
$this->_dependencyDB->installPackage($info);
}
return $ret;
}
// }}}
// {{{ getChannel()
/**
* @param string channel name
* @param bool whether to strictly return raw channels (no aliases)
* @return PEAR_ChannelFile|PEAR_Error
*/
function &getChannel($channel, $noaliases = false)
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$ret = &$this->_getChannel($channel, $noaliases);
if (!$ret) {
return PEAR::raiseError('Unknown channel: ' . $channel);
}
$this->_unlock();
return $ret;
}
// }}}
// {{{ getPackage()
/**
* @param string package name
* @param string channel name
* @return PEAR_PackageFile_v1|PEAR_PackageFile_v2|null
*/
function &getPackage($package, $channel = 'pear.php.net')
{
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$pf = &$this->_getPackage($package, $channel);
$this->_unlock();
return $pf;
}
// }}}
/**
* Get PEAR_PackageFile_v[1/2] objects representing the contents of
* a dependency group that are installed.
*
* This is used at uninstall-time
* @param array
* @return array|false
*/
function getInstalledGroup($group)
{
$ret = array();
if (isset($group['package'])) {
if (!isset($group['package'][0])) {
$group['package'] = array($group['package']);
}
foreach ($group['package'] as $package) {
$depchannel = isset($package['channel']) ? $package['channel'] : '__uri';
$p = &$this->getPackage($package['name'], $depchannel);
if ($p) {
$save = &$p;
$ret[] = &$save;
}
}
}
if (isset($group['subpackage'])) {
if (!isset($group['subpackage'][0])) {
$group['subpackage'] = array($group['subpackage']);
}
foreach ($group['subpackage'] as $package) {
$depchannel = isset($package['channel']) ? $package['channel'] : '__uri';
$p = &$this->getPackage($package['name'], $depchannel);
if ($p) {
$save = &$p;
$ret[] = &$save;
}
}
}
if (!count($ret)) {
return false;
}
return $ret;
}
// {{{ getChannelValidator()
/**
* @param string channel name
* @return PEAR_Validate|false
*/
function &getChannelValidator($channel)
{
$chan = $this->getChannel($channel);
if (PEAR::isError($chan)) {
return $chan;
}
$val = $chan->getValidationObject();
return $val;
}
// }}}
// {{{ getChannels()
/**
* @param string channel name
* @return array an array of PEAR_ChannelFile objects representing every installed channel
*/
function &getChannels()
{
$ret = array();
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
foreach ($this->_listChannels() as $channel) {
$e = &$this->_getChannel($channel);
if (!$e || PEAR::isError($e)) {
continue;
}
$ret[] = $e;
}
$this->_unlock();
return $ret;
}
// }}}
// {{{ checkFileMap()
/**
* Test whether a file or set of files belongs to a package.
*
* If an array is passed in
* @param string|array file path, absolute or relative to the pear
* install dir
* @param string|array name of PEAR package or array('package' => name, 'channel' =>
* channel) of a package that will be ignored
* @param string API version - 1.1 will exclude any files belonging to a package
* @param array private recursion variable
* @return array|false which package and channel the file belongs to, or an empty
* string if the file does not belong to an installed package,
* or belongs to the second parameter's package
*/
function checkFileMap($path, $package = false, $api = '1.0', $attrs = false)
{
if (is_array($path)) {
static $notempty;
if (empty($notempty)) {
if (!class_exists('PEAR_Installer_Role')) {
require_once 'PEAR/Installer/Role.php';
}
$notempty = create_function('$a','return !empty($a);');
}
$package = is_array($package) ? array(strtolower($package[0]), strtolower($package[1]))
: strtolower($package);
$pkgs = array();
foreach ($path as $name => $attrs) {
if (is_array($attrs)) {
if (isset($attrs['install-as'])) {
$name = $attrs['install-as'];
}
if (!in_array($attrs['role'], PEAR_Installer_Role::getInstallableRoles())) {
// these are not installed
continue;
}
if (!in_array($attrs['role'], PEAR_Installer_Role::getBaseinstallRoles())) {
$attrs['baseinstalldir'] = is_array($package) ? $package[1] : $package;
}
if (isset($attrs['baseinstalldir'])) {
$name = $attrs['baseinstalldir'] . DIRECTORY_SEPARATOR . $name;
}
}
$pkgs[$name] = $this->checkFileMap($name, $package, $api, $attrs);
if (PEAR::isError($pkgs[$name])) {
return $pkgs[$name];
}
}
return array_filter($pkgs, $notempty);
}
if (empty($this->filemap_cache)) {
if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
return $e;
}
$err = $this->_readFileMap();
$this->_unlock();
if (PEAR::isError($err)) {
return $err;
}
}
if (!$attrs) {
$attrs = array('role' => 'php'); // any old call would be for PHP role only
}
if (isset($this->filemap_cache[$attrs['role']][$path])) {
if ($api >= '1.1' && $this->filemap_cache[$attrs['role']][$path] == $package) {
return false;
}
return $this->filemap_cache[$attrs['role']][$path];
}
$l = strlen($this->install_dir);
if (substr($path, 0, $l) == $this->install_dir) {
$path = preg_replace('!^'.DIRECTORY_SEPARATOR.'+!', '', substr($path, $l));
}
if (isset($this->filemap_cache[$attrs['role']][$path])) {
if ($api >= '1.1' && $this->filemap_cache[$attrs['role']][$path] == $package) {
return false;
}
return $this->filemap_cache[$attrs['role']][$path];
}
return false;
}
// }}}
// {{{ flush()
/**
* Force a reload of the filemap
* @since 1.5.0RC3
*/
function flushFileMap()
{
$this->filemap_cache = null;
clearstatcache(); // ensure that the next read gets the full, current filemap
}
// }}}
// {{{ apiVersion()
/**
* Get the expected API version. Channels API is version 1.1, as it is backwards
* compatible with 1.0
* @return string
*/
function apiVersion()
{
return '1.1';
}
// }}}
/**
* Parse a package name, or validate a parsed package name array
* @param string|array pass in an array of format
* array(
* 'package' => 'pname',
* ['channel' => 'channame',]
* ['version' => 'version',]
* ['state' => 'state',]
* ['group' => 'groupname'])
* or a string of format
* [channel://][channame/]pname[-version|-state][/group=groupname]
* @return array|PEAR_Error
*/
function parsePackageName($param, $defaultchannel = 'pear.php.net')
{
$saveparam = $param;
if (is_array($param)) {
// convert to string for error messages
$saveparam = $this->parsedPackageNameToString($param);
// process the array
if (!isset($param['package'])) {
return PEAR::raiseError('parsePackageName(): array $param ' .
'must contain a valid package name in index "param"',
'package', null, null, $param);
}
if (!isset($param['uri'])) {
if (!isset($param['channel'])) {
$param['channel'] = $defaultchannel;
}
} else {
$param['channel'] = '__uri';
}
} else {
$components = @parse_url((string) $param);
if (isset($components['scheme'])) {
if ($components['scheme'] == 'http') {
// uri package
$param = array('uri' => $param, 'channel' => '__uri');
} elseif($components['scheme'] != 'channel') {
return PEAR::raiseError('parsePackageName(): only channel:// uris may ' .
'be downloaded, not "' . $param . '"', 'invalid', null, null, $param);
}
}
if (!isset($components['path'])) {
return PEAR::raiseError('parsePackageName(): array $param ' .
'must contain a valid package name in "' . $param . '"',
'package', null, null, $param);
}
if (isset($components['host'])) {
// remove the leading "/"
$components['path'] = substr($components['path'], 1);
}
if (!isset($components['scheme'])) {
if (strpos($components['path'], '/') !== false) {
if ($components['path']{0} == '/') {
return PEAR::raiseError('parsePackageName(): this is not ' .
'a package name, it begins with "/" in "' . $param . '"',
'invalid', null, null, $param);
}
$parts = explode('/', $components['path']);
$components['host'] = array_shift($parts);
if (count($parts) > 1) {
$components['path'] = array_pop($parts);
$components['host'] .= '/' . implode('/', $parts);
} else {
$components['path'] = implode('/', $parts);
}
} else {
$components['host'] = $defaultchannel;
}
} else {
if (strpos($components['path'], '/')) {
$parts = explode('/', $components['path']);
$components['path'] = array_pop($parts);
$components['host'] .= '/' . implode('/', $parts);
}
}
if (is_array($param)) {
$param['package'] = $components['path'];
} else {
$param = array(
'package' => $components['path']
);
if (isset($components['host'])) {
$param['channel'] = $components['host'];
}
}
if (isset($components['fragment'])) {
$param['group'] = $components['fragment'];
}
if (isset($components['user'])) {
$param['user'] = $components['user'];
}
if (isset($components['pass'])) {
$param['pass'] = $components['pass'];
}
if (isset($components['query'])) {
parse_str($components['query'], $param['opts']);
}
// check for extension
$pathinfo = pathinfo($param['package']);
if (isset($pathinfo['extension']) &&
in_array(strtolower($pathinfo['extension']), array('tgz', 'tar'))) {
$param['extension'] = $pathinfo['extension'];
$param['package'] = substr($pathinfo['basename'], 0,
strlen($pathinfo['basename']) - 4);
}
// check for version
if (strpos($param['package'], '-')) {
$test = explode('-', $param['package']);
if (count($test) != 2) {
return PEAR::raiseError('parsePackageName(): only one version/state ' .
'delimiter "-" is allowed in "' . $saveparam . '"',
'version', null, null, $param);
}
list($param['package'], $param['version']) = $test;
}
}
// validation
$info = $this->channelExists($param['channel']);
if (PEAR::isError($info)) {
return $info;
}
if (!$info) {
return PEAR::raiseError('unknown channel "' . $param['channel'] .
'" in "' . $saveparam . '"', 'channel', null, null, $param);
}
$chan = $this->getChannel($param['channel']);
if (PEAR::isError($chan)) {
return $chan;
}
if (!$chan) {
return PEAR::raiseError("Exception: corrupt registry, could not " .
"retrieve channel " . $param['channel'] . " information",
'registry', null, null, $param);
}
$param['channel'] = $chan->getName();
$validate = $chan->getValidationObject();
$vpackage = $chan->getValidationPackage();
// validate package name
if (!$validate->validPackageName($param['package'], $vpackage['_content'])) {
return PEAR::raiseError('parsePackageName(): invalid package name "' .
$param['package'] . '" in "' . $saveparam . '"',
'package', null, null, $param);
}
if (isset($param['group'])) {
if (!PEAR_Validate::validGroupName($param['group'])) {
return PEAR::raiseError('parsePackageName(): dependency group "' . $param['group'] .
'" is not a valid group name in "' . $saveparam . '"', 'group', null, null,
$param);
}
}
if (isset($param['state'])) {
if (!in_array(strtolower($param['state']), $validate->getValidStates())) {
return PEAR::raiseError('parsePackageName(): state "' . $param['state']
. '" is not a valid state in "' . $saveparam . '"',
'state', null, null, $param);
}
}
if (isset($param['version'])) {
if (isset($param['state'])) {
return PEAR::raiseError('parsePackageName(): cannot contain both ' .
'a version and a stability (state) in "' . $saveparam . '"',
'version/state', null, null, $param);
}
// check whether version is actually a state
if (in_array(strtolower($param['version']), $validate->getValidStates())) {
$param['state'] = strtolower($param['version']);
unset($param['version']);
} else {
if (!$validate->validVersion($param['version'])) {
return PEAR::raiseError('parsePackageName(): "' . $param['version'] .
'" is neither a valid version nor a valid state in "' .
$saveparam . '"', 'version/state', null, null, $param);
}
}
}
return $param;
}
/**
* @param array
* @return string
*/
function parsedPackageNameToString($parsed, $brief = false)
{
if (is_string($parsed)) {
return $parsed;
}
if (is_object($parsed)) {
$p = $parsed;
$parsed = array(
'package' => $p->getPackage(),
'channel' => $p->getChannel(),
'version' => $p->getVersion(),
);
}
if (isset($parsed['uri'])) {
return $parsed['uri'];
}
if ($brief) {
if ($channel = $this->channelAlias($parsed['channel'])) {
return $channel . '/' . $parsed['package'];
}
}
$upass = '';
if (isset($parsed['user'])) {
$upass = $parsed['user'];
if (isset($parsed['pass'])) {
$upass .= ':' . $parsed['pass'];
}
$upass = "$upass@";
}
$ret = 'channel://' . $upass . $parsed['channel'] . '/' . $parsed['package'];
if (isset($parsed['version']) || isset($parsed['state'])) {
$ver = isset($parsed['version']) ? $parsed['version'] : '';
$ver .= isset($parsed['state']) ? $parsed['state'] : '';
$ret .= '-' . $ver;
}
if (isset($parsed['extension'])) {
$ret .= '.' . $parsed['extension'];
}
if (isset($parsed['opts'])) {
$ret .= '?';
foreach ($parsed['opts'] as $name => $value) {
$parsed['opts'][$name] = "$name=$value";
}
$ret .= implode('&', $parsed['opts']);
}
if (isset($parsed['group'])) {
$ret .= '#' . $parsed['group'];
}
return $ret;
}
}
?>
| lgpl-2.1 |
cejug/yougi | java/src/main/java/org/cejug/yougi/knowledge/web/controller/MailingListMBean.java | 2800 | /* Yougi is a web application conceived to manage user groups or
* communities focused on a certain domain of knowledge, whose members are
* constantly sharing information and participating in social and educational
* events. Copyright (C) 2011 Hildeberto Mendonça.
*
* This application 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 application 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.
*
* There is a full copy of the GNU Lesser General Public License along with
* this library. Look for the file license.txt at the root level. If you do not
* find it, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA.
* */
package org.cejug.yougi.knowledge.web.controller;
import org.cejug.yougi.knowledge.entity.MailingList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import java.util.List;
/**
* @author Hildeberto Mendonca - http://www.hildeberto.com
*/
@ManagedBean
@RequestScoped
public class MailingListMBean {
@EJB
private org.cejug.yougi.knowledge.business.MailingListBean mailingListBean;
@ManagedProperty(value="#{param.id}")
private String id;
private MailingList mailingList;
private List<MailingList> mailingLists;
public MailingListMBean() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public MailingList getMailingList() {
return mailingList;
}
public void setMailingList(MailingList mailingList) {
this.mailingList = mailingList;
}
public List<MailingList> getMailingLists() {
if(this.mailingLists == null) {
this.mailingLists = mailingListBean.findMailingLists();
}
return this.mailingLists;
}
@PostConstruct
public void load() {
if(id != null && !id.isEmpty()) {
this.mailingList = mailingListBean.find(id);
} else {
this.mailingList = new MailingList();
}
}
public String save() {
mailingListBean.save(this.mailingList);
return "mailing_lists?faces-redirect=true";
}
public String remove() {
mailingListBean.remove(this.mailingList.getId());
return "mailing_lists?faces-redirect=true";
}
} | lgpl-2.1 |
sbonoc/opencms-core | src/org/opencms/xml/containerpage/CmsContainerBean.java | 7760 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.xml.containerpage;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.Transformer;
/**
* One container of a container page.<p>
*
* @since 8.0
*/
public class CmsContainerBean {
/** A lazy initialized map that describes if a certain element if part of this container. */
private transient Map<CmsUUID, Boolean> m_containsElement;
/** Flag indicating this container is used on detail pages only. */
private boolean m_detailOnly;
/** The id's of of all elements in this container. */
private transient List<CmsUUID> m_elementIds;
/** The container elements. */
private final List<CmsContainerElementBean> m_elements;
/** The maximal number of elements in the container. */
private int m_maxElements;
/** The container name. */
private final String m_name;
/** The parent element instance id. */
private String m_parentInstanceId;
/** The container type. */
private String m_type;
/** The container width set by the rendering container tag. */
private String m_width;
/**
* Creates a new container bean.<p>
*
* @param name the container name
* @param type the container type
* @param parentInstanceId the parent instance id
* @param maxElements the maximal number of elements in the container
* @param elements the elements
**/
public CmsContainerBean(
String name,
String type,
String parentInstanceId,
int maxElements,
List<CmsContainerElementBean> elements) {
m_name = name;
m_type = type;
m_parentInstanceId = parentInstanceId;
m_maxElements = maxElements;
m_elements = (elements == null
? Collections.<CmsContainerElementBean> emptyList()
: Collections.unmodifiableList(elements));
}
/**
* Creates a new container bean with an unlimited number of elements.<p>
*
* @param name the container name
* @param type the container type
* @param parentInstanceId the parent instance id
* @param elements the elements
**/
public CmsContainerBean(String name, String type, String parentInstanceId, List<CmsContainerElementBean> elements) {
this(name, type, parentInstanceId, -1, elements);
}
/**
* Returns <code>true</code> if the element with the provided id is contained in this container.<p>
*
* @param elementId the element id to check
*
* @return <code>true</code> if the element with the provided id is contained in this container
*/
public boolean containsElement(CmsUUID elementId) {
return getElementIds().contains(elementId);
}
/**
* Returns a lazy initialized map that describes if a certain element if part of this container.<p>
*
* @return a lazy initialized map that describes if a certain element if part of this container
*/
public Map<CmsUUID, Boolean> getContainsElement() {
if (m_containsElement == null) {
m_containsElement = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object input) {
return Boolean.valueOf(containsElement((CmsUUID)input));
}
});
}
return m_containsElement;
}
/**
* Returns the id's of all elements in this container.<p>
*
* @return the id's of all elements in this container
*/
public List<CmsUUID> getElementIds() {
if (m_elementIds == null) {
m_elementIds = new ArrayList<CmsUUID>(m_elements.size());
for (CmsContainerElementBean element : m_elements) {
m_elementIds.add(element.getId());
}
}
return m_elementIds;
}
/**
* Returns the elements in this container.<p>
*
* @return the elements in this container
*/
public List<CmsContainerElementBean> getElements() {
return m_elements;
}
/**
* Returns the maximal number of elements in this container.<p>
*
* @return the maximal number of elements in this container
*/
public int getMaxElements() {
return m_maxElements;
}
/**
* Returns the name of this container.<p>
*
* @return the name of this container
*/
public String getName() {
return m_name;
}
/**
* Returns the the parent instance id.<p>
*
* @return the parent instance id
*/
public String getParentInstanceId() {
return m_parentInstanceId;
}
/**
* Returns the type of this container.<p>
*
* @return the type of this container
*/
public String getType() {
return m_type;
}
/**
* Returns the container width set by the rendering container tag.<p>
*
* @return the container width
*/
public String getWidth() {
return m_width;
}
/**
* Returns if this container is used on detail pages only.<p>
*
* @return <code>true</code> if this container is used on detail pages only
*/
public boolean isDetailOnly() {
return m_detailOnly;
}
/**
* Returns if the given container is a nested container.<p>
*
* @return <code>true</code> if the given container is a nested container
*/
public boolean isNestedContainer() {
return CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_parentInstanceId);
}
/**
* Sets if this container is used on detail pages only.<p>
*
* @param detailOnly <code>true</code> if this container is used on detail pages only
*/
public void setDetailOnly(boolean detailOnly) {
m_detailOnly = detailOnly;
}
/**
* Sets the maximal number of elements in the container.<p>
*
* @param maxElements the maximal number of elements to set
*/
public void setMaxElements(int maxElements) {
m_maxElements = maxElements;
}
/**
* Sets the container type.<p>
*
* @param type the container type
*/
public void setType(String type) {
m_type = type;
}
/**
* Sets the client side render with of this container.<p>
*
* @param width the client side render with of this container
*/
public void setWidth(String width) {
m_width = width;
}
}
| lgpl-2.1 |
KDE/android-qt-creator | src/libs/utils/fileinprojectfinder.cpp | 8744 | /**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "fileinprojectfinder.h"
#include <utils/qtcassert.h>
#include <QDebug>
#include <QFileInfo>
#include <QUrl>
enum { debug = false };
namespace Utils {
/*!
\class Utils::FileInProjectFinder
\brief Helper class to find the 'original' file in the project directory for a given file url.
Often files are copied in the build + deploy process. findFile() searches for an existing file
in the project directory for a given file path:
E.g. following file paths:
\list
\i C:/app-build-desktop/qml/app/main.qml (shadow build directory)
\i C:/Private/e3026d63/qml/app/main.qml (Application data folder on Symbian device)
\i /Users/x/app-build-desktop/App.app/Contents/Resources/qml/App/main.qml (folder on Mac OS X)
\endlist
should all be mapped to $PROJECTDIR/qml/app/main.qml
*/
FileInProjectFinder::FileInProjectFinder()
{
}
static QString stripTrailingSlashes(const QString &path)
{
QString newPath = path;
while (newPath.endsWith(QLatin1Char('/')))
newPath.remove(newPath.length() - 1, 1);
return newPath;
}
void FileInProjectFinder::setProjectDirectory(const QString &absoluteProjectPath)
{
const QString newProjectPath = stripTrailingSlashes(absoluteProjectPath);
if (newProjectPath == m_projectDir)
return;
const QFileInfo infoPath(newProjectPath);
QTC_CHECK(newProjectPath.isEmpty()
|| (infoPath.exists() && infoPath.isAbsolute()));
m_projectDir = newProjectPath;
m_cache.clear();
}
QString FileInProjectFinder::projectDirectory() const
{
return m_projectDir;
}
void FileInProjectFinder::setProjectFiles(const QStringList &projectFiles)
{
if (m_projectFiles == projectFiles)
return;
m_projectFiles = projectFiles;
m_cache.clear();
}
void FileInProjectFinder::setSysroot(const QString &sysroot)
{
QString newsys = sysroot;
while (newsys.endsWith(QLatin1Char('/')))
newsys.remove(newsys.length() - 1, 1);
if (m_sysroot == newsys)
return;
m_sysroot = newsys;
m_cache.clear();
}
/**
Returns the best match for the given file url in the project directory.
The method first checks whether the file inside the project directory exists.
If not, the leading directory in the path is stripped, and the - now shorter - path is
checked for existence, and so on. Second, it tries to locate the file in the sysroot
folder specified. Third, we walk the list of project files, and search for a file name match
there. If all fails, it returns the original path from the file url.
*/
QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const
{
if (debug)
qDebug() << "FileInProjectFinder: trying to find file" << fileUrl.toString() << "...";
QString originalPath = fileUrl.toLocalFile();
if (originalPath.isEmpty()) // e.g. qrc://
originalPath = fileUrl.path();
if (originalPath.isEmpty()) {
if (debug)
qDebug() << "FileInProjectFinder: malformed url, returning";
if (success)
*success = false;
return originalPath;
}
if (!m_projectDir.isEmpty()) {
if (debug)
qDebug() << "FileInProjectFinder: checking project directory ...";
int prefixToIgnore = -1;
const QChar separator = QLatin1Char('/');
if (originalPath.startsWith(m_projectDir + separator)) {
#ifdef Q_OS_MAC
// starting with the project path is not sufficient if the file was
// copied in an insource build, e.g. into MyApp.app/Contents/Resources
static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources");
if (originalPath.contains(appResourcePath)) {
// the path is inside the project, but most probably as a resource of an insource build
// so ignore that path
prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length();
} else {
#endif
if (debug)
qDebug() << "FileInProjectFinder: found" << originalPath << "in project directory";
if (success)
*success = true;
return originalPath;
#ifdef Q_OS_MAC
}
#endif
}
if (m_cache.contains(originalPath)) {
if (debug)
qDebug() << "FileInProjectFinder: checking cache ...";
// check if cached path is still there
QString candidate = m_cache.value(originalPath);
QFileInfo candidateInfo(candidate);
if (candidateInfo.exists() && candidateInfo.isFile()) {
if (success)
*success = true;
if (debug)
qDebug() << "FileInProjectFinder: found" << candidate << "in the cache";
return candidate;
}
}
if (debug)
qDebug() << "FileInProjectFinder: checking stripped paths in project directory ...";
// Strip directories one by one from the beginning of the path,
// and see if the new relative path exists in the build directory.
if (prefixToIgnore < 0) {
if (!QFileInfo(originalPath).isAbsolute()
&& !originalPath.startsWith(separator)) {
prefixToIgnore = 0;
} else {
prefixToIgnore = originalPath.indexOf(separator);
}
}
while (prefixToIgnore != -1) {
QString candidate = originalPath;
candidate.remove(0, prefixToIgnore);
candidate.prepend(m_projectDir);
QFileInfo candidateInfo(candidate);
if (candidateInfo.exists() && candidateInfo.isFile()) {
if (success)
*success = true;
if (debug)
qDebug() << "FileInProjectFinder: found" << candidate << "in project directory";
m_cache.insert(originalPath, candidate);
return candidate;
}
prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1);
}
}
// find (solely by filename) in project files
if (debug)
qDebug() << "FileInProjectFinder: checking project files ...";
const QString fileName = QFileInfo(originalPath).fileName();
foreach (const QString &f, m_projectFiles) {
if (QFileInfo(f).fileName() == fileName) {
m_cache.insert(originalPath, f);
if (success)
*success = true;
if (debug)
qDebug() << "FileInProjectFinder: found" << f << "in project files";
return f;
}
}
if (debug)
qDebug() << "FileInProjectFinder: checking absolute path in sysroot ...";
// check if absolute path is found in sysroot
if (!m_sysroot.isEmpty()) {
const QString sysrootPath = m_sysroot + originalPath;
if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) {
if (success)
*success = true;
m_cache.insert(originalPath, sysrootPath);
if (debug)
qDebug() << "FileInProjectFinder: found" << sysrootPath << "in sysroot";
return sysrootPath;
}
}
if (success)
*success = false;
if (debug)
qDebug() << "FileInProjectFinder: couldn't find file!";
return originalPath;
}
} // namespace Utils
| lgpl-2.1 |
tikiorg/tiki | lib/test/core/Event/CustomizerTest.php | 3885 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
class Tiki_Event_CustomizerTest extends PHPUnit_Framework_TestCase
{
private $manager;
private $runner;
private $called;
private $lastEvent;
private $lastArguments;
function setUp()
{
$this->called = 0;
$manager = $this->manager = new Tiki_Event_Manager;
$self = $this;
$this->runner = new Math_Formula_Runner(
[
function ($verb) use ($manager, $self) {
switch ($verb) {
case 'event-trigger':
return new Tiki_Event_Function_EventTrigger($manager);
case 'event-record':
return new Tiki_Event_Function_EventRecord($self);
}
},
'Math_Formula_Function_' => '',
'Tiki_Event_Function_' => '',
]
);
}
function testBindThroughCustomizedEventFilter()
{
$this->manager->bind('custom.event', [$this, 'callbackAdd']);
$customizer = new Tiki_Event_Customizer;
$customizer->addRule('tiki.trackeritem.save', '(event-trigger custom.event)');
$customizer->bind($this->manager, $this->runner);
$this->manager->trigger('tiki.trackeritem.save');
$this->assertEquals(1, $this->called);
}
function testPassCustomArguments()
{
$this->manager->bind('custom.event', [$this, 'callbackAdd']);
$customizer = new Tiki_Event_Customizer;
$customizer->addRule(
'tiki.trackeritem.save',
'(event-trigger custom.event
(map
(amount (add args.a args.b))
(test args.c)
))'
);
$customizer->bind($this->manager, $this->runner);
$this->manager->trigger(
'tiki.trackeritem.save',
[
'a' => 2,
'b' => 3,
'c' => 4,
]
);
$this->assertEquals(5, $this->called);
}
function testDirectArgumentRecording()
{
$customizer = new Tiki_Event_Customizer;
$customizer->addRule('tiki.trackeritem.save', '(event-record event args)');
$customizer->bind($this->manager, $this->runner);
$args = [
'a' => 2,
'b' => 3,
'c' => 4,
'EVENT_ID' => 1,
];
$this->manager->trigger('tiki.trackeritem.save', $args);
$this->assertEquals('tiki.trackeritem.save', $this->lastEvent);
$this->assertEquals($args, $this->lastArguments);
}
function testChainedArgumentRecording()
{
$customizer = new Tiki_Event_Customizer;
$customizer->addRule('tiki.trackeritem.save', '(event-record event args)');
$customizer->bind($this->manager, $this->runner);
$args = [
'a' => 2,
'b' => 3,
'c' => 4,
'EVENT_ID' => 1,
];
$this->manager->bind('tiki.trackeritem.update', 'tiki.trackeritem.save');
$this->manager->trigger('tiki.trackeritem.update', $args);
$this->assertEquals('tiki.trackeritem.update', $this->lastEvent);
$this->assertEquals($args, $this->lastArguments);
}
function testCustomEventRecording()
{
$customizer = new Tiki_Event_Customizer;
$customizer->addRule('custom.event', '(event-record event args)');
$customizer->addRule(
'tiki.trackeritem.save',
'(event-trigger custom.event
(map
(amount (add args.a args.b))
(test args.c)
))'
);
$customizer->bind($this->manager, $this->runner);
$this->manager->trigger(
'tiki.trackeritem.save',
[
'a' => 2,
'b' => 3,
'c' => 4,
]
);
$this->assertEquals('custom.event', $this->lastEvent);
$this->assertEquals(
[
'amount' => 5,
'test' => 4,
'EVENT_ID' => 2,
],
$this->lastArguments
);
}
function callbackAdd($arguments)
{
$this->called += isset($arguments['amount']) ? $arguments['amount'] : 1;
}
function callbackMultiply($arguments)
{
$this->called *= isset($arguments['amount']) ? $arguments['amount'] : 2;
}
function recordEvent($event, $arguments)
{
$this->lastEvent = $event;
$this->lastArguments = $arguments;
}
}
| lgpl-2.1 |
fjalvingh/domui | common/to.etc.alg/src/main/java/to/etc/csv/CSVRecordReader.java | 15481 | /*
* DomUI Java User Interface - shared code
* Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
*
* 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-1301 USA
*
* See the "sponsors" file for a list of supporters.
*
* The latest version of DomUI and related code, support and documentation
* can be found at http://www.domui.org/
* The contact for the project is Frits Jalvingh <[email protected]>.
*/
package to.etc.csv;
import java.io.*;
import java.util.*;
import to.etc.util.*;
/**
* Reads CSV files record by record, and implements the iLoadInputProvider interface
* to access the fields.
* Created on Oct 13, 2003
* @author jal
*/
public class CSVRecordReader implements iRecordReader {
/** The name for the input, for reporting pps. */
private String m_name;
/** The source thing to read the data from */
private Reader m_r;
private LineNumberReader m_line_r;
/** Current line # */
int m_lnr;
/** When T, whitespace between fields is skipped */
private boolean m_skip_ws = true;
/** The list of fields for the CURRENT record. */
private List<Field> m_fld_al = new ArrayList<Field>();
private List<String> m_fldsep_al = new ArrayList<String>();
/** All characters that are allowed as quote characters */
private StringBuffer m_quote_sb = new StringBuffer();
/** Ignore all quotes. */
private boolean m_ignoreQuotes = false;
/** When set, any quote is escaped by the backslash character (C mode). */
private boolean m_escapeBackslash = true;
/** When set quotes are escaped by repeating them (BASIC mode) */
private boolean m_escapeDupQuote = false;
/** If T, the first line is read as a set of field names. */
private boolean m_startWithFieldNames;
/** We can use a whitespace as separator. Signal this, otherwise it will be skipped as a whitespace. */
private boolean m_whitespaceSeparator;
/**
* When set this allows shitty escaping: when quotes are not followed by a field separator they
* are assumed to be within the field data.
*/
private boolean m_escapeBadly = false;
private class Field implements iInputField {
// int m_lpos;
int m_index;
String m_fldname;
String m_value;
int m_field_lnr;
public Field() {
}
public void setName(String name) {
m_fldname = name;
}
/**
* Return the real name of the field, or the numeric name.
* @see to.etc.csv.iInputField#getName()
*/
public String getName() {
if(m_fldname == null)
return "#" + m_index;
return m_fldname;
}
/**
*
* @see to.etc.csv.iInputField#getValue()
*/
public String getValue() {
return m_value;
}
/**
*
* @see to.etc.csv.iInputField#isEmpty()
*/
public boolean isEmpty() {
return m_value == null || m_lnr != m_field_lnr;
}
public void setValue(String s) {
m_field_lnr = m_lnr;
m_value = s;
}
}
public void open(Reader r, String name) throws Exception {
m_name = name;
m_lnr = 0;
m_r = r;
m_line_r = new LineNumberReader(m_r);
}
public void close() throws Exception {
m_line_r.close();
}
private void error(String s) throws IOException {
throw new IOException(m_name + "(" + m_lnr + ":" + m_ix + "): " + s);
}
public int getCurrentRecNr() {
return m_lnr;
}
public void setFieldSeparator(String sep) {
m_fldsep_al.clear();
m_fldsep_al.add(sep);
}
public void addFieldSeparator(String sep) {
// Check if we are dealing with a whitespace separator.
if(sep.length() == 1 && Character.isWhitespace(sep.charAt(0)))
setWhitespaceSeparator(true);
m_fldsep_al.add(sep);
}
/** When T, whitespace between fields is skipped */
public void setSkipWhitespace(boolean skip_ws) {
m_skip_ws = skip_ws;
}
public void setIgnoreQuotes(boolean ignoreQuotes) {
m_ignoreQuotes = ignoreQuotes;
}
public void setEscapeBackslash(boolean escapeBackslash) {
m_escapeBackslash = escapeBackslash;
}
public void setEscapeDupQuote(boolean escapeDupQuote) {
m_escapeDupQuote = escapeDupQuote;
}
public void setStartWithFieldNames(boolean startWithFieldNames) {
m_startWithFieldNames = startWithFieldNames;
}
public void setEscapeBadly(boolean escapeBadly) {
m_escapeBadly = escapeBadly;
}
private boolean _nextRecord() throws IOException {
String line = m_line_r.readLine();
if(line == null)
return false;
m_lnr++;
decode(line);
return true;
}
/**
* Read the next (or first) record from the input and prepare it for
* processing.
* @return
*/
public boolean nextRecord() throws IOException {
if(m_startWithFieldNames && m_lnr == 0) // Reading line 1?
{
if(!_nextRecord()) // Try to read,
return false;
//-- Move the values to the field names.
for(int i = size(); --i >= 0;)
elementAt(i).m_fldname = elementAt(i).m_value;
}
return _nextRecord();
}
/**
* @author mbp, added method to see if it is an empty line. This is to make
* config files ending with an extra newline not cause unnecessary errors
*/
public boolean isEmptyLine() {
return m_len == 0;
}
/*--------------------------------------------------------------*/
/* CODING: Parser. */
/*--------------------------------------------------------------*/
private int m_len;
private int m_ix;
private int m_fld_ix;
private String m_line;
/**
* Parses a single line into fields. This fills the field set with
* data from the record.
* @param line
*/
private void decode(String line) throws IOException {
// System.out.println("Decode line "+m_lnr+": "+line);
m_line = line;
m_len = line.length();
m_ix = 0;
m_fld_ix = 0;
//-- Start the parse.
while(m_ix < m_len) {
if(m_skip_ws)
m_ix = checkForWS(m_line, m_ix); // Get past whitespace if needed,
if(m_ix >= m_len)
break;
parseField();
if(m_skip_ws)
m_ix = checkForWS(m_line, m_ix); // Get past whitespace if needed,
if(m_ix >= m_len)
break;
parseSeparator();
}
}
public final String getLine() {
return m_line;
}
/**
* Defines fieldnames using a comma or semicolon separated field name string.
* @param fields
*/
public void defineFields(String fields) {
StringTokenizer st = new StringTokenizer(fields, ";,");
int ix = 0;
while(st.hasMoreTokens()) {
String name = st.nextToken().trim();
if(name.length() > 2) {
char c = name.charAt(0);
if(c == '"' || c == '\"' || c == '`') {
char ec = name.charAt(name.length() - 1);
if(ec == c) {
name = name.substring(1, name.length() - 1);
}
}
}
iInputField f = getField(ix);
f.setName(name);
ix++;
}
}
/*--------------------------------------------------------------*/
/* CODING: Field parser. */
/*--------------------------------------------------------------*/
private void parseField() throws IOException {
char c = m_line.charAt(m_ix);
if(isQuote(c)) {
parseQuoted();
return;
}
//-- Unquoted field. Stop as soon as a separator is found.
int six = m_ix; // Save start position,
while(m_ix < m_len) // While there's data
{
int sl = checkForSeparator(m_line, m_ix);
if(sl != 0) // Separator at current location?
break;
m_ix++; // To next char
}
if(m_ix == six) // No spaces between separators?
addField(m_ix, null); // Treat as NULL value
else
addLitField(six, m_line, m_ix - six); // add the field.
}
private void parseQuoted() throws IOException {
int spos = m_ix;
char qc = m_line.charAt(m_ix++);
StringBuffer sb = new StringBuffer();
for(;;) {
if(m_ix >= m_len)
error("Missing end quote in field " + m_fld_ix);
int ql = checkEscapeQuote(m_line, m_ix, qc);
if(ql > 0) {
//-- Escaped quote found: add it,
sb.append(qc); // Add quote char
m_ix += ql; // And past it,
} else {
char c = m_line.charAt(m_ix++);
if(c == qc)
break;
sb.append(c); // Add the char literally,
}
}
//-- Field completed,
addField(spos, sb.toString());
}
/*--------------------------------------------------------------*/
/* CODING: Field access. */
/*--------------------------------------------------------------*/
private Field elementAt(int i) {
if(i > m_fld_al.size())
return null;
return m_fld_al.get(i);
}
public iInputField getField(int ix) {
while(m_fld_al.size() <= ix) {
Field f = new Field();
m_fld_al.add(f);
f.m_index = m_fld_al.size() - 1;
}
return elementAt(ix);
}
public int size() {
return m_fld_ix;
}
private void addLitField(int spos, String line, int len) {
//-- 1. Find/add a Field structure
if(m_fld_ix >= m_fld_al.size())
m_fld_al.add(new Field());
Field f = m_fld_al.get(m_fld_ix);
f.m_index = m_fld_ix++;
// f.m_lpos = spos;
f.setValue(line.substring(spos, spos + len));
// System.out.println(">> addLitField "+f.m_value);
}
private void addField(int spos, String val) {
//-- 1. Find/add a Field structure
if(m_fld_ix >= m_fld_al.size())
m_fld_al.add(new Field());
Field f = m_fld_al.get(m_fld_ix);
f.m_index = m_fld_ix++;
// f.m_lpos = spos;
f.setValue(val);
// System.out.println(">> addField "+f.m_value);
}
public iInputField find(String name) {
if(name.startsWith("#")) // Numeric reference?
{
int ix = StringTool.strToInt(name.substring(1), -1);
if(ix < 0 || ix >= m_fld_al.size())
return null;
return elementAt(ix);
}
for(int i = m_fld_al.size(); --i >= 0;) {
Field f = elementAt(i);
if(f.getName().equalsIgnoreCase(name))
return f;
}
return null;
}
public String getValue(int ix) {
iInputField f = getField(ix);
if(f == null)
return null;
return f.getValue();
}
public String getValue(String name) {
iInputField f = find(name);
if(f == null)
return null;
return f.getValue();
}
public int getIntValue(String name) throws IOException {
iInputField f = find(name);
if(f == null || f.isEmpty()) {
error("Expecting an integer value in '" + name + "'");
return 0; //This will never be returned but it fools the compiler into accepting that the null check was done.
}
return convertToInt(f.getValue(), name);
}
public int getIntValue(String name, int def) throws IOException {
iInputField f = find(name);
if(f == null || f.isEmpty())
return def;
return convertToInt(f.getValue(), name);
}
private int convertToInt(String val, String field) throws IOException {
try {
return Integer.parseInt(val.trim());
} catch(Exception x) {}
error("Expecting integer value in '" + field + "', got '" + val + "'");
return -1;
}
public long getLongValue(String name) throws IOException {
iInputField f = find(name);
if(f == null || f.isEmpty()) {
error("Expecting an long value in '" + name + "'");
return 0; //This will never be returned but it fools the compiler into accepting that the null check was done.
}
return convertToLong(f.getValue(), name);
}
public long getLongValue(String name, long def) throws IOException {
iInputField f = find(name);
if(f == null || f.isEmpty())
return def;
return convertToLong(f.getValue(), name);
}
private long convertToLong(String val, String field) throws IOException {
try {
return Long.parseLong(val.trim());
} catch(Exception x) {}
error("Expecting long value in '" + field + "', got '" + val + "'");
return -1;
}
/*--------------------------------------------------------------*/
/* CODING: Field separators. */
/*--------------------------------------------------------------*/
/**
* Checks if the current position contains a separator. If so, this
* skips the separator and exits; else it throws an error.
*/
private void parseSeparator() throws IOException {
int sl = checkForSeparator(m_line, m_ix);
if(sl == 0)
error("Missing field separator in input file " + m_name);
m_ix += sl;
if(m_fld_ix >= m_fld_al.size())
m_fld_al.add(new Field());
Field f = m_fld_al.get(m_fld_ix);
f.m_index = m_fld_ix;
// f.m_lpos = m_ix;
f.setValue(null);
}
private int checkForSeparator(String line, int ix) {
if(m_fldsep_al.size() == 0) // Make sure that at least 1 separator (comma) is registered
m_fldsep_al.add(",");
for(int i = m_fldsep_al.size(); --i >= 0;) {
int sc = checkForSeparator(m_fldsep_al.get(i), line, ix);
if(sc > 0) // This IS a separator
return sc;
}
return 0;
}
/**
* Checks if the separator specified is at the current location, and
* if so returns the #chars to skip past it.
* @param sep
* @param line
* @param ix
* @return
*/
private int checkForSeparator(String sep, String line, int ix) {
int len = line.length();
int six = ix;
if(m_skip_ws)
ix = checkForWS(line, ix);
if(ix + sep.length() > len)
return 0;
if(line.substring(ix, ix + sep.length()).equalsIgnoreCase(sep))
return ix + sep.length() - six;
return 0;
}
/**
* Returns the first non-whitespace character on the line (can be eoln)
* @param line
* @param ix
* @return
*/
private int checkForWS(String line, int ix) {
int len = line.length();
while(ix < len && Character.isWhitespace(line.charAt(ix))) {
// It's possible we have a Whitespace character as separator.
// If so, return
if(hasWhitespaceSeparator()) {
for(int i = m_fldsep_al.size(); --i >= 0;) {
if((m_fldsep_al.get(i)).length() == 1 && (m_fldsep_al.get(i)).charAt(0) == line.charAt(ix))
return ix;
}
}
ix++;
}
return ix;
}
private int checkEscapeQuote(String line, int ix, char qc) {
int len = line.length();
if(m_escapeBackslash) // Escape using \"
{
if(ix + 2 <= len) {
if(line.charAt(ix) == '\\' && line.charAt(ix + 1) == qc)
return 2;
}
}
if(m_escapeDupQuote) // Escape using the quote char 2ce
{
if(ix + 2 <= len) {
if(line.charAt(ix) == qc && line.charAt(ix + 1) == qc)
return 2;
}
}
if(m_escapeBadly) // Badly quoted: recognised if followed by non-separator.
{
if(ix + 2 <= len) // Has at least 2 chars,
{
if(line.charAt(ix) == qc) // Starts with quote,
{
//-- If the thing after the quote is NOT a separator then assume this quote fits,
int tix = ix + 1; // Past leading quote,
if(m_skip_ws)
tix = checkForWS(line, tix);
int sl = checkForSeparator(line, tix);
if(sl == 0)
return 1; // Not a separator-> assume this is an embedded quote.
}
}
}
return 0;
}
private boolean isQuote(char c) {
if(!m_ignoreQuotes) {
if(m_quote_sb.length() == 0)
m_quote_sb.append('\"');
}
for(int i = m_quote_sb.length(); --i >= 0;) {
if(m_quote_sb.charAt(i) == c)
return true;
}
return false;
}
private boolean hasWhitespaceSeparator() {
return m_whitespaceSeparator;
}
private void setWhitespaceSeparator(boolean separator) {
m_whitespaceSeparator = separator;
}
}
| lgpl-2.1 |
michaelgena/nuxeo-unify-php | nuxeo-unify-php-plugin/src/main/yo/app/scripts/controllers/generaldocumentation.js | 880 | 'use strict';
/**
* @ngdoc function
* @name frontjcdApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the frontApp
*/
angular.module('frontApp')
.controller('GeneralDocumentationCtrl', function ($scope, $cookies, nuxeoClient) {
//$scope, $routeParams, $sce, $location, nuxeoClient
$scope.documents = {};
$scope.sortType = 'title'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchDocument = ''; // set the default search/filter term
$scope.formatDate = function(date){
var dateOut = new Date(date);
return dateOut;
};
// Main callback
function callback(result) {
$scope.documents = result.entries;
$("#loader").hide("");
}
// Entry point
nuxeoClient.request('query/QueryForGeneralDocumentations').schema('file').get().then(callback);
});
| lgpl-2.1 |
robclark/qtmobility-1.1.0 | tools/qcrmlgen/main.cpp | 2174 | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with
** the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include "qcrmlgen.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCrmlGenerator *generator = new QCrmlGenerator;
generator->show();
return app.exec();
}
| lgpl-2.1 |
kpalin/dasobert | src/org/biojava/dasobert/das/AlignmentParameters.java | 3503 | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on Dec 10, 2005
*
*/
package org.biojava.dasobert.das;
import org.biojava.dasobert.dasregistry.Das1Source;
import org.biojava.dasobert.dasregistry.DasCoordinateSystem;
/** a class that stores the arguments that can be sent to the AlignmentThread class
*
* @author Andreas Prlic
*
*/
public class AlignmentParameters {
String query;
String subject;
String queryPDBChainId;
String subjectPDBChainId;
DasCoordinateSystem queryCoordinateSystem;
DasCoordinateSystem subjectCoordinateSystem;
Das1Source[] dasSources;
public static String DEFAULT_PDBCOORDSYS = "PDBresnum,Protein Structure";
public static String DEFAULT_UNIPROTCOORDSYS = "UniProt,Protein Sequence";
public static String DEFAULT_ENSPCOORDSYS = "Ensembl,Protein Sequence";
public AlignmentParameters() {
super();
dasSources = new Das1Source[0];
}
public DasCoordinateSystem getDefaultPDBCoordSys(){
return DasCoordinateSystem.fromString(DEFAULT_PDBCOORDSYS);
}
public DasCoordinateSystem getDefaultUniProtCoordSys(){
return DasCoordinateSystem.fromString(DEFAULT_UNIPROTCOORDSYS);
}
public DasCoordinateSystem getDefaultEnspCoordSys(){
return DasCoordinateSystem.fromString(DEFAULT_ENSPCOORDSYS);
}
public Das1Source[] getDasSources() {
return dasSources;
}
public void setDasSources(Das1Source[] dasSources) {
this.dasSources = dasSources;
}
public void setDasSource(Das1Source dasSource){
dasSources = new Das1Source[] {dasSource};
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public DasCoordinateSystem getQueryCoordinateSystem() {
return queryCoordinateSystem;
}
public void setQueryCoordinateSystem(DasCoordinateSystem queryCoordinateSystem) {
this.queryCoordinateSystem = queryCoordinateSystem;
}
public String getQueryPDBChainId() {
return queryPDBChainId;
}
public void setQueryPDBChainId(String queryPDBChainId) {
this.queryPDBChainId = queryPDBChainId;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public DasCoordinateSystem getSubjectCoordinateSystem() {
return subjectCoordinateSystem;
}
public void setSubjectCoordinateSystem(
DasCoordinateSystem subjectCoordinateSystem) {
this.subjectCoordinateSystem = subjectCoordinateSystem;
}
public String getSubjectPDBChainId() {
return subjectPDBChainId;
}
public void setSubjectPDBChainId(String subjectPDBChainId) {
this.subjectPDBChainId = subjectPDBChainId;
}
}
| lgpl-2.1 |
ironjacamar/ironjacamar | deployers/tests/src/test/java/org/jboss/jca/test/deployers/spec/rars/ra16inout/TestActivationSpec.java | 1356 | /*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2009, Red Hat Inc, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jca.test.deployers.spec.rars.ra16inout;
import org.jboss.jca.test.deployers.spec.rars.BaseActivationSpec;
/**
* TestActivationSpec
* @author <a href="mailto:[email protected]">Jeff Zhang</a>
* @version $Revision: $
*/
public class TestActivationSpec extends BaseActivationSpec
{
}
| lgpl-2.1 |
mrijk/gimp-sharp | lib/Spacing.cs | 1087 | // GIMP# - A C# wrapper around the GIMP Library
// Copyright (C) 2004-2018 Maurits Rijk
//
// Spacing.cs
//
// 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 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., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
namespace Gimp
{
public struct Spacing
{
public double X {get; set;}
public double Y {get; set;}
public Spacing(double x, double y) : this()
{
X = x;
Y = y;
}
}
}
| lgpl-2.1 |
geotools/geotools | modules/unsupported/elasticsearch/src/main/java/org/geotools/data/elasticsearch/FilterToElasticException.java | 913 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2020, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.data.elasticsearch;
class FilterToElasticException extends RuntimeException {
private static final long serialVersionUID = 1819999351118120451L;
public FilterToElasticException(String msg, Throwable exp) {
super(msg, exp);
}
}
| lgpl-2.1 |
NixOS/nix | src/nix/cat.cc | 1818 | #include "command.hh"
#include "store-api.hh"
#include "fs-accessor.hh"
#include "nar-accessor.hh"
using namespace nix;
struct MixCat : virtual Args
{
std::string path;
void cat(ref<FSAccessor> accessor)
{
auto st = accessor->stat(path);
if (st.type == FSAccessor::Type::tMissing)
throw Error("path '%1%' does not exist", path);
if (st.type != FSAccessor::Type::tRegular)
throw Error("path '%1%' is not a regular file", path);
std::cout << accessor->readFile(path);
}
};
struct CmdCatStore : StoreCommand, MixCat
{
CmdCatStore()
{
expectArgs({
.label = "path",
.handler = {&path},
.completer = completePath
});
}
std::string description() override
{
return "print the contents of a file in the Nix store on stdout";
}
std::string doc() override
{
return
#include "store-cat.md"
;
}
void run(ref<Store> store) override
{
cat(store->getFSAccessor());
}
};
struct CmdCatNar : StoreCommand, MixCat
{
Path narPath;
CmdCatNar()
{
expectArgs({
.label = "nar",
.handler = {&narPath},
.completer = completePath
});
expectArg("path", &path);
}
std::string description() override
{
return "print the contents of a file inside a NAR file on stdout";
}
std::string doc() override
{
return
#include "nar-cat.md"
;
}
void run(ref<Store> store) override
{
cat(makeNarAccessor(readFile(narPath)));
}
};
static auto rCmdCatStore = registerCommand2<CmdCatStore>({"store", "cat"});
static auto rCmdCatNar = registerCommand2<CmdCatNar>({"nar", "cat"});
| lgpl-2.1 |
Luxoft/SDLP2 | SDL_Core/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_response.cc | 2317 | /**
* Copyright (c) 2013, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company 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.
*/
#include "application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h"
#include "interfaces/MOBILE_API.h"
namespace application_manager {
namespace commands {
UIPerformAudioPassThruResponse::UIPerformAudioPassThruResponse(
const MessageSharedPtr& message)
: ResponseFromHMI(message) {
}
UIPerformAudioPassThruResponse::~UIPerformAudioPassThruResponse() {
}
void UIPerformAudioPassThruResponse::Run() {
LOG4CXX_INFO(logger_, "UIPerformAudioPassThruResponse::Run");
// prepare SmartObject for mobile factory
(*message_)[strings::params][strings::function_id] =
mobile_apis::FunctionID::PerformAudioPassThruID;
SendResponseToMobile(message_);
}
} // namespace commands
} // namespace application_manager
| lgpl-2.1 |
robclark/qtmobility-1.1.0 | tests/auto/qcontactmanager/tst_qcontactmanager.cpp | 154468 | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with
** the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtGlobal>
#include "qtcontacts.h"
#include "qcontactchangeset.h"
#include "qcontactmanagerdataholder.h"
#if defined(SYMBIAN_BACKEND_S60_VERSION_31) || defined(SYMBIAN_BACKEND_S60_VERSION_32) || defined(SYMBIAN_BACKEND_S60_VERSION_50)
// for the symbianManager() test.
#include <e32std.h>
#include <cntdb.h>
#include <cntdbobs.h>
#include <e32base.h>
#include <s32mem.h>
#include <cntitem.h>
#include <cntfldst.h>
#endif
#if defined(USE_VERSIT_PLZ)
// This makes it easier to create specific QContacts
#include "qversitcontactimporter.h"
#include "qversitdocument.h"
#include "qversitreader.h"
#endif
QTM_USE_NAMESPACE
// Eventually these will make it into qtestcase.h
// but we might need to tweak the timeout values here.
#ifndef QTRY_COMPARE
#define QTRY_COMPARE(__expr, __expected) \
do { \
const int __step = 50; \
const int __timeout = 5000; \
if ((__expr) != (__expected)) { \
QTest::qWait(0); \
} \
for (int __i = 0; __i < __timeout && ((__expr) != (__expected)); __i+=__step) { \
QTest::qWait(__step); \
} \
QCOMPARE(__expr, __expected); \
} while(0)
#endif
#ifndef QTRY_VERIFY
#define QTRY_VERIFY(__expr) \
do { \
const int __step = 50; \
const int __timeout = 5000; \
if (!(__expr)) { \
QTest::qWait(0); \
} \
for (int __i = 0; __i < __timeout && !(__expr); __i+=__step) { \
QTest::qWait(__step); \
} \
QVERIFY(__expr); \
} while(0)
#endif
#define QTRY_WAIT(code, __expr) \
do { \
const int __step = 50; \
const int __timeout = 5000; \
if (!(__expr)) { \
QTest::qWait(0); \
} \
for (int __i = 0; __i < __timeout && !(__expr); __i+=__step) { \
do { code } while(0); \
QTest::qWait(__step); \
} \
} while(0)
#define QCONTACTMANAGER_REMOVE_VERSIONS_FROM_URI(params) params.remove(QString::fromAscii(QTCONTACTS_VERSION_NAME)); \
params.remove(QString::fromAscii(QTCONTACTS_IMPLEMENTATION_VERSION_NAME))
//TESTED_COMPONENT=src/contacts
//TESTED_CLASS=
//TESTED_FILES=
// to get QFETCH to work with the template expression...
typedef QMap<QString,QString> tst_QContactManager_QStringMap;
Q_DECLARE_METATYPE(tst_QContactManager_QStringMap)
Q_DECLARE_METATYPE(QList<QContactLocalId>)
/* A class that no backend can support */
class UnsupportedMetatype {
int foo;
};
Q_DECLARE_METATYPE(UnsupportedMetatype)
Q_DECLARE_METATYPE(QContact)
Q_DECLARE_METATYPE(QContactManager::Error)
class tst_QContactManager : public QObject
{
Q_OBJECT
public:
tst_QContactManager();
virtual ~tst_QContactManager();
private:
void dumpContactDifferences(const QContact& a, const QContact& b);
void dumpContact(const QContact &c);
void dumpContacts(QContactManager *cm);
bool isSuperset(const QContact& ca, const QContact& cb);
QList<QContactDetail> removeAllDefaultDetails(const QList<QContactDetail>& details);
void addManagers(); // add standard managers to the data
QContact createContact(QContactDetailDefinition nameDef, QString firstName, QString lastName, QString phoneNumber);
void saveContactName(QContact *contact, QContactDetailDefinition nameDef, QContactName *contactName, const QString &name) const;
void validateDefinitions(const QMap<QString, QContactDetailDefinition>& defs) const;
QScopedPointer<QContactManagerDataHolder> managerDataHolder;
public slots:
void initTestCase();
void cleanupTestCase();
private slots:
void doDump();
void doDump_data() {addManagers();}
void doDumpSchema();
void doDumpSchema_data() {addManagers();}
/* Special test with special data */
void uriParsing();
void nameSynthesis();
void compatibleContact();
/* Backend-specific tests */
#if defined(SYMBIAN_BACKEND_S60_VERSION_31) || defined(SYMBIAN_BACKEND_S60_VERSION_32) || defined(SYMBIAN_BACKEND_S60_VERSION_50)
void symbianManager();
void symbianManager_data() {addManagers();}
#endif
/* Tests that are run on all managers */
void metadata();
void nullIdOperations();
void add();
void update();
void remove();
void batch();
void signalEmission();
void detailDefinitions();
void displayName();
void actionPreferences();
void selfContactId();
void detailOrders();
void relationships();
void contactType();
#if defined(USE_VERSIT_PLZ)
void partialSave();
void partialSave_data() {addManagers();}
#endif
/* Tests that take no data */
void contactValidation();
void errorStayingPut();
void ctors();
void invalidManager();
void memoryManager();
void changeSet();
void fetchHint();
void engineDefaultSchema();
/* Special test with special data */
void uriParsing_data();
void nameSynthesis_data();
void compatibleContact_data();
/* Tests that are run on all managers */
void metadata_data() {addManagers();}
void nullIdOperations_data() {addManagers();}
void add_data() {addManagers();}
void update_data() {addManagers();}
void remove_data() {addManagers();}
void batch_data() {addManagers();}
void signalEmission_data() {addManagers();}
void detailDefinitions_data() {addManagers();}
void displayName_data() {addManagers();}
void actionPreferences_data() {addManagers();}
void selfContactId_data() {addManagers();}
void detailOrders_data() {addManagers();}
void relationships_data() {addManagers();}
void contactType_data() {addManagers();}
};
tst_QContactManager::tst_QContactManager()
{
}
tst_QContactManager::~tst_QContactManager()
{
}
void tst_QContactManager::initTestCase()
{
managerDataHolder.reset(new QContactManagerDataHolder());
/* Make sure these other test plugins are NOT loaded by default */
// These are now removed from the list of managers in addManagers()
//QVERIFY(!QContactManager::availableManagers().contains("testdummy"));
//QVERIFY(!QContactManager::availableManagers().contains("teststaticdummy"));
//QVERIFY(!QContactManager::availableManagers().contains("maliciousplugin"));
}
void tst_QContactManager::cleanupTestCase()
{
managerDataHolder.reset(0);
}
void tst_QContactManager::dumpContactDifferences(const QContact& ca, const QContact& cb)
{
// Try to narrow down the differences
QContact a(ca);
QContact b(cb);
QContactName n1 = a.detail(QContactName::DefinitionName);
QContactName n2 = b.detail(QContactName::DefinitionName);
// Check the name components in more detail
QCOMPARE(n1.firstName(), n2.firstName());
QCOMPARE(n1.middleName(), n2.middleName());
QCOMPARE(n1.lastName(), n2.lastName());
QCOMPARE(n1.prefix(), n2.prefix());
QCOMPARE(n1.suffix(), n2.suffix());
QCOMPARE(n1.customLabel(), n2.customLabel());
// Check the display label
QCOMPARE(a.displayLabel(), b.displayLabel());
// Now look at the rest
QList<QContactDetail> aDetails = a.details();
QList<QContactDetail> bDetails = b.details();
// They can be in any order, so loop
// First remove any matches
foreach(QContactDetail d, aDetails) {
foreach(QContactDetail d2, bDetails) {
if(d == d2) {
a.removeDetail(&d);
b.removeDetail(&d2);
break;
}
}
}
// Now dump the extra details that were unmatched in A (note that DisplayLabel and Type are always present).
aDetails = a.details();
bDetails = b.details();
foreach(QContactDetail d, aDetails) {
if (d.definitionName() != QContactDisplayLabel::DefinitionName && d.definitionName() != QContactType::DefinitionName)
qDebug() << "A contact had extra detail:" << d.definitionName() << d.variantValues();
}
// and same for B
foreach(QContactDetail d, bDetails) {
if (d.definitionName() != QContactDisplayLabel::DefinitionName && d.definitionName() != QContactType::DefinitionName)
qDebug() << "B contact had extra detail:" << d.definitionName() << d.variantValues();
}
// now test specifically the display label and the type
if (a.displayLabel() != b.displayLabel()) {
qDebug() << "A contact display label =" << a.displayLabel();
qDebug() << "B contact display label =" << b.displayLabel();
}
if (a.type() != b.type()) {
qDebug() << "A contact type =" << a.type();
qDebug() << "B contact type =" << b.type();
}
}
bool tst_QContactManager::isSuperset(const QContact& ca, const QContact& cb)
{
// returns true if contact ca is a superset of contact cb
// we use this test instead of equality because dynamic information
// such as presence/location, and synthesised information such as
// display label and (possibly) type, may differ between a contact
// in memory and the contact in the managed store.
QContact a(ca);
QContact b(cb);
QList<QContactDetail> aDetails = a.details();
QList<QContactDetail> bDetails = b.details();
// They can be in any order, so loop
// First remove any matches
foreach(QContactDetail d, aDetails) {
foreach(QContactDetail d2, bDetails) {
if(d == d2) {
a.removeDetail(&d);
b.removeDetail(&d2);
break;
}
}
}
// Second remove any superset matches (eg, backend adds a field)
aDetails = a.details();
bDetails = b.details();
foreach (QContactDetail d, aDetails) {
foreach (QContactDetail d2, bDetails) {
if (d.definitionName() == d2.definitionName()) {
bool canRemove = true;
QMap<QString, QVariant> d2map = d2.variantValues();
foreach (QString key, d2map.keys()) {
if (d.value(key) != d2.value(key)) {
// d can have _more_ keys than d2,
// but not _less_; and it cannot
// change the value.
canRemove = false;
}
}
if (canRemove) {
// if we get to here, we can remove the details.
a.removeDetail(&d);
b.removeDetail(&d2);
break;
}
}
}
}
// check for contact type updates
if (!a.type().isEmpty())
if (!b.type().isEmpty())
if (a.type() != b.type())
return false; // nonempty type is different.
// Now check to see if b has any details remaining; if so, a is not a superset.
// Note that the DisplayLabel and Type can never be removed.
if (b.details().size() > 2
|| (b.details().size() == 2 && (b.details().value(0).definitionName() != QContactDisplayLabel::DefinitionName
|| b.details().value(1).definitionName() != QContactType::DefinitionName)))
return false;
return true;
}
void tst_QContactManager::dumpContact(const QContact& contact)
{
QContactManager m;
qDebug() << "Contact: " << contact.id().localId() << "(" << m.synthesizedContactDisplayLabel(contact) << ")";
QList<QContactDetail> details = contact.details();
foreach(QContactDetail d, details) {
qDebug() << " " << d.definitionName() << ":";
qDebug() << " Vals:" << d.variantValues();
}
}
void tst_QContactManager::dumpContacts(QContactManager *cm)
{
QList<QContactLocalId> ids = cm->contactIds();
qDebug() << "There are" << ids.count() << "contacts in" << cm->managerUri();
foreach(QContactLocalId id, ids) {
QContact c = cm->contact(id);
dumpContact(c);
}
}
void tst_QContactManager::uriParsing_data()
{
QTest::addColumn<QString>("uri");
QTest::addColumn<bool>("good"); // is this a good uri or not
QTest::addColumn<QString>("manager");
QTest::addColumn<QMap<QString, QString> >("parameters");
QMap<QString, QString> inparameters;
inparameters.insert("foo", "bar");
inparameters.insert("bazflag", QString());
inparameters.insert("bar", "glob");
QMap<QString, QString> inparameters2;
inparameters2.insert("this has spaces", QString());
inparameters2.insert("and& an", " &");
inparameters2.insert("and an ", "=quals");
QTest::newRow("built") << QContactManager::buildUri("manager", inparameters) << true << "manager" << inparameters;
QTest::newRow("built with escaped parameters") << QContactManager::buildUri("manager", inparameters2) << true << "manager" << inparameters2;
QTest::newRow("no scheme") << "this should not split" << false << QString() << tst_QContactManager_QStringMap();
QTest::newRow("wrong scheme") << "invalidscheme:foo bar" << false << QString() << tst_QContactManager_QStringMap();
QTest::newRow("right scheme, no colon") << "qtcontacts" << false << QString() << tst_QContactManager_QStringMap();
QTest::newRow("no manager, colon, no params") << "qtcontacts::" << false << "manager" << tst_QContactManager_QStringMap();
QTest::newRow("yes manager, no colon, no params") << "qtcontacts:manager" << true << "manager" << tst_QContactManager_QStringMap();
QTest::newRow("yes manager, yes colon, no params") << "qtcontacts:manager:" << true << "manager"<< tst_QContactManager_QStringMap();
QTest::newRow("yes params") << "qtcontacts:manager:foo=bar&bazflag=&bar=glob" << true << "manager" << inparameters;
QTest::newRow("yes params but misformed") << "qtcontacts:manager:foo=bar&=gloo&bar=glob" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 2") << "qtcontacts:manager:=&=gloo&bar=glob" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 3") << "qtcontacts:manager:==" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 4") << "qtcontacts:manager:&&" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 5") << "qtcontacts:manager:&goo=bar" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 6") << "qtcontacts:manager:goo&bar" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 7") << "qtcontacts:manager:goo&bar&gob" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 8") << "qtcontacts:manager:==&&==&goo=bar" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 9") << "qtcontacts:manager:foo=bar=baz" << false << "manager" << inparameters;
QTest::newRow("yes params but misformed 10") << "qtcontacts:manager:foo=bar=baz=glob" << false << "manager" << inparameters;
QTest::newRow("no manager but yes params") << "qtcontacts::foo=bar&bazflag=&bar=glob" << false << QString() << inparameters;
QTest::newRow("no manager or params") << "qtcontacts::" << false << QString() << inparameters;
QTest::newRow("no manager or params or colon") << "qtcontacts:" << false << QString() << inparameters;
}
void tst_QContactManager::addManagers()
{
QTest::addColumn<QString>("uri");
QStringList managers = QContactManager::availableManagers();
/* Known one that will not pass */
managers.removeAll("invalid");
managers.removeAll("testdummy");
managers.removeAll("teststaticdummy");
managers.removeAll("maliciousplugin");
foreach(QString mgr, managers) {
QMap<QString, QString> params;
QTest::newRow(QString("mgr='%1'").arg(mgr).toLatin1().constData()) << QContactManager::buildUri(mgr, params);
if (mgr == "memory") {
params.insert("id", "tst_QContactManager");
QTest::newRow(QString("mgr='%1', params").arg(mgr).toLatin1().constData()) << QContactManager::buildUri(mgr, params);
}
}
}
/*
* Helper method for creating a QContact instance with name and phone number
* details. Name is generated according to the detail definition assuming that
* either first and last name or custom label is supported.
*/
QContact tst_QContactManager::createContact(
QContactDetailDefinition nameDef,
QString firstName,
QString lastName,
QString phoneNumber)
{
QContact contact;
if(!firstName.isEmpty() || !lastName.isEmpty()) {
QContactName n;
if(nameDef.fields().contains(QContactName::FieldFirstName)
&& nameDef.fields().contains(QContactName::FieldFirstName)) {
n.setFirstName(firstName);
n.setLastName(lastName);
} else if(nameDef.fields().contains(QContactName::FieldCustomLabel)) {
n.setCustomLabel(firstName + " " + lastName);
} else {
// assume that either first and last name or custom label is supported
QTest::qWarn("Neither custom label nor first name/last name supported!");
return QContact();
}
contact.saveDetail(&n);
}
if (!phoneNumber.isEmpty()) {
QContactPhoneNumber ph;
ph.setNumber(phoneNumber);
contact.saveDetail(&ph);
}
return contact;
}
void tst_QContactManager::saveContactName(QContact *contact, QContactDetailDefinition nameDef, QContactName *contactName, const QString &name) const
{
// check which name fields are supported in the following order:
// 1. custom label, 2. first name, 3. last name
if(nameDef.fields().contains(QContactName::FieldCustomLabel)) {
contactName->setCustomLabel(name);
} else if(nameDef.fields().contains(QContactName::FieldFirstName)) {
contactName->setFirstName(name);
} else if(nameDef.fields().contains(QContactName::FieldLastName)) {
contactName->setLastName(name);
} else {
// Assume that at least one of the above name fields is supported by the backend
QVERIFY(false);
}
contact->saveDetail(contactName);
}
void tst_QContactManager::metadata()
{
// ensure that the backend is publishing its metadata (name / parameters / uri) correctly
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(new QContactManager("memory"));
QVERIFY(QContactManager::buildUri(cm->managerName(), cm->managerParameters()) == cm->managerUri());
}
void tst_QContactManager::nullIdOperations()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(new QContactManager("memory"));
QVERIFY(!cm->removeContact(QContactLocalId()));
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
QContact c = cm->contact(QContactLocalId());
QVERIFY(c.id() == QContactId());
QVERIFY(c.isEmpty());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
}
void tst_QContactManager::uriParsing()
{
QFETCH(QString, uri);
QFETCH(bool, good);
QFETCH(QString, manager);
QFETCH(tst_QContactManager_QStringMap, parameters);
QString outmanager;
QMap<QString, QString> outparameters;
if (good) {
/* Good split */
/* Test splitting */
QVERIFY(QContactManager::parseUri(uri, 0, 0)); // no out parms
// 1 out param
QVERIFY(QContactManager::parseUri(uri, &outmanager, 0));
QCOMPARE(manager, outmanager);
QVERIFY(QContactManager::parseUri(uri, 0, &outparameters));
QCONTACTMANAGER_REMOVE_VERSIONS_FROM_URI(outparameters);
QCOMPARE(parameters, outparameters);
outmanager.clear();
outparameters.clear();
QVERIFY(QContactManager::parseUri(uri, &outmanager, &outparameters));
QCONTACTMANAGER_REMOVE_VERSIONS_FROM_URI(outparameters);
QCOMPARE(manager, outmanager);
QCOMPARE(parameters, outparameters);
} else {
/* bad splitting */
outmanager.clear();
outparameters.clear();
QVERIFY(QContactManager::parseUri(uri, 0, 0) == false);
QVERIFY(QContactManager::parseUri(uri, &outmanager, 0) == false);
QVERIFY(outmanager.isEmpty());
QVERIFY(QContactManager::parseUri(uri, 0, &outparameters) == false);
QCONTACTMANAGER_REMOVE_VERSIONS_FROM_URI(outparameters);
QVERIFY(outparameters.isEmpty());
/* make sure the in parameters don't change with a bad split */
outmanager = manager;
outparameters = parameters;
QVERIFY(QContactManager::parseUri(uri, &outmanager, 0) == false);
QCOMPARE(manager, outmanager);
QVERIFY(QContactManager::parseUri(uri, 0, &outparameters) == false);
QCONTACTMANAGER_REMOVE_VERSIONS_FROM_URI(outparameters);
QCOMPARE(parameters, outparameters);
}
}
void tst_QContactManager::ctors()
{
/* test the different ctors to make sure we end up with the same uri */
QVERIFY(QContactManager::availableManagers().count() > 1); // invalid + something else
QVERIFY(QContactManager::availableManagers().contains("invalid"));
QString defaultStore = QContactManager::availableManagers().value(0);
QVERIFY(defaultStore != "invalid");
qDebug() << "Available managers:" << QContactManager::availableManagers();
QMap<QString, QString> randomParameters;
randomParameters.insert("something", "old");
randomParameters.insert("something...", "new");
randomParameters.insert("something ", "borrowed");
randomParameters.insert(" something", "blue");
QObject parent;
QContactManager cm; // default
QContactManager cm2(defaultStore);
QContactManager cm3(defaultStore, QMap<QString, QString>());
QContactManager cm4(cm.managerUri()); // should fail
QScopedPointer<QContactManager> cm5(QContactManager::fromUri(QContactManager::buildUri(defaultStore, QMap<QString, QString>())));
QScopedPointer<QContactManager> cm6(QContactManager::fromUri(cm.managerUri())); // uri is not a name; should fail.
QScopedPointer<QContactManager> cm9(QContactManager::fromUri(QString(), &parent));
QVERIFY(cm9->parent() == &parent);
/* OLD TEST WAS THIS: */
//QCOMPARE(cm.managerUri(), cm2.managerUri());
//QCOMPARE(cm.managerUri(), cm3.managerUri());
//QCOMPARE(cm.managerUri(), cm5->managerUri());
//QCOMPARE(cm.managerUri(), cm6->managerUri());
//QCOMPARE(cm.managerUri(), cm9->managerUri());
/* NEW TEST IS THIS: Test that the names of the managers are the same */
QCOMPARE(cm.managerName(), cm2.managerName());
QCOMPARE(cm.managerName(), cm3.managerName());
QCOMPARE(cm.managerName(), cm5->managerName());
QCOMPARE(cm.managerName(), cm6->managerName());
QCOMPARE(cm.managerName(), cm9->managerName());
QVERIFY(cm.managerUri() != cm4.managerUri()); // don't pass a uri to the ctor
/* Test that we get invalid stores when we do silly things */
QContactManager em("non existent");
QContactManager em2("non existent", QMap<QString, QString>());
QContactManager em3("memory", randomParameters);
/* Also invalid, since we don't have one of these anyway */
QScopedPointer<QContactManager> em4(QContactManager::fromUri("invalid uri"));
QScopedPointer<QContactManager> em5(QContactManager::fromUri(QContactManager::buildUri("nonexistent", QMap<QString, QString>())));
QScopedPointer<QContactManager> em6(QContactManager::fromUri(em3.managerUri()));
/*
* Sets of stores that should be equivalent:
* - 1, 2, 4, 5
* - 3, 6
*/
/* First some URI testing for equivalent stores */
QVERIFY(em.managerUri() == em2.managerUri());
QVERIFY(em.managerUri() == em5->managerUri());
QVERIFY(em.managerUri() == em4->managerUri());
QVERIFY(em2.managerUri() == em4->managerUri());
QVERIFY(em2.managerUri() == em5->managerUri());
QVERIFY(em4->managerUri() == em5->managerUri());
QVERIFY(em3.managerUri() == em6->managerUri());
/* Test the stores that should not be the same */
QVERIFY(em.managerUri() != em3.managerUri());
QVERIFY(em.managerUri() != em6->managerUri());
/* now the components */
QCOMPARE(em.managerName(), QString("invalid"));
QCOMPARE(em2.managerName(), QString("invalid"));
QCOMPARE(em3.managerName(), QString("memory"));
QCOMPARE(em4->managerName(), QString("invalid"));
QCOMPARE(em5->managerName(), QString("invalid"));
QCOMPARE(em6->managerName(), QString("memory"));
QCOMPARE(em.managerParameters(), tst_QContactManager_QStringMap());
QCOMPARE(em2.managerParameters(), tst_QContactManager_QStringMap());
QCOMPARE(em4->managerParameters(), tst_QContactManager_QStringMap());
QCOMPARE(em5->managerParameters(), tst_QContactManager_QStringMap());
QCOMPARE(em3.managerParameters(), em6->managerParameters()); // memory engine discards the given params, replaces with id.
// Finally test the platform specific engines are actually the defaults
#if defined(Q_OS_SYMBIAN)
QCOMPARE(defaultStore, QString("symbian"));
#elif defined(Q_WS_MAEMO_6)
QCOMPARE(defaultStore, QString("tracker"));
#elif defined(Q_WS_MAEMO_5)
QCOMPARE(defaultStore, QString("maemo5"));
#elif defined(Q_OS_WINCE)
QCOMPARE(defaultStore, QString("wince"));
#else
QCOMPARE(defaultStore, QString("memory"));
#endif
}
void tst_QContactManager::doDump()
{
// Only do this if it has been explicitly selected
if (QCoreApplication::arguments().contains("doDump")) {
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
dumpContacts(cm.data());
}
}
Q_DECLARE_METATYPE(QVariant)
void tst_QContactManager::doDumpSchema()
{
// Only do this if it has been explicitly selected
if (QCoreApplication::arguments().contains("doDumpSchema")) {
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
// Get the schema for each supported type
foreach(QString type, cm->supportedContactTypes()) {
QMap<QString, QContactDetailDefinition> defs = cm->detailDefinitions(type);
foreach(QContactDetailDefinition def, defs.values()) {
if (def.isUnique())
qDebug() << QString("%2::%1 (Unique) {").arg(def.name()).arg(type).toAscii().constData();
else
qDebug() << QString("%2::%1 {").arg(def.name()).arg(type).toAscii().constData();
QMap<QString, QContactDetailFieldDefinition> fields = def.fields();
foreach(QString fname, fields.keys()) {
QContactDetailFieldDefinition field = fields.value(fname);
if (field.allowableValues().count() > 0) {
// Make some pretty output
QStringList allowedList;
foreach(QVariant var, field.allowableValues()) {
QString allowed;
if (var.type() == QVariant::String)
allowed = QString("'%1'").arg(var.toString());
else if (var.type() == QVariant::StringList)
allowed = QString("'%1'").arg(var.toStringList().join(","));
else {
// use the textstream <<
QDebug dbg(&allowed);
dbg << var;
}
allowedList.append(allowed);
}
qDebug() << QString(" %2 %1 {%3}").arg(fname).arg(QMetaType::typeName(field.dataType())).arg(allowedList.join(",")).toAscii().constData();
} else
qDebug() << QString(" %2 %1").arg(fname).arg(QMetaType::typeName(field.dataType())).toAscii().constData();
}
qDebug() << "}";
}
}
}
}
void tst_QContactManager::add()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
QContactDetailDefinition nameDef = cm->detailDefinition(QContactName::DefinitionName, QContactType::TypeContact);
QContact alice = createContact(nameDef, "Alice", "inWonderland", "1234567");
int currCount = cm->contactIds().count();
QVERIFY(cm->saveContact(&alice));
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(!alice.id().managerUri().isEmpty());
QVERIFY(alice.id().localId() != 0);
QCOMPARE(cm->contactIds().count(), currCount+1);
QContact added = cm->contact(alice.id().localId());
QVERIFY(added.id() == alice.id());
if (!isSuperset(added, alice)) {
dumpContacts(cm.data());
dumpContactDifferences(added, alice);
QCOMPARE(added, alice);
}
// now try adding a contact that does not exist in the database with non-zero id
if (cm->managerName() == "symbiansim") {
// TODO: symbiansim backend fails this test currently. Will be fixed later.
QWARN("This manager has a known issue with saving a non-zero id contact. Skipping this test step.");
} else {
QContact nonexistent = createContact(nameDef, "nonexistent", "contact", "");
QVERIFY(cm->saveContact(&nonexistent)); // should work
QVERIFY(cm->removeContact(nonexistent.id().localId())); // now nonexistent has an id which does not exist
QVERIFY(!cm->saveContact(&nonexistent)); // hence, should fail
QCOMPARE(cm->error(), QContactManager::DoesNotExistError);
nonexistent.setId(QContactId());
QVERIFY(cm->saveContact(&nonexistent)); // after setting id to zero, should save
QVERIFY(cm->removeContact(nonexistent.id().localId()));
}
// now try adding a "megacontact"
// - get list of all definitions supported by the manager
// - add one detail of each definition to a contact
// - save the contact
// - read it back
// - ensure that it's the same.
QContact megacontact;
QMap<QString, QContactDetailDefinition> defmap = cm->detailDefinitions();
QList<QContactDetailDefinition> defs = defmap.values();
foreach (const QContactDetailDefinition def, defs) {
// Leave these warnings here - might need an API for this
// XXX FIXME: access constraint reporting as moved to the detail itself
//if (def.accessConstraint() == QContactDetailDefinition::ReadOnly) {
// continue;
//}
if (cm->managerName() == "maemo5") {
// The maemo5 backend only supports reading of Guid and QCOA
if (def.name() == QContactGuid::DefinitionName)
continue;
if (def.name() == QContactOnlineAccount::DefinitionName)
continue;
if (def.name() == QContactPresence::DefinitionName)
continue;
}
// This is probably read-only
if (def.name() == QContactTimestamp::DefinitionName)
continue;
// otherwise, create a new detail of the given type and save it to the contact
QContactDetail det(def.name());
QMap<QString, QContactDetailFieldDefinition> fieldmap = def.fields();
QStringList fieldKeys = fieldmap.keys();
foreach (const QString& fieldKey, fieldKeys) {
// get the field, and check to see that it's not constrained.
QContactDetailFieldDefinition currentField = fieldmap.value(fieldKey);
// Don't test detail uris as these are manager specific
if (fieldKey == QContactDetail::FieldDetailUri)
continue;
// Special case: phone number.
if (def.name() == QContactPhoneNumber::DefinitionName &&
fieldKey == QContactPhoneNumber::FieldNumber) {
det.setValue(fieldKey, "+3581234567890");
continue;
}
// Attempt to create a worthy value
if (!currentField.allowableValues().isEmpty()) {
// we want to save a value that will be accepted.
if (currentField.dataType() == QVariant::StringList)
det.setValue(fieldKey, QStringList() << currentField.allowableValues().first().toString());
else if (currentField.dataType() == QVariant::List)
det.setValue(fieldKey, QVariantList() << currentField.allowableValues().first());
else
det.setValue(fieldKey, currentField.allowableValues().first());
} else {
// any value of the correct type will be accepted
bool savedSuccessfully = false;
QVariant dummyValue = QVariant(fieldKey); // try to get some unique string data
if (dummyValue.canConvert(currentField.dataType())) {
savedSuccessfully = dummyValue.convert(currentField.dataType());
if (savedSuccessfully) {
// we have successfully created a (supposedly) valid field for this detail.
det.setValue(fieldKey, dummyValue);
continue;
}
}
// nope, couldn't save the string value (test); try a date.
dummyValue = QVariant(QDate::currentDate());
if (dummyValue.canConvert(currentField.dataType())) {
savedSuccessfully = dummyValue.convert(currentField.dataType());
if (savedSuccessfully) {
// we have successfully created a (supposedly) valid field for this detail.
det.setValue(fieldKey, dummyValue);
continue;
}
}
// nope, couldn't convert a string or a date - try the integer value (42)
dummyValue = QVariant(42);
if (dummyValue.canConvert(currentField.dataType())) {
savedSuccessfully = dummyValue.convert(currentField.dataType());
if (savedSuccessfully) {
// we have successfully created a (supposedly) valid field for this detail.
det.setValue(fieldKey, dummyValue);
continue;
}
}
// if we get here, we don't know what sort of value can be saved...
}
}
if (!det.isEmpty())
megacontact.saveDetail(&det);
}
QVERIFY(cm->saveContact(&megacontact)); // must be able to save since built from definitions.
QContact retrievedMegacontact = cm->contact(megacontact.id().localId());
if (!isSuperset(retrievedMegacontact, megacontact)) {
dumpContactDifferences(megacontact, retrievedMegacontact);
QEXPECT_FAIL("mgr='wince'", "Address Display Label mismatch", Continue);
QCOMPARE(megacontact, retrievedMegacontact);
}
// now a contact with many details of a particular definition
// if the detail is not unique it should then support minumum of two of the same kind
const int nrOfdetails = 2;
QContact veryContactable = createContact(nameDef, "Very", "Contactable", "");
for (int i = 0; i < nrOfdetails; i++) {
QString phnStr = QString::number(i);
QContactPhoneNumber vcphn;
vcphn.setNumber(phnStr);
QVERIFY(veryContactable.saveDetail(&vcphn));
}
// check that all the numbers were added successfully
QVERIFY(veryContactable.details(QContactPhoneNumber::DefinitionName).size() == nrOfdetails);
// check if it can be saved
QContactDetailDefinition def = cm->detailDefinition(QContactPhoneNumber::DefinitionName);
if (def.isUnique()) {
QVERIFY(!cm->saveContact(&veryContactable));
}
else {
QVERIFY(cm->saveContact(&veryContactable));
// verify save
QContact retrievedContactable = cm->contact(veryContactable.id().localId());
if (!isSuperset(retrievedContactable, veryContactable)) {
dumpContactDifferences(veryContactable, retrievedContactable);
QEXPECT_FAIL("mgr='wince'", "Number of phones supported mismatch", Continue);
QCOMPARE(veryContactable, retrievedContactable);
}
}
}
void tst_QContactManager::update()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
if (cm->managerName() == QString(QLatin1String("maemo5"))) {
// we specifically want to test the update semantics of the maemo5 backend
// since there are various complexities relating to roster contacts.
QContact mt;
QContactName mtn;
mtn.setFirstName("test");
mtn.setLastName("maemo");
QContactPhoneNumber pn;
pn.setNumber("12345");
mt.saveDetail(&mtn);
cm->saveContact(&mt);
mt = cm->contact(mt.localId()); // force reload of (persisted) contact
QVERIFY(mt.details<QContactPhoneNumber>().count() == 0);
// now save a single phonenumber
mt.saveDetail(&pn);
cm->saveContact(&mt);
mt = cm->contact(mt.localId()); // force reload of (persisted) contact
QVERIFY(mt.details<QContactPhoneNumber>().count() == 1);
// edit some other existing detail and save (shouldn't duplicate the phone number)
mtn.setMiddleName("middle");
mt.saveDetail(&mtn);
cm->saveContact(&mt);
mt = cm->contact(mt.localId()); // force reload of (persisted) contact
QCOMPARE(mt.details<QContactPhoneNumber>().count(), 1);
// add some other detail and save (shouldn't duplicate the phone number)
QContactEmailAddress mte;
mte.setEmailAddress("[email protected]");
mt.saveDetail(&mte);
cm->saveContact(&mt);
mt = cm->contact(mt.localId()); // force reload of (persisted) contact
QCOMPARE(mt.details<QContactPhoneNumber>().count(), 1);
// add another phone number detail and save (should create a single other phone number)
QContactPhoneNumber pn2;
pn2.setNumber("98765");
mt.saveDetail(&pn2);
cm->saveContact(&mt);
mt = cm->contact(mt.localId()); // force reload of (persisted) contact
QCOMPARE(mt.details<QContactPhoneNumber>().count(), 2);
// here we do something tricky: we save one of the previously saved phone numbers
// in a _different_ contact, and see if that causes problems with the overwrite vs new detail code.
QContactPhoneNumber pn2Copy = pn2;
QContact mt2;
QContactName mt2n;
mt2n.setFirstName("test2");
mt2.saveDetail(&mt2n);
QContactPhoneNumber shouldBeNew = pn;
mt2.saveDetail(&shouldBeNew);
QVERIFY(cm->saveContact(&mt2));
mt2 = cm->contact(mt2.localId());
QCOMPARE(mt2.details<QContactPhoneNumber>().count(), 1);
mt2.saveDetail(&pn2);
QVERIFY(cm->saveContact(&mt2));
mt2 = cm->contact(mt2.localId());
QCOMPARE(mt2.details<QContactPhoneNumber>().count(), 2);
pn2 = pn2Copy; // reset just in case backend added some fields.
// remove the other phone number detail, shouldn't cause side effects to the first...
// NOTE: we need to reload the details before attempting to remove/edit them
// because the backend can change the ids.
QList<QContactPhoneNumber> pnums = mt.details<QContactPhoneNumber>();
foreach (const QContactPhoneNumber& pd, pnums) {
if (pd.number() == pn2.number())
pn2 = pd;
else if (pd.number() == pn.number())
pn = pd;
}
mt.removeDetail(&pn2);
cm->saveContact(&mt);
mt = cm->contact(mt.localId()); // force reload of (persisted) contact
QCOMPARE(mt.details<QContactPhoneNumber>().count(), 1);
// edit the original phone number detail, shouldn't duplicate the phone number
// NOTE: we need to reload the details before attempting to remove/edit them
// because the backend can change the ids.
pnums = mt.details<QContactPhoneNumber>();
foreach (const QContactPhoneNumber& pd, pnums) {
if (pd.number() == pn2.number())
pn2 = pd;
else if (pd.number() == pn.number())
pn = pd;
}
pn.setNumber("54321");
mt.saveDetail(&pn);
cm->saveContact(&mt);
mt = cm->contact(mt.localId());
QCOMPARE(mt.details<QContactPhoneNumber>().count(), 1);
QVERIFY(mt.detail<QContactPhoneNumber>() == pn);
// we also should do the same test for other details (for example, gender).
// if the backend cannot save multiple copies of a detail (eg, gender always overwrites)
// it should FAIL the save operation if the contact has multiple of that detail type,
// and set error to QContactManager::LimitReachedError.
QContactGender mtg, mtg2;
mtg.setGender(QContactGender::GenderFemale);
mtg2.setGender(QContactGender::GenderMale);
mt.saveDetail(&mtg);
QVERIFY(cm->saveContact(&mt)); // one gender is fine
mt.saveDetail(&mtg2);
QVERIFY(!cm->saveContact(&mt)); // two is not
//QCOMPARE(cm->error(), QContactManager::LimitReachedError); // should be LimitReachedError.
mt = cm->contact(mt.localId());
QVERIFY(mt.details<QContactGender>().count() == 1);
}
/* Save a new contact first */
int contactCount = cm->contacts().size();
QContactDetailDefinition nameDef = cm->detailDefinition(QContactName::DefinitionName, QContactType::TypeContact);
QContact alice = createContact(nameDef, "Alice", "inWonderland", "1234567");
QVERIFY(cm->saveContact(&alice));
QVERIFY(cm->error() == QContactManager::NoError);
contactCount += 1; // added a new contact.
QCOMPARE(cm->contacts().size(), contactCount);
/* Update name */
QContactName name = alice.detail(QContactName::DefinitionName);
saveContactName(&alice, nameDef, &name, "updated");
QVERIFY(cm->saveContact(&alice));
QVERIFY(cm->error() == QContactManager::NoError);
saveContactName(&alice, nameDef, &name, "updated2");
QVERIFY(cm->saveContact(&alice));
QVERIFY(cm->error() == QContactManager::NoError);
alice = cm->contact(alice.localId()); // force reload of (persisted) alice
QContact updated = cm->contact(alice.localId());
QContactName updatedName = updated.detail(QContactName::DefinitionName);
QCOMPARE(updatedName, name);
QCOMPARE(cm->contacts().size(), contactCount); // contact count should be the same, no new contacts
/* Test that adding a new detail doesn't cause unwanted side effects */
int detailCount = alice.details().size();
QContactEmailAddress email;
email.setEmailAddress("[email protected]");
alice.saveDetail(&email);
QVERIFY(cm->saveContact(&alice));
QCOMPARE(cm->contacts().size(), contactCount); // contact count shoudl be the same, no new contacts
// This test is dangerous, since backends can add timestamps etc...
detailCount += 1;
QCOMPARE(detailCount, alice.details().size()); // adding a detail should cause the detail count to increase by one.
/* Test that removal of fields in a detail works */
QContactPhoneNumber phn = alice.detail<QContactPhoneNumber>();
phn.setNumber("1234567");
phn.setContexts(QContactDetail::ContextHome);
alice.saveDetail(&phn);
QVERIFY(cm->saveContact(&alice));
alice = cm->contact(alice.localId()); // force reload of (persisted) alice
QVERIFY(alice.detail<QContactPhoneNumber>().contexts().contains(QContactDetail::ContextHome)); // check context saved.
phn = alice.detail<QContactPhoneNumber>(); // reload the detail, since it's key could have changed
phn.setContexts(QStringList()); // remove context field.
alice.saveDetail(&phn);
QVERIFY(cm->saveContact(&alice));
alice = cm->contact(alice.localId()); // force reload of (persisted) alice
QVERIFY(alice.detail<QContactPhoneNumber>().contexts().isEmpty()); // check context removed.
QCOMPARE(cm->contacts().size(), contactCount); // removal of a field of a detail shouldn't affect the contact count
// This test is dangerous, since backends can add timestamps etc...
QCOMPARE(detailCount, alice.details().size()); // removing a field from a detail should affect the detail count
/* Test that removal of details works */
phn = alice.detail<QContactPhoneNumber>(); // reload the detail, since it's key could have changed
alice.removeDetail(&phn);
QVERIFY(cm->saveContact(&alice));
alice = cm->contact(alice.localId()); // force reload of (persisted) alice
QVERIFY(alice.details<QContactPhoneNumber>().isEmpty()); // no such detail.
QCOMPARE(cm->contacts().size(), contactCount); // removal of a detail shouldn't affect the contact count
// This test is dangerous, since backends can add timestamps etc...
//detailCount -= 1;
//QCOMPARE(detailCount, alice.details().size()); // removing a detail should cause the detail count to decrease by one.
if (cm->hasFeature(QContactManager::Groups)) {
// Try changing types - not allowed
// from contact -> group
alice.setType(QContactType::TypeGroup);
QContactName na = alice.detail(QContactName::DefinitionName);
alice.removeDetail(&na);
QVERIFY(!cm->saveContact(&alice));
QVERIFY(cm->error() == QContactManager::AlreadyExistsError);
// from group -> contact
QContact jabberwock = createContact(nameDef, "", "", "1234567890");
jabberwock.setType(QContactType::TypeGroup);
QVERIFY(cm->saveContact(&jabberwock));
jabberwock.setType(QContactType::TypeContact);
QVERIFY(!cm->saveContact(&jabberwock));
QVERIFY(cm->error() == QContactManager::AlreadyExistsError);
}
}
void tst_QContactManager::remove()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
/* Save a new contact first */
QContactDetailDefinition nameDef = cm->detailDefinition(QContactName::DefinitionName, QContactType::TypeContact);
QContact alice = createContact(nameDef, "Alice", "inWonderland", "1234567");
QVERIFY(cm->saveContact(&alice));
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(alice.id() != QContactId());
/* Remove the created contact */
const int contactCount = cm->contactIds().count();
QVERIFY(cm->removeContact(alice.localId()));
QCOMPARE(cm->contactIds().count(), contactCount - 1);
QVERIFY(cm->contact(alice.localId()).isEmpty());
QCOMPARE(cm->error(), QContactManager::DoesNotExistError);
}
void tst_QContactManager::batch()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
/* First test null pointer operations */
QVERIFY(!cm->saveContacts(NULL, NULL));
QVERIFY(cm->error() == QContactManager::BadArgumentError);
QVERIFY(!cm->removeContacts(QList<QContactLocalId>(), NULL));
QVERIFY(cm->error() == QContactManager::BadArgumentError);
// Get supported name field
QString nameField = QContactName::FieldFirstName;
QContactDetailDefinition def = cm->detailDefinition(QContactName::DefinitionName);
if (!def.fields().contains(QContactName::FieldFirstName)) {
if(def.fields().contains(QContactName::FieldCustomLabel))
nameField = QLatin1String(QContactName::FieldCustomLabel);
else
QSKIP("This backend does not support the required name field!", SkipSingle);
}
/* Now add 3 contacts, all valid */
QContact a;
QContactName na;
na.setValue(nameField, "XXXXXX Albert");
a.saveDetail(&na);
QContact b;
QContactName nb;
nb.setValue(nameField, "XXXXXX Bob");
b.saveDetail(&nb);
QContact c;
QContactName nc;
nc.setValue(nameField, "XXXXXX Carol");
c.saveDetail(&nc);
QList<QContact> contacts;
contacts << a << b << c;
QMap<int, QContactManager::Error> errorMap;
// Add one dummy error to test if the errors are reset
errorMap.insert(0, QContactManager::NoError);
QVERIFY(cm->saveContacts(&contacts, &errorMap));
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(errorMap.count() == 0);
/* Make sure our contacts got updated too */
QVERIFY(contacts.count() == 3);
QVERIFY(contacts.at(0).id() != QContactId());
QVERIFY(contacts.at(1).id() != QContactId());
QVERIFY(contacts.at(2).id() != QContactId());
QVERIFY(contacts.at(0).detail(QContactName::DefinitionName) == na);
QVERIFY(contacts.at(1).detail(QContactName::DefinitionName) == nb);
QVERIFY(contacts.at(2).detail(QContactName::DefinitionName) == nc);
/* Retrieve again */
a = cm->contact(contacts.at(0).id().localId());
b = cm->contact(contacts.at(1).id().localId());
c = cm->contact(contacts.at(2).id().localId());
QVERIFY(contacts.at(0).detail(QContactName::DefinitionName) == na);
QVERIFY(contacts.at(1).detail(QContactName::DefinitionName) == nb);
QVERIFY(contacts.at(2).detail(QContactName::DefinitionName) == nc);
/* Save again, with a null error map */
QVERIFY(cm->saveContacts(&contacts, NULL));
QVERIFY(cm->error() == QContactManager::NoError);
/* Now make an update to them all */
QContactPhoneNumber number;
number.setNumber("1234567");
QVERIFY(contacts[0].saveDetail(&number));
number.setNumber("234567");
QVERIFY(contacts[1].saveDetail(&number));
number.setNumber("34567");
QVERIFY(contacts[2].saveDetail(&number));
QVERIFY(cm->saveContacts(&contacts, &errorMap));
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(errorMap.count() == 0);
/* Retrieve them and check them again */
a = cm->contact(contacts.at(0).id().localId());
b = cm->contact(contacts.at(1).id().localId());
c = cm->contact(contacts.at(2).id().localId());
QVERIFY(contacts.at(0).detail(QContactName::DefinitionName) == na);
QVERIFY(contacts.at(1).detail(QContactName::DefinitionName) == nb);
QVERIFY(contacts.at(2).detail(QContactName::DefinitionName) == nc);
QVERIFY(a.details<QContactPhoneNumber>().count() == 1);
QVERIFY(b.details<QContactPhoneNumber>().count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(a.details<QContactPhoneNumber>().at(0).number() == "1234567");
QVERIFY(b.details<QContactPhoneNumber>().at(0).number() == "234567");
QVERIFY(c.details<QContactPhoneNumber>().at(0).number() == "34567");
/* Retrieve them with the batch ID fetch API */
QList<QContactLocalId> batchIds;
batchIds << a.localId() << b.localId() << c.localId();
// Null error map first (doesn't crash)
QList<QContact> batchFetch = cm->contacts(batchIds, QContactFetchHint(), 0);
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(batchFetch.count() == 3);
QVERIFY(batchFetch.at(0).detail(QContactName::DefinitionName) == na);
QVERIFY(batchFetch.at(1).detail(QContactName::DefinitionName) == nb);
QVERIFY(batchFetch.at(2).detail(QContactName::DefinitionName) == nc);
// With error map
batchFetch = cm->contacts(batchIds, QContactFetchHint(), &errorMap);
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(errorMap.count() == 0);
QVERIFY(batchFetch.count() == 3);
QVERIFY(batchFetch.at(0).detail(QContactName::DefinitionName) == na);
QVERIFY(batchFetch.at(1).detail(QContactName::DefinitionName) == nb);
QVERIFY(batchFetch.at(2).detail(QContactName::DefinitionName) == nc);
/* Now an empty id */
batchIds.clear();
batchIds << QContactLocalId() << a.localId() << b.localId() << c.localId();
batchFetch = cm->contacts(batchIds, QContactFetchHint(), 0);
QVERIFY(cm->error() != QContactManager::NoError);
QVERIFY(batchFetch.count() == 4);
QVERIFY(batchFetch.at(0).detail(QContactName::DefinitionName) == QContactDetail());
QVERIFY(batchFetch.at(1).detail(QContactName::DefinitionName) == na);
QVERIFY(batchFetch.at(2).detail(QContactName::DefinitionName) == nb);
QVERIFY(batchFetch.at(3).detail(QContactName::DefinitionName) == nc);
batchFetch = cm->contacts(batchIds, QContactFetchHint(), &errorMap);
QVERIFY(cm->error() != QContactManager::NoError);
QVERIFY(batchFetch.count() == 4);
QVERIFY(errorMap.count() == 1);
QVERIFY(errorMap[0] == QContactManager::DoesNotExistError);
QVERIFY(batchFetch.at(0).detail(QContactName::DefinitionName) == QContactDetail());
QVERIFY(batchFetch.at(1).detail(QContactName::DefinitionName) == na);
QVERIFY(batchFetch.at(2).detail(QContactName::DefinitionName) == nb);
QVERIFY(batchFetch.at(3).detail(QContactName::DefinitionName) == nc);
/* Now multiple of the same contact */
batchIds.clear();
batchIds << c.localId() << b.localId() << c.localId() << a.localId() << a.localId();
batchFetch = cm->contacts(batchIds, QContactFetchHint(), &errorMap);
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(batchFetch.count() == 5);
QVERIFY(errorMap.count() == 0);
QVERIFY(batchFetch.at(0).detail(QContactName::DefinitionName) == nc);
QVERIFY(batchFetch.at(1).detail(QContactName::DefinitionName) == nb);
QVERIFY(batchFetch.at(2).detail(QContactName::DefinitionName) == nc);
QVERIFY(batchFetch.at(3).detail(QContactName::DefinitionName) == na);
QVERIFY(batchFetch.at(4).detail(QContactName::DefinitionName) == na);
/* Now delete them all */
QList<QContactLocalId> ids;
ids << a.id().localId() << b.id().localId() << c.id().localId();
QVERIFY(cm->removeContacts(ids, &errorMap));
QVERIFY(errorMap.count() == 0);
QVERIFY(cm->error() == QContactManager::NoError);
/* Make sure the contacts really don't exist any more */
QVERIFY(cm->contact(a.id().localId()).id() == QContactId());
QVERIFY(cm->contact(a.id().localId()).isEmpty());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
QVERIFY(cm->contact(b.id().localId()).id() == QContactId());
QVERIFY(cm->contact(b.id().localId()).isEmpty());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
QVERIFY(cm->contact(c.id().localId()).id() == QContactId());
QVERIFY(cm->contact(c.id().localId()).isEmpty());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
/* Now try removing with all invalid ids (e.g. the ones we just removed) */
ids.clear();
ids << a.id().localId() << b.id().localId() << c.id().localId();
QVERIFY(!cm->removeContacts(ids, &errorMap));
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
QVERIFY(errorMap.count() == 3);
QVERIFY(errorMap.values().at(0) == QContactManager::DoesNotExistError);
QVERIFY(errorMap.values().at(1) == QContactManager::DoesNotExistError);
QVERIFY(errorMap.values().at(2) == QContactManager::DoesNotExistError);
/* And again with a null error map */
QVERIFY(!cm->removeContacts(ids, NULL));
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
/* Try adding some new ones again, this time one with an error */
contacts.clear();
a.setId(QContactId());
b.setId(QContactId());
c.setId(QContactId());
/* Make B the bad guy */
QContactDetail bad("does not exist and will break if you add it");
bad.setValue("This is also bad", "Very bad");
b.saveDetail(&bad);
contacts << a << b << c;
QVERIFY(!cm->saveContacts(&contacts, &errorMap));
/* We can't really say what the error will be.. maybe bad argument, maybe invalid detail */
QVERIFY(cm->error() != QContactManager::NoError);
/* It's permissible to fail all the adds, or to add the successful ones */
QVERIFY(errorMap.count() > 0);
QVERIFY(errorMap.count() <= 3);
// A might have gone through
if (errorMap.keys().contains(0)) {
QVERIFY(errorMap.value(0) != QContactManager::NoError);
QVERIFY(contacts.at(0).id() == QContactId());
} else {
QVERIFY(contacts.at(0).id() != QContactId());
}
// B should have failed
QVERIFY(errorMap.value(1) == QContactManager::InvalidDetailError);
QVERIFY(contacts.at(1).id() == QContactId());
// C might have gone through
if (errorMap.keys().contains(2)) {
QVERIFY(errorMap.value(2) != QContactManager::NoError);
QVERIFY(contacts.at(2).id() == QContactId());
} else {
QVERIFY(contacts.at(2).id() != QContactId());
}
/* Fix up B and re save it */
QVERIFY(contacts[1].removeDetail(&bad));
QVERIFY(cm->saveContacts(&contacts, &errorMap));
QVERIFY(errorMap.count() == 0);
QVERIFY(cm->error() == QContactManager::NoError);
// Save and remove a fourth contact. Store the id.
a.setId(QContactId());
QVERIFY(cm->saveContact(&a));
QContactLocalId removedId = a.localId();
QVERIFY(cm->removeContact(removedId));
/* Now delete 3 items, but with one bad argument */
ids.clear();
ids << contacts.at(0).id().localId();
ids << removedId;
ids << contacts.at(2).id().localId();
QVERIFY(!cm->removeContacts(ids, &errorMap));
QVERIFY(cm->error() != QContactManager::NoError);
/* Again, the backend has the choice of either removing the successful ones, or not */
QVERIFY(errorMap.count() > 0);
QVERIFY(errorMap.count() <= 3);
// A might have gone through
if (errorMap.keys().contains(0)) {
QVERIFY(errorMap.value(0) != QContactManager::NoError);
QVERIFY(contacts.at(0).id() == QContactId());
} else {
QVERIFY(contacts.at(0).id() != QContactId());
}
/* B should definitely have failed */
QVERIFY(errorMap.value(1) == QContactManager::DoesNotExistError);
QVERIFY(ids.at(1) == removedId);
// A might have gone through
if (errorMap.keys().contains(2)) {
QVERIFY(errorMap.value(2) != QContactManager::NoError);
QVERIFY(contacts.at(2).id() == QContactId());
} else {
QVERIFY(contacts.at(2).id() != QContactId());
}
}
void tst_QContactManager::invalidManager()
{
/* Create an invalid manager */
QContactManager manager("this should never work");
QVERIFY(manager.managerName() == "invalid");
QVERIFY(manager.managerVersion() == 0);
/* also, test the other ctor behaviour is sane also */
QContactManager anotherManager("this should never work", 15);
QVERIFY(anotherManager.managerName() == "invalid");
QVERIFY(anotherManager.managerVersion() == 0);
/* Now test that all the operations fail */
QVERIFY(manager.contactIds().count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QContact foo;
QContactName nf;
nf.setLastName("Lastname");
foo.saveDetail(&nf);
QVERIFY(manager.synthesizedContactDisplayLabel(foo).isEmpty());
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.saveContact(&foo) == false);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(foo.id() == QContactId());
QVERIFY(manager.contactIds().count() == 0);
QVERIFY(manager.contact(foo.id().localId()).id() == QContactId());
QVERIFY(manager.contact(foo.id().localId()).isEmpty());
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.removeContact(foo.id().localId()) == false);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QMap<int, QContactManager::Error> errorMap;
errorMap.insert(0, QContactManager::NoError);
QVERIFY(!manager.saveContacts(0, &errorMap));
QVERIFY(manager.errorMap().count() == 0);
QVERIFY(errorMap.count() == 0);
QVERIFY(manager.error() == QContactManager::BadArgumentError);
/* filters */
QContactFilter f; // matches everything
QContactDetailFilter df;
df.setDetailDefinitionName(QContactDisplayLabel::DefinitionName, QContactDisplayLabel::FieldLabel);
QVERIFY(manager.contactIds(QContactFilter()).count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.contactIds(df).count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.contactIds(f | f).count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.contactIds(df | df).count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.isFilterSupported(f) == false);
QVERIFY(manager.isFilterSupported(df) == false);
QList<QContact> list;
list << foo;
QVERIFY(!manager.saveContacts(&list, &errorMap));
QVERIFY(errorMap.count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(!manager.removeContacts(QList<QContactLocalId>(), &errorMap));
QVERIFY(errorMap.count() == 0);
QVERIFY(manager.error() == QContactManager::BadArgumentError);
QList<QContactLocalId> idlist;
idlist << foo.id().localId();
QVERIFY(!manager.removeContacts(idlist, &errorMap));
QVERIFY(errorMap.count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
/* Detail definitions */
QVERIFY(manager.detailDefinitions().count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QContactDetailDefinition def;
def.setUnique(true);
def.setName("new field");
QMap<QString, QContactDetailFieldDefinition> fields;
QContactDetailFieldDefinition currField;
currField.setDataType(QVariant::String);
fields.insert("value", currField);
def.setFields(fields);
QVERIFY(manager.saveDetailDefinition(def, QContactType::TypeContact) == false);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QVERIFY(manager.saveDetailDefinition(def) == false);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QVERIFY(manager.detailDefinitions().count(QContactType::TypeContact) == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QVERIFY(manager.detailDefinitions().count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QVERIFY(manager.detailDefinition("new field").name() == QString());
QVERIFY(manager.removeDetailDefinition(def.name(), QContactType::TypeContact) == false);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QVERIFY(manager.removeDetailDefinition(def.name()) == false);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
QVERIFY(manager.detailDefinitions().count() == 0);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::InvalidContactTypeError);
/* Self contact id */
QVERIFY(!manager.setSelfContactId(QContactLocalId(12)));
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.selfContactId() == QContactLocalId());
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::DoesNotExistError);
/* Relationships */
QContactId idOne, idTwo;
idOne.setLocalId(QContactLocalId(15));
idOne.setManagerUri(QString());
idTwo.setLocalId(QContactLocalId(22));
idTwo.setManagerUri(QString());
QContactRelationship invalidRel;
invalidRel.setFirst(idOne);
invalidRel.setSecond(idTwo);
QList<QContactRelationship> invalidRelList;
invalidRelList << invalidRel;
QVERIFY(!manager.saveRelationship(&invalidRel));
QVERIFY(manager.error() == QContactManager::NotSupportedError);
QVERIFY(manager.relationships().isEmpty());
QVERIFY(manager.error() == QContactManager::NotSupportedError);
manager.saveRelationships(&invalidRelList, NULL);
QVERIFY(manager.error() == QContactManager::NotSupportedError);
manager.removeRelationships(invalidRelList, NULL);
QVERIFY(manager.error() == QContactManager::NotSupportedError || manager.error() == QContactManager::DoesNotExistError);
/* Capabilities */
QVERIFY(manager.supportedDataTypes().count() == 0);
QVERIFY(!manager.hasFeature(QContactManager::ActionPreferences));
QVERIFY(!manager.hasFeature(QContactManager::MutableDefinitions));
}
void tst_QContactManager::memoryManager()
{
QMap<QString, QString> params;
QContactManager m1("memory");
params.insert("random", "shouldNotBeUsed");
QContactManager m2("memory", params);
params.insert("id", "shouldBeUsed");
QContactManager m3("memory", params);
QContactManager m4("memory", params);
params.insert("id", QString(""));
QContactManager m5("memory", params); // should be another anonymous
QVERIFY(m1.hasFeature(QContactManager::ActionPreferences));
QVERIFY(m1.hasFeature(QContactManager::MutableDefinitions));
QVERIFY(m1.hasFeature(QContactManager::Anonymous));
// add a contact to each of m1, m2, m3
QContact c;
QContactName nc;
nc.setFirstName("John");
nc.setLastName("Civilian");
c.saveDetail(&nc);
m1.saveContact(&c);
c.setId(QContactId());
QContact c2;
QContactName nc2 = c2.detail(QContactName::DefinitionName);
c2 = c;
nc2.setMiddleName("Public");
c2.saveDetail(&nc2);
m2.saveContact(&c2); // save c2 first; c will be given a higher id
m2.saveContact(&c); // save c to m2
c.setId(QContactId());
nc.setSuffix("MD");
c.saveDetail(&nc);
m3.saveContact(&c);
/* test that m1 != m2 != m3 and that m3 == m4 */
// check the counts are correct - especially note m4 and m3.
QCOMPARE(m1.contactIds().count(), 1);
QCOMPARE(m2.contactIds().count(), 2);
QCOMPARE(m3.contactIds().count(), 1);
QCOMPARE(m4.contactIds().count(), 1);
QCOMPARE(m5.contactIds().count(), 0);
// remove c2 from m2 - ensure that this doesn't affect any other manager.
m2.removeContact(c2.id().localId());
QCOMPARE(m1.contactIds().count(), 1);
QCOMPARE(m2.contactIds().count(), 1);
QCOMPARE(m3.contactIds().count(), 1);
QCOMPARE(m4.contactIds().count(), 1);
QCOMPARE(m5.contactIds().count(), 0);
// check that the contacts contained within are different.
// note that in the m1->m2 case, only the id will be different!
QVERIFY(m1.contact(m1.contactIds().at(0)) != m2.contact(m2.contactIds().at(0)));
QVERIFY(m1.contact(m1.contactIds().at(0)) != m3.contact(m3.contactIds().at(0)));
QVERIFY(m2.contact(m2.contactIds().at(0)) != m3.contact(m3.contactIds().at(0)));
QVERIFY(m3.contact(m3.contactIds().at(0)) == m4.contact(m4.contactIds().at(0)));
// now, we should be able to remove from m4, and have m3 empty
QVERIFY(m4.removeContact(c.id().localId()));
QCOMPARE(m3.contactIds().count(), 0);
QCOMPARE(m4.contactIds().count(), 0);
QCOMPARE(m5.contactIds().count(), 0);
}
#if defined(SYMBIAN_BACKEND_S60_VERSION_31) || defined(SYMBIAN_BACKEND_S60_VERSION_32) || defined(SYMBIAN_BACKEND_S60_VERSION_50)
/* Some symbian-specific unit tests. */
void tst_QContactManager::symbianManager()
{
QFETCH(QString, uri);
QString managerName;
QMap<QString, QString> managerParameters;
QContactManager::parseUri(uri, &managerName, &managerParameters);
if (managerName != QString("symbian"))
return;
/* Firstly, a test for invalid storage type crash - QTMOBILITY-470 */
// open the contact database, and create a new contact
CContactDatabase* cntdb = CContactDatabase::OpenL();
CleanupStack::PushL(cntdb);
CContactItem* testItem = CContactCard::NewLC();
// create a new thumbnail field with (invalid) storage type KStorageTypeText instead of KStorageTypeStore
CContactItemField* thumbnailField;
thumbnailField = CContactItemField::NewLC(KStorageTypeText, KUidContactFieldPicture);
thumbnailField->SetMapping(KUidContactFieldVCardMapPHOTO);
thumbnailField->AddFieldTypeL(KUidContactFieldVCardMapBMP);
thumbnailField->ResetStore();
// set the thumbnail data in the thumbnail field, and add it to the contact
_LIT8(KThumbnailDataString, "Dummy Thumbnail Data String");
thumbnailField->StoreStorage()->SetThingL(KThumbnailDataString);
testItem->AddFieldL(*thumbnailField);
CleanupStack::Pop(thumbnailField);
// save the updated contact.
cntdb->CommitContactL(*testItem);
cntdb->CloseContactL(testItem->Id());
CleanupStack::PopAndDestroy(2); // testItem, cntdb
// force database to read thumbnail with invalid storage type. crash if not handled properly.
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
QList<QContact> allContacts = cm->contacts();
}
#endif
void tst_QContactManager::nameSynthesis_data()
{
QTest::addColumn<QString>("expected");
QTest::addColumn<bool>("addname");
QTest::addColumn<QString>("prefix");
QTest::addColumn<QString>("first");
QTest::addColumn<QString>("middle");
QTest::addColumn<QString>("last");
QTest::addColumn<QString>("suffix");
QTest::addColumn<bool>("addcompany");
QTest::addColumn<QString>("company");
QTest::addColumn<bool>("addname2");
QTest::addColumn<QString>("secondprefix");
QTest::addColumn<QString>("secondfirst");
QTest::addColumn<QString>("secondmiddle");
QTest::addColumn<QString>("secondlast");
QTest::addColumn<QString>("secondsuffix");
QTest::addColumn<bool>("addcompany2");
QTest::addColumn<QString>("secondcompany");
QString e; // empty string.. gets a work out
/* Various empty ones */
QTest::newRow("empty contact") << e
<< false << e << e << e << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("empty name") << e
<< true << e << e << e << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("empty names") << e
<< true << e << e << e << e << e
<< false << e
<< true << e << e << e << e << e
<< false << e;
QTest::newRow("empty org") << e
<< false << e << e << e << e << e
<< true << e
<< false << e << e << e << e << e
<< true << e;
QTest::newRow("empty orgs") << e
<< false << e << e << e << e << e
<< true << e
<< false << e << e << e << e << e
<< true << e;
QTest::newRow("empty orgs and names") << e
<< true << e << e << e << e << e
<< true << e
<< true << e << e << e << e << e
<< true << e;
/* Single values */
QTest::newRow("prefix") << "Prefix"
<< true << "Prefix" << e << e << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("first") << "First"
<< true << e << "First" << e << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("middle") << "Middle"
<< true << e << e << "Middle" << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("last") << "Last"
<< true << e << e << e << "Last" << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("suffix") << "Suffix"
<< true << e << e << e << e << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
/* Single values in the second name */
QTest::newRow("prefix in second") << "Prefix"
<< false << "Prefix" << e << e << e << e
<< false << e
<< true << "Prefix" << e << e << e << e
<< false << e;
QTest::newRow("first in second") << "First"
<< false << e << "First" << e << e << e
<< false << e
<< true << e << "First" << e << e << e
<< false << e;
QTest::newRow("middle in second") << "Middle"
<< false << e << e << "Middle" << e << e
<< false << e
<< true << e << e << "Middle" << e << e
<< false << e;
QTest::newRow("last in second") << "Last"
<< false << e << e << e << "Last" << e
<< false << e
<< true << e << e << e << "Last" << e
<< false << e;
QTest::newRow("suffix in second") << "Suffix"
<< false << e << e << e << e << "Suffix"
<< false << e
<< true << e << e << e << e << "Suffix"
<< false << e;
/* Multiple name values */
QTest::newRow("prefix first") << "Prefix First"
<< true << "Prefix" << "First" << e << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("prefix middle") << "Prefix Middle"
<< true << "Prefix" << e << "Middle" << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("prefix last") << "Prefix Last"
<< true << "Prefix" << e << e << "Last" << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("prefix suffix") << "Prefix Suffix"
<< true << "Prefix" << e << e << e << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("first middle") << "First Middle"
<< true << e << "First" << "Middle" << e << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("first last") << "First Last"
<< true << e << "First" << e << "Last" << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("first suffix") << "First Suffix"
<< true << e << "First" << e << e << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("middle last") << "Middle Last"
<< true << e << e << "Middle" << "Last" << e
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("middle suffix") << "Middle Suffix"
<< true << e << e << "Middle" << e << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("last suffix") << "Last Suffix"
<< true << e << e << e << "Last" << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
/* Everything.. */
QTest::newRow("all name") << "Prefix First Middle Last Suffix"
<< true << "Prefix" << "First" << "Middle" << "Last" << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("all name second") << "Prefix First Middle Last Suffix"
<< false << "Prefix" << "First" << "Middle" << "Last" << "Suffix"
<< false << e
<< true << "Prefix" << "First" << "Middle" << "Last" << "Suffix"
<< false << e;
/* Org */
QTest::newRow("org") << "Company"
<< false << e << e << e << e << e
<< true << "Company"
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("second org") << "Company"
<< false << e << e << e << e << e
<< false << e
<< false << e << e << e << e << e
<< true << "Company";
/* Mix */
QTest::newRow("org and empty name") << "Company"
<< true << e << e << e << e << e
<< true << "Company"
<< false << e << e << e << e << e
<< false << e;
QTest::newRow("name and empty org") << "Prefix First Middle Last Suffix"
<< true << "Prefix" << "First" << "Middle" << "Last" << "Suffix"
<< false << e
<< false << e << e << e << e << e
<< false << e;
/* names are preferred to orgs */
QTest::newRow("name and org") << "Prefix First Middle Last Suffix"
<< true << "Prefix" << "First" << "Middle" << "Last" << "Suffix"
<< true << "Company"
<< false << e << e << e << e << e
<< false << e;
}
void tst_QContactManager::nameSynthesis()
{
QContactManager cm("memory");
QFETCH(QString, expected);
QFETCH(QString, prefix);
QFETCH(QString, first);
QFETCH(QString, middle);
QFETCH(QString, last);
QFETCH(QString, suffix);
QFETCH(QString, company);
QFETCH(QString, secondprefix);
QFETCH(QString, secondfirst);
QFETCH(QString, secondmiddle);
QFETCH(QString, secondlast);
QFETCH(QString, secondsuffix);
QFETCH(QString, secondcompany);
QFETCH(bool, addname);
QFETCH(bool, addname2);
QFETCH(bool, addcompany);
QFETCH(bool, addcompany2);
/* Test the default name synthesis code */
QContact c;
QContactName name, name2;
QContactOrganization org, org2;
name.setPrefix(prefix);
name.setFirstName(first);
name.setMiddleName(middle);
name.setLastName(last);
name.setSuffix(suffix);
name2.setPrefix(secondprefix);
name2.setFirstName(secondfirst);
name2.setMiddleName(secondmiddle);
name2.setLastName(secondlast);
name2.setSuffix(secondsuffix);
org.setName(company);
org2.setName(secondcompany);
if (addname)
c.saveDetail(&name);
if (addname2)
c.saveDetail(&name2);
if (addcompany)
c.saveDetail(&org);
if (addcompany2)
c.saveDetail(&org2);
// Finally!
QCOMPARE(cm.synthesizedContactDisplayLabel(c), expected);
}
void tst_QContactManager::compatibleContact_data()
{
QTest::addColumn<QContact>("input");
QTest::addColumn<QContact>("expected");
QTest::addColumn<QContactManager::Error>("error");
QContact baseContact;
QContactName name;
name.setFirstName(QLatin1String("First"));
baseContact.saveDetail(&name);
{
QTest::newRow("already compatible") << baseContact << baseContact << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactDetail detail("UnknownDetail");
detail.setValue("Key", QLatin1String("Value"));
contact.saveDetail(&detail);
QTest::newRow("unknown detail") << contact << baseContact << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactType type1;
type1.setType(QContactType::TypeContact);
contact.saveDetail(&type1);
QContactType type2;
type2.setType(QContactType::TypeGroup);
contact.saveDetail(&type2);
QContact expected(baseContact);
expected.saveDetail(&type2);
QTest::newRow("duplicate unique field") << contact << expected << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactPhoneNumber phoneNumber;
phoneNumber.setValue("UnknownKey", "Value");
contact.saveDetail(&phoneNumber);
QTest::newRow("unknown field") << contact << baseContact << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactDisplayLabel displayLabel;
displayLabel.setValue(QContactDisplayLabel::FieldLabel, QStringList("Value"));
contact.saveDetail(&displayLabel);
QTest::newRow("wrong type") << contact << baseContact << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactPhoneNumber phoneNumber1;
phoneNumber1.setNumber(QLatin1String("1234"));
phoneNumber1.setSubTypes(QStringList()
<< QContactPhoneNumber::SubTypeMobile
<< QContactPhoneNumber::SubTypeVoice
<< QLatin1String("InvalidSubtype"));
contact.saveDetail(&phoneNumber1);
QContact expected(baseContact);
QContactPhoneNumber phoneNumber2;
phoneNumber2.setNumber(QLatin1String("1234"));
phoneNumber2.setSubTypes(QStringList()
<< QContactPhoneNumber::SubTypeMobile
<< QContactPhoneNumber::SubTypeVoice);
expected.saveDetail(&phoneNumber2);
QTest::newRow("bad value (list)") << contact << expected << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactPhoneNumber phoneNumber1;
phoneNumber1.setNumber(QLatin1String("1234"));
phoneNumber1.setSubTypes(QStringList(QLatin1String("InvalidSubtype")));
contact.saveDetail(&phoneNumber1);
QContact expected(baseContact);
QContactPhoneNumber phoneNumber2;
phoneNumber2.setNumber(QLatin1String("1234"));
expected.saveDetail(&phoneNumber2);
QTest::newRow("all bad value (list)") << contact << expected << QContactManager::NoError;
}
{
QContact contact(baseContact);
QContactGender gender;
gender.setGender(QLatin1String("UnknownGender"));
contact.saveDetail(&gender);
QTest::newRow("bad value (string)") << contact << baseContact << QContactManager::NoError;
}
{
QContact contact;
QContactGender gender;
gender.setGender(QLatin1String("UnknownGender"));
contact.saveDetail(&gender);
QTest::newRow("bad value (string)") << contact << QContact() << QContactManager::DoesNotExistError;
}
}
void tst_QContactManager::compatibleContact()
{
QContactManager cm("memory");
QFETCH(QContact, input);
QFETCH(QContact, expected);
QFETCH(QContactManager::Error, error);
QCOMPARE(cm.compatibleContact(input), expected);
QCOMPARE(cm.error(), error);
}
void tst_QContactManager::contactValidation()
{
/* Use the memory engine as a reference (validation is not engine specific) */
QScopedPointer<QContactManager> cm(new QContactManager("memory"));
QContact c;
/*
* Add some definitions for testing:
*
* 1) a unique detail
* 2) a detail with restricted values
* 3) a create only detail
* 4) a unique create only detail
*/
QContactDetailDefinition uniqueDef;
QMap<QString, QContactDetailFieldDefinition> fields;
QContactDetailFieldDefinition field;
field.setDataType(QVariant::String);
fields.insert("value", field);
uniqueDef.setName("UniqueDetail");
uniqueDef.setFields(fields);
uniqueDef.setUnique(true);
QVERIFY(cm->saveDetailDefinition(uniqueDef));
QContactDetailDefinition restrictedDef;
restrictedDef.setName("RestrictedDetail");
fields.clear();
field.setAllowableValues(QVariantList() << "One" << "Two" << "Three");
fields.insert("value", field);
restrictedDef.setFields(fields);
QVERIFY(cm->saveDetailDefinition(restrictedDef));
// first, test an invalid definition
QContactDetail d1 = QContactDetail("UnknownDefinition");
d1.setValue("test", "test");
c.saveDetail(&d1);
QVERIFY(!cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::InvalidDetailError);
c.removeDetail(&d1);
// second, test an invalid uniqueness constraint
QContactDetail d2 = QContactDetail("UniqueDetail");
d2.setValue("value", "test");
c.saveDetail(&d2);
// One unique should be ok
QVERIFY(cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::NoError);
// Two uniques should not be ok
QContactDetail d3 = QContactDetail("UniqueDetail");
d3.setValue("value", "test2");
c.saveDetail(&d3);
QVERIFY(!cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::AlreadyExistsError);
c.removeDetail(&d3);
c.removeDetail(&d2);
// third, test an invalid field name
QContactDetail d4 = QContactDetail(QContactPhoneNumber::DefinitionName);
d4.setValue("test", "test");
c.saveDetail(&d4);
QVERIFY(!cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::InvalidDetailError);
c.removeDetail(&d4);
// fourth, test an invalid field data type
QContactDetail d5 = QContactDetail(QContactPhoneNumber::DefinitionName);
d5.setValue(QContactPhoneNumber::FieldNumber, QDateTime::currentDateTime());
c.saveDetail(&d5);
QVERIFY(!cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::InvalidDetailError);
c.removeDetail(&d5);
// fifth, test an invalid field value (not in the allowed list)
QContactDetail d6 = QContactDetail("RestrictedDetail");
d6.setValue("value", "Seven"); // not in One, Two or Three
c.saveDetail(&d6);
QVERIFY(!cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::InvalidDetailError);
c.removeDetail(&d6);
/* Now a valid value */
d6.setValue("value", "Two");
c.saveDetail(&d6);
QVERIFY(cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::NoError);
c.removeDetail(&d6);
// Test a completely valid one.
QContactDetail d7 = QContactDetail(QContactPhoneNumber::DefinitionName);
d7.setValue(QContactPhoneNumber::FieldNumber, "0123456");
c.saveDetail(&d7);
QVERIFY(cm->saveContact(&c));
QCOMPARE(cm->error(), QContactManager::NoError);
c.removeDetail(&d7);
}
void tst_QContactManager::signalEmission()
{
QTest::qWait(500); // clear the signal queue
QFETCH(QString, uri);
QScopedPointer<QContactManager> m1(QContactManager::fromUri(uri));
qRegisterMetaType<QContactLocalId>("QContactLocalId");
qRegisterMetaType<QList<QContactLocalId> >("QList<QContactLocalId>");
QSignalSpy spyCA(m1.data(), SIGNAL(contactsAdded(QList<QContactLocalId>)));
QSignalSpy spyCM(m1.data(), SIGNAL(contactsChanged(QList<QContactLocalId>)));
QSignalSpy spyCR(m1.data(), SIGNAL(contactsRemoved(QList<QContactLocalId>)));
QList<QVariant> args;
QList<QContactLocalId> arg;
QContact c;
QList<QContact> batchAdd;
QList<QContactLocalId> batchRemove;
QList<QContactLocalId> sigids;
int addSigCount = 0; // the expected signal counts.
int modSigCount = 0;
int remSigCount = 0;
QContactDetailDefinition nameDef = m1->detailDefinition(QContactName::DefinitionName, QContactType::TypeContact);
// verify add emits signal added
QContactName nc;
saveContactName(&c, nameDef, &nc, "John");
QVERIFY(m1->saveContact(&c));
QContactLocalId cid = c.id().localId();
addSigCount += 1;
QTRY_COMPARE(spyCA.count(), addSigCount);
args = spyCA.takeFirst();
addSigCount -= 1;
arg = args.first().value<QList<quint32> >();
QVERIFY(arg.count() == 1);
QCOMPARE(QContactLocalId(arg.at(0)), cid);
// verify save modified emits signal changed
saveContactName(&c, nameDef, &nc, "Citizen");
QVERIFY(m1->saveContact(&c));
modSigCount += 1;
QTRY_COMPARE(spyCM.count(), modSigCount);
args = spyCM.takeFirst();
modSigCount -= 1;
arg = args.first().value<QList<quint32> >();
QVERIFY(arg.count() == 1);
QCOMPARE(QContactLocalId(arg.at(0)), cid);
// verify remove emits signal removed
m1->removeContact(c.id().localId());
remSigCount += 1;
QTRY_COMPARE(spyCR.count(), remSigCount);
args = spyCR.takeFirst();
remSigCount -= 1;
arg = args.first().value<QList<quint32> >();
QVERIFY(arg.count() == 1);
QCOMPARE(QContactLocalId(arg.at(0)), cid);
// verify multiple adds works as advertised
QContact c2, c3;
QContactName nc2, nc3;
saveContactName(&c2, nameDef, &nc2, "Mark");
saveContactName(&c3, nameDef, &nc3, "Garry");
#if defined(Q_OS_SYMBIAN)
// TODO: symbiansim backend fails this test currently. Commented out for
// now. Will be fixed later.
if(!uri.contains("symbiansim")) {
QVERIFY(!m1->saveContact(&c)); // saving contact with nonexistent id fails
}
#endif
QVERIFY(m1->saveContact(&c2));
addSigCount += 1;
QVERIFY(m1->saveContact(&c3));
addSigCount += 1;
QTRY_COMPARE(spyCM.count(), modSigCount);
QTRY_COMPARE(spyCA.count(), addSigCount);
// verify multiple modifies works as advertised
saveContactName(&c2, nameDef, &nc2, "M.");
QVERIFY(m1->saveContact(&c2));
modSigCount += 1;
saveContactName(&c2, nameDef, &nc2, "Mark");
saveContactName(&c3, nameDef, &nc3, "G.");
QVERIFY(m1->saveContact(&c2));
modSigCount += 1;
QVERIFY(m1->saveContact(&c3));
modSigCount += 1;
QTRY_COMPARE(spyCM.count(), modSigCount);
// verify multiple removes works as advertised
m1->removeContact(c3.id().localId());
remSigCount += 1;
m1->removeContact(c2.id().localId());
remSigCount += 1;
QTRY_COMPARE(spyCR.count(), remSigCount);
QVERIFY(!m1->removeContact(c.id().localId())); // not saved.
/* Now test the batch equivalents */
spyCA.clear();
spyCM.clear();
spyCR.clear();
/* Batch adds - set ids to zero so add succeeds. */
c.setId(QContactId());
c2.setId(QContactId());
c3.setId(QContactId());
batchAdd << c << c2 << c3;
QMap<int, QContactManager::Error> errorMap;
QVERIFY(m1->saveContacts(&batchAdd, &errorMap));
QVERIFY(batchAdd.count() == 3);
c = batchAdd.at(0);
c2 = batchAdd.at(1);
c3 = batchAdd.at(2);
/* We basically loop, processing events, until we've seen an Add signal for each contact */
sigids.clear();
QTRY_WAIT( while(spyCA.size() > 0) {sigids += spyCA.takeFirst().at(0).value<QList<QContactLocalId> >(); }, sigids.contains(c.localId()) && sigids.contains(c2.localId()) && sigids.contains(c3.localId()));
QTRY_COMPARE(spyCM.count(), 0);
QTRY_COMPARE(spyCR.count(), 0);
/* Batch modifies */
QContactName modifiedName = c.detail(QContactName::DefinitionName);
saveContactName(&c, nameDef, &modifiedName, "Modified number 1");
modifiedName = c2.detail(QContactName::DefinitionName);
saveContactName(&c2, nameDef, &modifiedName, "Modified number 2");
modifiedName = c3.detail(QContactName::DefinitionName);
saveContactName(&c3, nameDef, &modifiedName, "Modified number 3");
batchAdd.clear();
batchAdd << c << c2 << c3;
QVERIFY(m1->saveContacts(&batchAdd, &errorMap));
sigids.clear();
QTRY_WAIT( while(spyCM.size() > 0) {sigids += spyCM.takeFirst().at(0).value<QList<QContactLocalId> >(); }, sigids.contains(c.localId()) && sigids.contains(c2.localId()) && sigids.contains(c3.localId()));
/* Batch removes */
batchRemove << c.id().localId() << c2.id().localId() << c3.id().localId();
QVERIFY(m1->removeContacts(batchRemove, &errorMap));
sigids.clear();
QTRY_WAIT( while(spyCR.size() > 0) {sigids += spyCR.takeFirst().at(0).value<QList<QContactLocalId> >(); }, sigids.contains(c.localId()) && sigids.contains(c2.localId()) && sigids.contains(c3.localId()));
QTRY_COMPARE(spyCA.count(), 0);
QTRY_COMPARE(spyCM.count(), 0);
QScopedPointer<QContactManager> m2(QContactManager::fromUri(uri));
// During construction SIM backend (m2) will try writing contacts with
// nickname, email and additional number to find out if the SIM card
// will support these fields. The other backend (m1) will then receive
// signals about that. These need to be caught so they don't interfere
// with the tests. (This trial and error method is used because existing
// API for checking the availability of these fields is not public.)
// NOTE: This applies only to pre 10.1 platforms (S60 3.1, 3.2, ect.)
if (uri.contains("symbiansim")) {
QTest::qWait(0);
spyCA.clear();
spyCM.clear();
spyCR.clear();
}
QVERIFY(m1->hasFeature(QContactManager::Anonymous) ==
m2->hasFeature(QContactManager::Anonymous));
/* Now some cross manager testing */
if (!m1->hasFeature(QContactManager::Anonymous)) {
// verify that signals are emitted for modifications made to other managers (same id).
QContactName ncs = c.detail(QContactName::DefinitionName);
saveContactName(&c, nameDef, &ncs, "Test");
c.setId(QContactId()); // reset id so save can succeed.
QVERIFY(m2->saveContact(&c));
saveContactName(&c, nameDef, &ncs, "Test2");
QVERIFY(m2->saveContact(&c));
QTRY_COMPARE(spyCA.count(), 1); // check that we received the update signals.
QTRY_COMPARE(spyCM.count(), 1); // check that we received the update signals.
m2->removeContact(c.localId());
QTRY_COMPARE(spyCR.count(), 1); // check that we received the remove signal.
}
}
void tst_QContactManager::errorStayingPut()
{
/* Make sure that when we clone a manager, we don't clone the error */
QMap<QString, QString> params;
params.insert("id", "error isolation test");
QContactManager m1("memory",params);
QVERIFY(m1.error() == QContactManager::NoError);
/* Remove an invalid contact to get an error */
QVERIFY(m1.removeContact(0) == false);
QVERIFY(m1.error() == QContactManager::DoesNotExistError);
/* Create a new manager with hopefully the same backend */
QContactManager m2("memory", params);
QVERIFY(m1.error() == QContactManager::DoesNotExistError);
QVERIFY(m2.error() == QContactManager::NoError);
/* Cause an error on the other ones and check the first is not affected */
m2.saveContacts(0, 0);
QVERIFY(m1.error() == QContactManager::DoesNotExistError);
QVERIFY(m2.error() == QContactManager::BadArgumentError);
QContact c;
QContactDetail d("This does not exist and if it does this will break");
d.setValue("Value that also doesn't exist", 5);
c.saveDetail(&d);
QVERIFY(m1.saveContact(&c) == false);
QVERIFY(m1.error() == QContactManager::InvalidDetailError);
QVERIFY(m2.error() == QContactManager::BadArgumentError);
}
void tst_QContactManager::validateDefinitions(const QMap<QString, QContactDetailDefinition>& defs) const
{
// Do some sanity checking on the definitions first
if (defs.keys().count() != defs.uniqueKeys().count()) {
qDebug() << "ERROR - duplicate definitions with the same name:";
QList<QString> defkeys = defs.keys();
foreach(QString uniq, defs.uniqueKeys()) {
if (defkeys.count(uniq) > 1) {
qDebug() << QString(" %1").arg(uniq).toAscii().constData();
defkeys.removeAll(uniq);
}
}
QVERIFY(defs.keys().count() == defs.uniqueKeys().count());
}
foreach(QContactDetailDefinition def, defs.values()) {
QMap<QString, QContactDetailFieldDefinition> fields = def.fields();
// Again some sanity checking
if (fields.keys().count() != fields.uniqueKeys().count()) {
qDebug() << "ERROR - duplicate fields with the same name:";
QList<QString> defkeys = fields.keys();
foreach(QString uniq, fields.uniqueKeys()) {
if (defkeys.count(uniq) > 1) {
qDebug() << QString(" %2::%1").arg(uniq).arg(def.name()).toAscii().constData();
defkeys.removeAll(uniq);
}
}
QVERIFY(fields.keys().count() == fields.uniqueKeys().count());
}
foreach(QContactDetailFieldDefinition field, def.fields().values()) {
// Sanity check the allowed values
if (field.allowableValues().count() > 0) {
if (field.dataType() == QVariant::StringList) {
// We accept QString or QStringList allowed values
foreach(QVariant var, field.allowableValues()) {
if (var.type() != QVariant::String && var.type() != QVariant::StringList) {
QString foo;
QDebug dbg(&foo);
dbg.nospace() << var;
qDebug().nospace() << "Field " << QString("%1::%2").arg(def.name()).arg(def.fields().key(field)).toAscii().constData() << " allowable value '" << foo.simplified().toAscii().constData() << "' not supported for field type " << QMetaType::typeName(field.dataType());
}
QVERIFY(var.type() == QVariant::String || var.type() == QVariant::StringList);
}
} else if (field.dataType() == QVariant::List || field.dataType() == QVariant::Map || field.dataType() == (QVariant::Type) qMetaTypeId<QVariant>()) {
// Well, anything goes
} else {
// The type of each allowed value must match the data type
foreach(QVariant var, field.allowableValues()) {
if (var.type() != field.dataType()) {
QString foo;
QDebug dbg(&foo);
dbg.nospace() << var;
qDebug().nospace() << "Field " << QString("%1::%2").arg(def.name()).arg(def.fields().key(field)).toAscii().constData() << " allowable value '" << foo.simplified().toAscii().constData() << "' not supported for field type " << QMetaType::typeName(field.dataType());
}
QVERIFY(var.type() == field.dataType());
}
}
}
}
}
}
void tst_QContactManager::engineDefaultSchema()
{
/* Test the default schemas - mostly just that they are valid, and v2 has certain changes */
QMap<QString, QMap<QString, QContactDetailDefinition> > v1defaultSchemas = QContactManagerEngine::schemaDefinitions();
QMap<QString, QMap<QString, QContactDetailDefinition> > v1Schemas = QContactManagerEngine::schemaDefinitions(1);
QMap<QString, QMap<QString, QContactDetailDefinition> > v2Schemas = QContactManagerEngine::schemaDefinitions(2);
QVERIFY(v1Schemas == v1defaultSchemas);
QVERIFY(v1Schemas != v2Schemas);
QCOMPARE(v1Schemas.keys().count(), v1Schemas.uniqueKeys().count());
QCOMPARE(v2Schemas.keys().count(), v2Schemas.uniqueKeys().count());
foreach(const QString& type, v1Schemas.keys()) {
validateDefinitions(v1Schemas.value(type));
}
foreach(const QString& type, v2Schemas.keys()) {
validateDefinitions(v2Schemas.value(type));
}
/* Make sure that birthdays do not have calendar ids in v1, but do in v2*/
QVERIFY(!v1Schemas.value(QContactType::TypeContact).value(QContactBirthday::DefinitionName).fields().contains(QContactBirthday::FieldCalendarId));
QVERIFY(!v1Schemas.value(QContactType::TypeGroup).value(QContactBirthday::DefinitionName).fields().contains(QContactBirthday::FieldCalendarId));
QVERIFY(v2Schemas.value(QContactType::TypeContact).value(QContactBirthday::DefinitionName).fields().contains(QContactBirthday::FieldCalendarId));
QVERIFY(v2Schemas.value(QContactType::TypeGroup).value(QContactBirthday::DefinitionName).fields().contains(QContactBirthday::FieldCalendarId));
/* Urls can be blogs in v2 but not b1 */
QVERIFY(!v1Schemas.value(QContactType::TypeContact).value(QContactUrl::DefinitionName).fields().value(QContactUrl::FieldSubType).allowableValues().contains(QString(QLatin1String(QContactUrl::SubTypeBlog))));
QVERIFY(!v1Schemas.value(QContactType::TypeGroup).value(QContactUrl::DefinitionName).fields().value(QContactUrl::FieldSubType).allowableValues().contains(QString(QLatin1String(QContactUrl::SubTypeBlog))));
QVERIFY(v2Schemas.value(QContactType::TypeContact).value(QContactUrl::DefinitionName).fields().value(QContactUrl::FieldSubType).allowableValues().contains(QString(QLatin1String(QContactUrl::SubTypeBlog))));
QVERIFY(v2Schemas.value(QContactType::TypeGroup).value(QContactUrl::DefinitionName).fields().value(QContactUrl::FieldSubType).allowableValues().contains(QString(QLatin1String(QContactUrl::SubTypeBlog))));
/* Make sure family, favorite and hobby are not in v1, but are in v2 */
QVERIFY(!v1Schemas.value(QContactType::TypeContact).contains(QContactFamily::DefinitionName));
QVERIFY(!v1Schemas.value(QContactType::TypeGroup).contains(QContactFamily::DefinitionName));
QVERIFY(v2Schemas.value(QContactType::TypeContact).contains(QContactFamily::DefinitionName));
QVERIFY(v2Schemas.value(QContactType::TypeGroup).contains(QContactFamily::DefinitionName));
QVERIFY(!v1Schemas.value(QContactType::TypeContact).contains(QContactFavorite::DefinitionName));
QVERIFY(!v1Schemas.value(QContactType::TypeGroup).contains(QContactFavorite::DefinitionName));
QVERIFY(v2Schemas.value(QContactType::TypeContact).contains(QContactFavorite::DefinitionName));
QVERIFY(v2Schemas.value(QContactType::TypeGroup).contains(QContactFavorite::DefinitionName));
QVERIFY(!v1Schemas.value(QContactType::TypeContact).contains(QContactHobby::DefinitionName));
QVERIFY(!v1Schemas.value(QContactType::TypeGroup).contains(QContactHobby::DefinitionName));
QVERIFY(v2Schemas.value(QContactType::TypeContact).contains(QContactHobby::DefinitionName));
QVERIFY(v2Schemas.value(QContactType::TypeGroup).contains(QContactHobby::DefinitionName));
}
void tst_QContactManager::detailDefinitions()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
QMap<QString, QContactDetailDefinition> defs = cm->detailDefinitions();
/* Validate the existing definitions */
foreach(const QString& contactType, cm->supportedContactTypes()) {
validateDefinitions(cm->detailDefinitions(contactType));
}
/* Try to make a credible definition */
QContactDetailDefinition newDef;
QContactDetailFieldDefinition field;
QMap<QString, QContactDetailFieldDefinition> fields;
field.setDataType(cm->supportedDataTypes().value(0));
fields.insert("New Value", field);
newDef.setName("New Definition");
newDef.setFields(fields);
/* Updated version of an existing definition */
QContactDetailDefinition updatedDef = defs.begin().value(); // XXX TODO Fixme
fields = updatedDef.fields();
fields.insert("New Value", field);
updatedDef.setFields(fields);
/* A detail definition with valid allowed values (or really just one) */
QContactDetailDefinition allowedDef = newDef;
field.setAllowableValues(field.allowableValues() << (QVariant(field.dataType())));
fields.clear();
fields.insert("Restricted value", field);
allowedDef.setFields(fields);
/* Many invalid definitions */
QContactDetailDefinition noIdDef;
noIdDef.setFields(fields);
QContactDetailDefinition noFieldsDef;
noFieldsDef.setName("No fields");
QContactDetailDefinition invalidFieldKeyDef;
invalidFieldKeyDef.setName("Invalid field key");
QMap<QString, QContactDetailFieldDefinition> badfields;
badfields.insert(QString(), field);
invalidFieldKeyDef.setFields(badfields);
QContactDetailDefinition invalidFieldTypeDef;
invalidFieldTypeDef.setName("Invalid field type");
badfields.clear();
QContactDetailFieldDefinition badfield;
badfield.setDataType((QVariant::Type) qMetaTypeId<UnsupportedMetatype>());
badfields.insert("Bad type", badfield);
invalidFieldTypeDef.setFields(badfields);
QContactDetailDefinition invalidAllowedValuesDef;
invalidAllowedValuesDef.setName("Invalid field allowed values");
badfields.clear();
badfield.setDataType(field.dataType()); // use a supported type
badfield.setAllowableValues(QList<QVariant>() << "String" << 5); // but unsupported value
badfields.insert("Bad allowed", badfield);
invalidAllowedValuesDef.setFields(badfields);
/* XXX Multiply defined fields.. depends on semantichangeSet. */
if (cm->hasFeature(QContactManager::MutableDefinitions)) {
/* First do some negative testing */
/* Bad add class */
QVERIFY(cm->saveDetailDefinition(QContactDetailDefinition()) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
/* Bad remove string */
QVERIFY(cm->removeDetailDefinition(QString()) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
QVERIFY(cm->saveDetailDefinition(noIdDef) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
QVERIFY(cm->saveDetailDefinition(noFieldsDef) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
QVERIFY(cm->saveDetailDefinition(invalidFieldKeyDef) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
QVERIFY(cm->saveDetailDefinition(invalidFieldTypeDef) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
QVERIFY(cm->saveDetailDefinition(invalidAllowedValuesDef) == false);
QVERIFY(cm->error() == QContactManager::BadArgumentError);
/* Check that our new definition doesn't already exist */
QVERIFY(cm->detailDefinition(newDef.name()).isEmpty());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
QVERIFY(cm->removeDetailDefinition(newDef.name()) == false);
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
/* Add a new definition */
QVERIFY(cm->saveDetailDefinition(newDef) == true);
QVERIFY(cm->error() == QContactManager::NoError);
/* Now retrieve it */
QContactDetailDefinition def = cm->detailDefinition(newDef.name());
QVERIFY(def == newDef);
/* Update it */
QMap<QString, QContactDetailFieldDefinition> newFields = def.fields();
newFields.insert("Another new value", field);
newDef.setFields(newFields);
QVERIFY(cm->saveDetailDefinition(newDef) == true);
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(cm->detailDefinition(newDef.name()) == newDef);
/* Remove it */
QVERIFY(cm->removeDetailDefinition(newDef.name()) == true);
QVERIFY(cm->error() == QContactManager::NoError);
/* and make sure it does not exist any more */
QVERIFY(cm->detailDefinition(newDef.name()) == QContactDetailDefinition());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
/* Add the other good one */
QVERIFY(cm->saveDetailDefinition(allowedDef) == true);
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(allowedDef == cm->detailDefinition(allowedDef.name()));
/* and remove it */
QVERIFY(cm->removeDetailDefinition(allowedDef.name()) == true);
QVERIFY(cm->detailDefinition(allowedDef.name()) == QContactDetailDefinition());
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
} else {
/* Bad add class */
QVERIFY(cm->saveDetailDefinition(QContactDetailDefinition()) == false);
QVERIFY(cm->error() == QContactManager::NotSupportedError);
/* Make sure we can't add/remove/modify detail definitions */
QVERIFY(cm->removeDetailDefinition(QString()) == false);
QVERIFY(cm->error() == QContactManager::NotSupportedError);
/* Try updating an existing definition */
QVERIFY(cm->saveDetailDefinition(updatedDef) == false);
QVERIFY(cm->error() == QContactManager::NotSupportedError);
/* Try removing an existing definition */
QVERIFY(cm->removeDetailDefinition(updatedDef.name()) == false);
QVERIFY(cm->error() == QContactManager::NotSupportedError);
}
}
void tst_QContactManager::displayName()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
/*
* Very similar to the tst_QContact functions, except we test
* saving and retrieving contacts updates the display label
*/
/* Try to make this a bit more consistent by using a single name */
QContact d;
QContactName name;
saveContactName(&d, cm->detailDefinition(QContactName::DefinitionName, QContactType::TypeContact), &name, "Wesley");
QVERIFY(d.displayLabel().isEmpty());
QString synth = cm->synthesizedContactDisplayLabel(d);
// Make sure this doesn't crash
cm->synthesizeContactDisplayLabel(0);
// Make sure this gives the same results
cm->synthesizeContactDisplayLabel(&d);
QCOMPARE(d.displayLabel(), synth);
/*
* The display label is not updated until you save the contact or call synthCDL
*/
QVERIFY(cm->saveContact(&d));
d = cm->contact(d.id().localId());
QVERIFY(!d.isEmpty());
QCOMPARE(d.displayLabel(), synth);
/* Remove the detail via removeDetail */
QContactDisplayLabel old;
int count = d.details().count();
QVERIFY(!d.removeDetail(&old)); // should fail.
QVERIFY(d.isEmpty() == false);
QVERIFY(d.details().count() == count); // it should not be removed!
/* Save the contact again */
QVERIFY(cm->saveContact(&d));
d = cm->contact(d.id().localId());
QVERIFY(!d.isEmpty());
/* Make sure the label is still the synth version */
QCOMPARE(d.displayLabel(), synth);
/* And delete the contact */
QVERIFY(cm->removeContact(d.id().localId()));
}
void tst_QContactManager::actionPreferences()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
// early out if the manager doesn't support action preference saving.
if (!cm->hasFeature(QContactManager::ActionPreferences)) {
QSKIP("Manager does not support action preferences", SkipSingle);
}
// create a sample contact
QContactAvatar a;
a.setImageUrl(QUrl("test.png"));
QContactPhoneNumber p1;
p1.setNumber("12345");
QContactPhoneNumber p2;
p2.setNumber("34567");
QContactPhoneNumber p3;
p3.setNumber("56789");
QContactUrl u;
u.setUrl("http://test.nokia.com");
QContactName n;
QContact c;
saveContactName(&c, cm->detailDefinition(QContactName::DefinitionName, QContactType::TypeContact), &n, "TestContact");
c.saveDetail(&a);
c.saveDetail(&p1);
c.saveDetail(&p2);
c.saveDetail(&p3);
c.saveDetail(&u);
// set a preference for dialing a particular saved phonenumber.
c.setPreferredDetail("Dial", p2);
QVERIFY(cm->saveContact(&c)); // save the contact
QContact loaded = cm->contact(c.id().localId()); // reload the contact
// test that the preference was saved correctly.
QContactDetail pref = loaded.preferredDetail("Dial");
QVERIFY(pref == p2);
cm->removeContact(c.id().localId());
}
void tst_QContactManager::changeSet()
{
QContactLocalId id(1);
QContactChangeSet changeSet;
QVERIFY(changeSet.addedContacts().isEmpty());
QVERIFY(changeSet.changedContacts().isEmpty());
QVERIFY(changeSet.removedContacts().isEmpty());
changeSet.insertAddedContact(id);
QVERIFY(!changeSet.addedContacts().isEmpty());
QVERIFY(changeSet.changedContacts().isEmpty());
QVERIFY(changeSet.removedContacts().isEmpty());
QVERIFY(changeSet.addedContacts().contains(id));
changeSet.insertChangedContact(id);
changeSet.insertChangedContacts(QList<QContactLocalId>() << id);
QVERIFY(changeSet.changedContacts().size() == 1); // set, should only be added once.
QVERIFY(!changeSet.addedContacts().isEmpty());
QVERIFY(!changeSet.changedContacts().isEmpty());
QVERIFY(changeSet.removedContacts().isEmpty());
QVERIFY(changeSet.changedContacts().contains(id));
changeSet.clearChangedContacts();
QVERIFY(changeSet.changedContacts().isEmpty());
changeSet.insertRemovedContacts(QList<QContactLocalId>() << id);
QVERIFY(changeSet.removedContacts().contains(id));
changeSet.clearRemovedContacts();
QVERIFY(changeSet.removedContacts().isEmpty());
QVERIFY(changeSet.dataChanged() == false);
QContactChangeSet changeSet2;
changeSet2 = changeSet;
QVERIFY(changeSet.addedContacts() == changeSet2.addedContacts());
changeSet.emitSignals(0);
changeSet2.clearAddedContacts();
QVERIFY(changeSet2.addedContacts().isEmpty());
changeSet2.insertAddedContacts(changeSet.addedContacts().toList());
QVERIFY(changeSet.addedContacts() == changeSet2.addedContacts());
changeSet2.clearAll();
QVERIFY(changeSet.addedContacts() != changeSet2.addedContacts());
QContactChangeSet changeSet3(changeSet2);
QVERIFY(changeSet.addedContacts() != changeSet3.addedContacts());
QVERIFY(changeSet2.addedContacts() == changeSet3.addedContacts());
changeSet.setDataChanged(true);
QVERIFY(changeSet.dataChanged() == true);
QVERIFY(changeSet.dataChanged() != changeSet2.dataChanged());
QVERIFY(changeSet.dataChanged() != changeSet3.dataChanged());
changeSet.emitSignals(0);
changeSet.addedRelationshipsContacts().insert(id);
changeSet.insertAddedRelationshipsContacts(QList<QContactLocalId>() << id);
QVERIFY(changeSet.addedRelationshipsContacts().contains(id));
changeSet.clearAddedRelationshipsContacts();
QVERIFY(changeSet.addedRelationshipsContacts().isEmpty());
changeSet.insertRemovedRelationshipsContacts(QList<QContactLocalId>() << id);
QVERIFY(changeSet.removedRelationshipsContacts().contains(id));
changeSet.clearRemovedRelationshipsContacts();
QVERIFY(changeSet.removedRelationshipsContacts().isEmpty());
changeSet.emitSignals(0);
changeSet.removedRelationshipsContacts().insert(id);
changeSet.emitSignals(0);
changeSet.setOldAndNewSelfContactId(QPair<QContactLocalId, QContactLocalId>(QContactLocalId(0), id));
changeSet2 = changeSet;
QVERIFY(changeSet2.addedRelationshipsContacts() == changeSet.addedRelationshipsContacts());
QVERIFY(changeSet2.removedRelationshipsContacts() == changeSet.removedRelationshipsContacts());
QVERIFY(changeSet2.oldAndNewSelfContactId() == changeSet.oldAndNewSelfContactId());
changeSet.emitSignals(0);
changeSet.setOldAndNewSelfContactId(QPair<QContactLocalId, QContactLocalId>(id, QContactLocalId(0)));
QVERIFY(changeSet2.oldAndNewSelfContactId() != changeSet.oldAndNewSelfContactId());
changeSet.setDataChanged(true);
changeSet.emitSignals(0);
}
void tst_QContactManager::fetchHint()
{
QContactFetchHint hint;
hint.setOptimizationHints(QContactFetchHint::NoBinaryBlobs);
QCOMPARE(hint.optimizationHints(), QContactFetchHint::NoBinaryBlobs);
QStringList rels;
rels << QString(QLatin1String(QContactRelationship::HasMember));
hint.setRelationshipTypesHint(rels);
QCOMPARE(hint.relationshipTypesHint(), rels);
}
void tst_QContactManager::selfContactId()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
// early out if the manager doesn't support self contact id saving
QContactLocalId selfContact = cm->selfContactId();
if (!cm->hasFeature(QContactManager::SelfContact)) {
// ensure that the error codes / return values are meaningful failures.
QEXPECT_FAIL("mgr='maemo5'", "maemo5 supports getting the self contact but not setting it.", Continue);
QVERIFY(cm->error() == QContactManager::DoesNotExistError);
QVERIFY(!cm->setSelfContactId(QContactLocalId(123)));
QVERIFY(cm->error() == QContactManager::NotSupportedError);
QSKIP("Manager does not support the concept of a self-contact", SkipSingle);
}
// create a new "self" contact and retrieve its Id
QVERIFY(cm->error() == QContactManager::NoError || cm->error() == QContactManager::DoesNotExistError);
QContact self;
QContactPhoneNumber selfPhn;
selfPhn.setNumber("12345");
self.saveDetail(&selfPhn);
if (!cm->saveContact(&self)) {
QSKIP("Unable to save the generated self contact", SkipSingle);
}
QContactLocalId newSelfContact = self.localId();
// Setup signal spy
qRegisterMetaType<QContactLocalId>("QContactLocalId");
QSignalSpy spy(cm.data(), SIGNAL(selfContactIdChanged(QContactLocalId,QContactLocalId)));
// Set new self contact
QVERIFY(cm->setSelfContactId(newSelfContact));
QVERIFY(cm->error() == QContactManager::NoError);
QTRY_VERIFY(spy.count() == 1);
QVERIFY(spy.at(0).count() == 2);
// note: for some reason qvariant_cast<QContactLocalId>(spy.at(0).at(0)) returns always zero
// because the type is not recognized. Hence the ugly casting below.
QVERIFY(*((const QContactLocalId*) spy.at(0).at(0).constData()) == selfContact);
QVERIFY(*((const QContactLocalId*) spy.at(0).at(1).constData()) == newSelfContact);
QVERIFY(cm->selfContactId() == newSelfContact);
// Remove self contact
if(!cm->removeContact(self.localId())) {
QSKIP("Unable to remove self contact", SkipSingle);
}
QTRY_VERIFY(spy.count() == 2);
QVERIFY(spy.at(1).count() == 2);
QVERIFY(*((const QContactLocalId*) spy.at(1).at(0).constData()) == newSelfContact);
QVERIFY(*((const QContactLocalId*) spy.at(1).at(1).constData()) == QContactLocalId(0));
QVERIFY(cm->selfContactId() == QContactLocalId(0)); // ensure reset after removed.
// reset to original state.
cm->setSelfContactId(selfContact);
}
QList<QContactDetail> tst_QContactManager::removeAllDefaultDetails(const QList<QContactDetail>& details)
{
QList<QContactDetail> newlist;
foreach (const QContactDetail d, details) {
if (d.definitionName() != QContactDisplayLabel::DefinitionName
&& d.definitionName() != QContactType::DefinitionName
&& d.definitionName() != QContactTimestamp::DefinitionName) {
newlist << d;
}
}
return newlist;
}
void tst_QContactManager::detailOrders()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
if (!cm->hasFeature(QContactManager::DetailOrdering))
QSKIP("Skipping: This manager does not support detail ordering!", SkipSingle);
QContact a;
//phone numbers
QContactDetailDefinition d = cm->detailDefinition(QContactPhoneNumber::DefinitionName, QContactType::TypeContact);
QContactDetailFieldDefinition supportedContexts = d.fields().value(QContactDetail::FieldContext);
QString contextOther = QContactDetail::ContextOther;
if (!supportedContexts.allowableValues().contains(contextOther)) {
contextOther = QString();
}
QContactPhoneNumber number1, number2, number3;
number1.setNumber("11111111");
number1.setContexts(QContactPhoneNumber::ContextHome);
number2.setNumber("22222222");
number2.setContexts(QContactPhoneNumber::ContextWork);
number3.setNumber("33333333");
if (!contextOther.isEmpty())
number3.setContexts(contextOther);
a.saveDetail(&number1);
a.saveDetail(&number2);
a.saveDetail(&number3);
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
QList<QContactDetail> details = a.details(QContactPhoneNumber::DefinitionName);
QVERIFY(details.count() == 3);
QVERIFY(details.at(0).value(QContactPhoneNumber::FieldContext) == QContactPhoneNumber::ContextHome);
QVERIFY(details.at(1).value(QContactPhoneNumber::FieldContext) == QContactPhoneNumber::ContextWork);
QVERIFY(details.at(2).value(QContactPhoneNumber::FieldContext) == contextOther);
QVERIFY(a.removeDetail(&number2));
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactPhoneNumber::DefinitionName);
QVERIFY(details.count() == 2);
QVERIFY(details.at(0).value(QContactPhoneNumber::FieldContext) == QContactPhoneNumber::ContextHome);
QVERIFY(details.at(1).value(QContactPhoneNumber::FieldContext) == contextOther);
a.saveDetail(&number2);
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactPhoneNumber::DefinitionName);
QVERIFY(details.count() == 3);
QVERIFY(details.at(0).value(QContactPhoneNumber::FieldContext) == QContactPhoneNumber::ContextHome);
QVERIFY(details.at(1).value(QContactPhoneNumber::FieldContext) == contextOther);
QVERIFY(details.at(2).value(QContactPhoneNumber::FieldContext) == QContactPhoneNumber::ContextWork);
//addresses
d = cm->detailDefinition(QContactAddress::DefinitionName, QContactType::TypeContact);
supportedContexts = d.fields().value(QContactDetail::FieldContext);
contextOther = QString(QLatin1String(QContactDetail::ContextOther));
if (!supportedContexts.allowableValues().contains(contextOther)) {
contextOther = QString();
}
QContactAddress address1, address2, address3;
address1.setStreet("Brandl St");
address1.setRegion("Brisbane");
address3 = address2 = address1;
address1.setContexts(QContactAddress::ContextHome);
address2.setContexts(QContactAddress::ContextWork);
if (!contextOther.isEmpty())
address3.setContexts(contextOther);
a.saveDetail(&address1);
a.saveDetail(&address2);
a.saveDetail(&address3);
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactAddress::DefinitionName);
QVERIFY(details.count() == 3);
QVERIFY(details.at(0).value(QContactAddress::FieldContext) == QContactAddress::ContextHome);
QVERIFY(details.at(1).value(QContactAddress::FieldContext) == QContactAddress::ContextWork);
QVERIFY(details.at(2).value(QContactAddress::FieldContext) == contextOther);
QVERIFY(a.removeDetail(&address2));
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactAddress::DefinitionName);
QVERIFY(details.count() == 2);
QVERIFY(details.at(0).value(QContactAddress::FieldContext) == QContactAddress::ContextHome);
QVERIFY(details.at(1).value(QContactAddress::FieldContext) == contextOther);
a.saveDetail(&address2);
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactAddress::DefinitionName);
QVERIFY(details.count() == 3);
QVERIFY(details.at(0).value(QContactAddress::FieldContext) == QContactAddress::ContextHome);
QVERIFY(details.at(1).value(QContactAddress::FieldContext) == contextOther);
QVERIFY(details.at(2).value(QContactAddress::FieldContext) == QContactAddress::ContextWork);
//emails
d = cm->detailDefinition(QContactEmailAddress::DefinitionName, QContactType::TypeContact);
supportedContexts = d.fields().value(QContactDetail::FieldContext);
contextOther = QString(QLatin1String(QContactDetail::ContextOther));
if (!supportedContexts.allowableValues().contains(contextOther)) {
contextOther = QString();
}
QContactEmailAddress email1, email2, email3;
email1.setEmailAddress("[email protected]");
email3 = email2 = email1;
email1.setContexts(QContactEmailAddress::ContextHome);
email2.setContexts(QContactEmailAddress::ContextWork);
if (!contextOther.isEmpty())
email3.setContexts(contextOther);
a.saveDetail(&email1);
a.saveDetail(&email2);
a.saveDetail(&email3);
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactEmailAddress::DefinitionName);
QVERIFY(details.count() == 3);
QVERIFY(details.at(0).value(QContactEmailAddress::FieldContext) == QContactEmailAddress::ContextHome);
QVERIFY(details.at(1).value(QContactEmailAddress::FieldContext) == QContactEmailAddress::ContextWork);
QVERIFY(details.at(2).value(QContactEmailAddress::FieldContext) == contextOther);
QVERIFY(a.removeDetail(&email2));
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactEmailAddress::DefinitionName);
QVERIFY(details.count() == 2);
QVERIFY(details.at(0).value(QContactEmailAddress::FieldContext) == QContactEmailAddress::ContextHome);
QVERIFY(details.at(1).value(QContactEmailAddress::FieldContext) == contextOther);
a.saveDetail(&email2);
QVERIFY(cm->saveContact(&a));
a = cm->contact(a.id().localId());
details = a.details(QContactEmailAddress::DefinitionName);
QVERIFY(details.count() == 3);
QVERIFY(details.at(0).value(QContactEmailAddress::FieldContext) == QContactEmailAddress::ContextHome);
QVERIFY(details.at(1).value(QContactEmailAddress::FieldContext) == contextOther);
QVERIFY(details.at(2).value(QContactEmailAddress::FieldContext) == QContactEmailAddress::ContextWork);
QVERIFY(cm->removeContact(a.id().localId()));
QVERIFY(cm->error() == QContactManager::NoError);
}
void tst_QContactManager::relationships()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
// save some contacts
QContact source;
QContact dest1, dest2, dest3, dest4;
QContactPhoneNumber n1, n2, n3, n4;
n1.setNumber("1");
n2.setNumber("2");
n3.setNumber("3");
n4.setNumber("4");
dest1.saveDetail(&n1);
dest2.saveDetail(&n2);
dest3.saveDetail(&n3);
dest4.saveDetail(&n3);
cm->saveContact(&source);
cm->saveContact(&dest1);
cm->saveContact(&dest2);
cm->saveContact(&dest3);
cm->saveContact(&dest4);
// check if manager supports relationships
if (!cm->hasFeature(QContactManager::Relationships)) {
// ensure that the operations all fail as required.
QContactRelationship r1, r2, r3;
r1.setFirst(source.id());
r1.setSecond(dest1.id());
r1.setRelationshipType(QContactRelationship::HasManager);
r2.setFirst(source.id());
r2.setSecond(dest2.id());
r2.setRelationshipType(QContactRelationship::HasManager);
r3.setFirst(source.id());
r3.setSecond(dest3.id());
r3.setRelationshipType(QContactRelationship::HasManager);
QList<QContactRelationship> batchList;
batchList << r2 << r3;
// test save and remove
QVERIFY(!cm->saveRelationship(&r1));
QVERIFY(cm->error() == QContactManager::NotSupportedError);
QVERIFY(!cm->removeRelationship(r1));
QVERIFY(cm->error() == QContactManager::NotSupportedError);
cm->saveRelationships(&batchList, NULL);
QVERIFY(cm->error() == QContactManager::NotSupportedError);
// test retrieval
QList<QContactRelationship> retrieveList;
retrieveList = cm->relationships(source.id(), QContactRelationship::First);
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(source.id(), QContactRelationship::Second);
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(source.id(), QContactRelationship::Either); // Either
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(QContactRelationship::HasManager, source.id(), QContactRelationship::First);
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(QContactRelationship::HasManager, source.id(), QContactRelationship::Second);
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(QContactRelationship::HasManager, source.id(), QContactRelationship::Either);
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(QContactRelationship::HasManager, source.id());
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
retrieveList = cm->relationships(QContactRelationship::HasManager);
QVERIFY(retrieveList.isEmpty());
QVERIFY(cm->error() == QContactManager::NotSupportedError);
return;
}
// Get supported relationship types
QStringList availableRelationshipTypes;
if (cm->isRelationshipTypeSupported(QContactRelationship::HasMember))
availableRelationshipTypes << QContactRelationship::HasMember;
if (cm->isRelationshipTypeSupported(QContactRelationship::HasAssistant))
availableRelationshipTypes << QContactRelationship::HasAssistant;
if (cm->isRelationshipTypeSupported(QContactRelationship::HasManager))
availableRelationshipTypes << QContactRelationship::HasManager;
if (cm->isRelationshipTypeSupported(QContactRelationship::HasSpouse))
availableRelationshipTypes << QContactRelationship::HasSpouse;
if (cm->isRelationshipTypeSupported(QContactRelationship::IsSameAs))
availableRelationshipTypes << QContactRelationship::IsSameAs;
// Check arbitary relationship support
if (cm->hasFeature(QContactManager::ArbitraryRelationshipTypes)) {
// add some arbitary type for testing
if (availableRelationshipTypes.count())
availableRelationshipTypes.insert(0, "test-arbitrary-relationship-type");
else {
availableRelationshipTypes.append("test-arbitrary-relationship-type");
availableRelationshipTypes.append(QContactRelationship::HasMember);
availableRelationshipTypes.append(QContactRelationship::HasAssistant);
}
}
// Verify that we have relationship types. If there are none then the manager
// is saying it supports relationships but does not actually implement any
// relationship type.
QVERIFY(!availableRelationshipTypes.isEmpty());
// Some backends (eg. symbian) require that when type is "HasMember"
// then "first" contact must be a group.
if (availableRelationshipTypes.at(0) == QContactRelationship::HasMember) {
cm->removeContact(source.localId());
source.setId(QContactId());
source.setType(QContactType::TypeGroup);
cm->saveContact(&source);
}
// Create some common contact id's for testing
QContactId dest1Uri = dest1.id();
QContactId dest1EmptyUri;
dest1EmptyUri.setManagerUri(QString());
dest1EmptyUri.setLocalId(dest1.id().localId());
QContactId dest2Uri = dest2.id();
QContactId dest3Uri = dest3.id();
QContactId dest3EmptyUri;
dest3EmptyUri.setManagerUri(QString());
dest3EmptyUri.setLocalId(dest3.id().localId());
// build our relationship - source is the manager all of the dest contacts.
QContactRelationship customRelationshipOne;
customRelationshipOne.setFirst(source.id());
customRelationshipOne.setSecond(dest1EmptyUri);
customRelationshipOne.setRelationshipType(availableRelationshipTypes.at(0));
QCOMPARE(customRelationshipOne.first(), source.id());
QCOMPARE(customRelationshipOne.second(), dest1EmptyUri);
QVERIFY(customRelationshipOne.relationshipType() == availableRelationshipTypes.at(0));
// save the relationship
int managerRelationshipsCount = cm->relationships(availableRelationshipTypes.at(0)).count();
QVERIFY(cm->saveRelationship(&customRelationshipOne));
// test that the empty manager URI has been updated.
QCOMPARE(customRelationshipOne.second(), dest1Uri); // updated with correct manager URI
// test our accessors.
QCOMPARE(cm->relationships(availableRelationshipTypes.at(0)).count(), (managerRelationshipsCount + 1));
QVERIFY(cm->relationships(availableRelationshipTypes.at(0), source.id()).count() == 1);
// remove the dest1 contact, relationship should be removed.
cm->removeContact(dest1.localId());
QCOMPARE(cm->relationships(availableRelationshipTypes.at(0), dest1Uri, QContactRelationship::Second).count(), 0);
// modify and save the relationship
customRelationshipOne.setSecond(dest2Uri);
QVERIFY(cm->saveRelationship(&customRelationshipOne));
// attempt to save the relationship again. XXX TODO: what should the result be? currently succeeds (overwrites)
int relationshipsCount = cm->relationships().count();
QVERIFY(cm->saveRelationship(&customRelationshipOne)); // succeeds, but just overwrites
QCOMPARE(relationshipsCount, cm->relationships().count()); // shouldn't change; save should have overwritten.
// removing the source contact should result in removal of the relationship.
QVERIFY(cm->removeContact(source.id().localId()));
QCOMPARE(cm->relationships().count(), relationshipsCount - 1); // the relationship should have been removed.
// now ensure that qcontact relationship caching works as required - perhaps this should be in tst_QContact?
source.setId(QContactId()); // reset id so we can resave
QVERIFY(cm->saveContact(&source)); // save source again.
customRelationshipOne.setFirst(source.id());
customRelationshipOne.setSecond(dest2.id());
QVERIFY(cm->saveRelationship(&customRelationshipOne));
// Add a second relationship
QContactRelationship customRelationshipTwo;
customRelationshipTwo.setFirst(source.id());
if (availableRelationshipTypes.count() > 1)
customRelationshipTwo.setRelationshipType(availableRelationshipTypes.at(1));
else
customRelationshipTwo.setRelationshipType(availableRelationshipTypes.at(0));
customRelationshipTwo.setSecond(dest3.id());
QVERIFY(cm->saveRelationship(&customRelationshipTwo));
// currently, the contacts are "stale" - no cached relationships
QVERIFY(dest3.relatedContacts().isEmpty());
QVERIFY(dest3.relationships().isEmpty());
QVERIFY(dest2.relatedContacts().isEmpty());
QVERIFY(dest2.relationships().isEmpty());
// now refresh the contacts
dest3 = cm->contact(dest3.localId());
dest2 = cm->contact(dest2.localId());
source = cm->contact(source.localId());
// and test again.
QVERIFY(source.relatedContacts(QString(), QContactRelationship::First).isEmpty()); // source is always the first, so this should be empty.
QVERIFY(source.relatedContacts(QString(), QContactRelationship::Second).contains(dest2.id()));
QVERIFY(source.relatedContacts(QString(), QContactRelationship::Either).contains(dest2.id()));
QVERIFY(source.relatedContacts(QString(), QContactRelationship::Second).contains(dest3.id()));
QVERIFY(source.relatedContacts(QString(), QContactRelationship::Either).contains(dest3.id()));
QVERIFY(source.relatedContacts(availableRelationshipTypes.at(0), QContactRelationship::Second).contains(dest2.id()));
QVERIFY(source.relatedContacts(availableRelationshipTypes.at(0), QContactRelationship::First).isEmpty());
QVERIFY(dest2.relatedContacts().contains(source.id()));
QVERIFY(dest2.relationships().contains(customRelationshipOne));
QVERIFY(!dest2.relationships().contains(customRelationshipTwo));
QVERIFY(dest2.relationships(availableRelationshipTypes.at(0)).contains(customRelationshipOne));
QVERIFY(!dest2.relationships(availableRelationshipTypes.at(0)).contains(customRelationshipTwo));
QVERIFY(dest2.relatedContacts(availableRelationshipTypes.at(0)).contains(source.id()));
QVERIFY(dest2.relatedContacts(availableRelationshipTypes.at(0), QContactRelationship::First).contains(source.id()));
QVERIFY(dest2.relatedContacts(availableRelationshipTypes.at(0), QContactRelationship::Second).isEmpty());
QVERIFY(!dest2.relatedContacts(availableRelationshipTypes.at(0), QContactRelationship::Second).contains(source.id()));
QVERIFY(dest3.relatedContacts().contains(source.id()));
QVERIFY(!dest3.relationships().contains(customRelationshipOne));
QVERIFY(dest3.relationships().contains(customRelationshipTwo));
QVERIFY(!dest3.relationships(availableRelationshipTypes.at(0)).contains(customRelationshipOne));
// Test iteration
QList<QContactRelationship> relats = source.relationships();
QList<QContactRelationship>::iterator it = relats.begin();
while (it != relats.end()) {
QContactId firstId = it->first();
QVERIFY(firstId == source.id());
QVERIFY(it->second() == dest2.id() || it->second() == dest3.id());
it++;
}
if (availableRelationshipTypes.count() > 1) {
QVERIFY(source.relatedContacts(availableRelationshipTypes.at(1), QContactRelationship::Second).contains(dest3.id()));
QVERIFY(source.relatedContacts(availableRelationshipTypes.at(1), QContactRelationship::First).isEmpty());
QVERIFY(dest2.relationships(availableRelationshipTypes.at(1)).isEmpty());
QVERIFY(!dest3.relationships(availableRelationshipTypes.at(0)).contains(customRelationshipTwo));
QVERIFY(dest3.relationships(availableRelationshipTypes.at(1)).contains(customRelationshipTwo));
QVERIFY(!dest3.relationships(availableRelationshipTypes.at(1)).contains(customRelationshipOne));
QVERIFY(dest3.relatedContacts(availableRelationshipTypes.at(1)).contains(source.id()));
QVERIFY(!dest3.relatedContacts(availableRelationshipTypes.at(0)).contains(source.id()));
QVERIFY(dest3.relatedContacts(availableRelationshipTypes.at(1)).contains(source.id())); // role = either
QVERIFY(!dest3.relatedContacts(availableRelationshipTypes.at(1), QContactRelationship::Second).contains(source.id()));
QVERIFY(dest3.relatedContacts(availableRelationshipTypes.at(1), QContactRelationship::First).contains(source.id()));
QVERIFY(dest2.relatedContacts(availableRelationshipTypes.at(1)).isEmpty());
}
else {
QVERIFY(source.relatedContacts(availableRelationshipTypes.at(0), QContactRelationship::Second).contains(dest3.id()));
}
// Cleanup a bit
QMap<int, QContactManager::Error> errorMap;
QList<QContactRelationship> moreRels;
moreRels << customRelationshipOne << customRelationshipTwo;
errorMap.insert(5, QContactManager::BadArgumentError);
QVERIFY(cm->removeRelationships(moreRels, &errorMap));
QVERIFY(errorMap.count() == 0);
// test batch API and ordering in contacts
QList<QContactRelationship> currentRelationships = cm->relationships(source.id(), QContactRelationship::First);
QList<QContactRelationship> batchList;
QContactRelationship br1, br2, br3;
br1.setFirst(source.id());
br1.setSecond(dest2.id());
br1.setRelationshipType(availableRelationshipTypes.at(0));
br2.setFirst(source.id());
br2.setSecond(dest3.id());
br2.setRelationshipType(availableRelationshipTypes.at(0));
if (availableRelationshipTypes.count() > 1)
{
br3.setFirst(source.id());
br3.setSecond(dest3.id());
br3.setRelationshipType(availableRelationshipTypes.at(1));
}
else
{
br3.setFirst(source.id());
br3.setSecond(dest4.id());
br3.setRelationshipType(availableRelationshipTypes.at(0));
}
batchList << br1 << br2 << br3;
// ensure that the batch save works properly
cm->saveRelationships(&batchList, NULL);
QCOMPARE(cm->error(), QContactManager::NoError);
QList<QContactRelationship> batchRetrieve = cm->relationships(source.id(), QContactRelationship::First);
QVERIFY(batchRetrieve.contains(br1));
QVERIFY(batchRetrieve.contains(br2));
QVERIFY(batchRetrieve.contains(br3));
// remove a single relationship
QVERIFY(cm->removeRelationship(br3));
batchRetrieve = cm->relationships(source.id(), QContactRelationship::First);
QVERIFY(batchRetrieve.contains(br1));
QVERIFY(batchRetrieve.contains(br2));
QVERIFY(!batchRetrieve.contains(br3)); // has already been removed.
// now ensure that the batch remove works and we get returned to the original state.
batchList.removeOne(br3);
cm->removeRelationships(batchList, NULL);
QVERIFY(cm->error() == QContactManager::NoError);
QCOMPARE(cm->relationships(source.id(), QContactRelationship::First), currentRelationships);
// attempt to save relationships between an existing source but non-existent destination
QContactId nonexistentDest;
quint32 idSeed = 0x5544;
QContactLocalId nonexistentLocalId = QContactLocalId(idSeed);
nonexistentDest.setManagerUri(cm->managerUri());
while (true) {
nonexistentLocalId = cm->contact(nonexistentLocalId).localId();
if (nonexistentLocalId == QContactLocalId(0)) {
// found a "spare" local id (no contact with that id)
break;
}
// keep looking...
idSeed += 1;
nonexistentLocalId = QContactLocalId(idSeed);
QVERIFY(nonexistentLocalId != QContactLocalId(0)); // integer overflow check.
}
nonexistentDest.setLocalId(nonexistentLocalId);
QContactRelationship maliciousRel;
maliciousRel.setFirst(source.id());
maliciousRel.setSecond(nonexistentDest);
maliciousRel.setRelationshipType("nokia-test-invalid-relationship-type");
QVERIFY(!cm->saveRelationship(&maliciousRel));
// attempt to save a circular relationship - should fail!
maliciousRel.setFirst(source.id());
maliciousRel.setSecond(source.id());
maliciousRel.setRelationshipType(availableRelationshipTypes.at(0));
QVERIFY(!cm->saveRelationship(&maliciousRel));
// more negative testing, but force manager to recognise the empty URI
QContactId circularId = source.id();
circularId.setManagerUri(QString());
maliciousRel.setFirst(circularId);
maliciousRel.setSecond(circularId);
maliciousRel.setRelationshipType(availableRelationshipTypes.at(0));
QVERIFY(!cm->saveRelationship(&maliciousRel));
maliciousRel.setFirst(source.id());
maliciousRel.setSecond(circularId);
maliciousRel.setRelationshipType(availableRelationshipTypes.at(0));
QVERIFY(!cm->saveRelationship(&maliciousRel));
maliciousRel.setFirst(circularId);
maliciousRel.setSecond(source.id());
maliciousRel.setRelationshipType(availableRelationshipTypes.at(0));
QVERIFY(!cm->saveRelationship(&maliciousRel));
// attempt to save a relationship where the source contact comes from another manager
circularId.setManagerUri("test-nokia-invalid-manager-uri");
maliciousRel.setFirst(circularId); // an invalid source contact
maliciousRel.setSecond(dest2.id()); // a valid destination contact
maliciousRel.setRelationshipType(availableRelationshipTypes.at(0));
QVERIFY(!cm->saveRelationship(&maliciousRel));
// remove the nonexistent relationship
relationshipsCount = cm->relationships().count();
QVERIFY(!cm->removeRelationship(maliciousRel)); // does not exist; fail remove.
QVERIFY(cm->error() == QContactManager::DoesNotExistError || cm->error() == QContactManager::InvalidRelationshipError);
QCOMPARE(cm->relationships().count(), relationshipsCount); // should be unchanged.
// now we want to ensure that a relationship is removed if one of the contacts is removed.
customRelationshipOne.setFirst(source.id());
customRelationshipOne.setSecond(dest2.id());
customRelationshipOne.setRelationshipType(availableRelationshipTypes.at(0));
// Test batch save with an error map
moreRels.clear();
moreRels << customRelationshipOne;
errorMap.insert(0, QContactManager::BadArgumentError);
QVERIFY(cm->saveRelationships(&moreRels, &errorMap));
QVERIFY(cm->error() == QContactManager::NoError);
QVERIFY(errorMap.count() == 0); // should be reset
source = cm->contact(source.localId());
dest2 = cm->contact(dest2.localId());
QVERIFY(cm->removeContact(dest2.localId())); // remove dest2, the relationship should be removed
QVERIFY(cm->relationships(availableRelationshipTypes.at(0), dest2.id(), QContactRelationship::Second).isEmpty());
source = cm->contact(source.localId());
QVERIFY(!source.relatedContacts().contains(dest2.id())); // and it shouldn't appear in cache.
// now clean up and remove our dests.
QVERIFY(cm->removeContact(source.localId()));
QVERIFY(cm->removeContact(dest3.localId()));
// attempt to save relationships with nonexistent contacts
QVERIFY(!cm->saveRelationship(&br1));
QVERIFY(cm->error() == QContactManager::InvalidRelationshipError);
cm->saveRelationships(&batchList, NULL);
QVERIFY(cm->error() == QContactManager::InvalidRelationshipError);
QVERIFY(!cm->removeRelationship(br1));
QVERIFY(cm->error() == QContactManager::DoesNotExistError || cm->error() == QContactManager::InvalidRelationshipError);
cm->removeRelationships(batchList, NULL);
QVERIFY(cm->error() == QContactManager::DoesNotExistError || cm->error() == QContactManager::InvalidRelationshipError);
}
void tst_QContactManager::contactType()
{
QFETCH(QString, uri);
QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri));
if (!cm->hasFeature(QContactManager::Groups))
QSKIP("Skipping: This manager does not support group contacts!", SkipSingle);
QContact g1, g2, c;
g1.setType(QContactType::TypeGroup);
g2.setType(QContactType::TypeGroup);
QContactPhoneNumber g1p, g2p, cp;
g1p.setNumber("22222");
g2p.setNumber("11111");
cp.setNumber("33333");
g1.saveDetail(&g1p);
g2.saveDetail(&g2p);
c.saveDetail(&cp);
QVERIFY(cm->saveContact(&g1));
QVERIFY(cm->saveContact(&g2));
QVERIFY(cm->saveContact(&c));
// test that the accessing by type works properly
QContactDetailFilter groupFilter;
groupFilter.setDetailDefinitionName(QContactType::DefinitionName, QContactType::FieldType);
groupFilter.setValue(QString(QLatin1String(QContactType::TypeGroup)));
QVERIFY(cm->contactIds(groupFilter).contains(g1.localId()));
QVERIFY(cm->contactIds(groupFilter).contains(g2.localId()));
QVERIFY(!cm->contactIds(groupFilter).contains(c.localId()));
QList<QContactSortOrder> sortOrders;
QContactSortOrder byPhoneNumber;
byPhoneNumber.setDetailDefinitionName(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber);
sortOrders.append(byPhoneNumber);
// and ensure that sorting works properly with typed contacts also
QList<QContactLocalId> sortedIds = cm->contactIds(groupFilter, sortOrders);
QVERIFY(sortedIds.indexOf(g2.localId()) < sortedIds.indexOf(g1.localId()));
cm->removeContact(g1.localId());
cm->removeContact(g2.localId());
cm->removeContact(c.localId());
}
#if defined(USE_VERSIT_PLZ)
void tst_QContactManager::partialSave()
{
QFETCH(QString, uri);
QContactManager* cm = QContactManager::fromUri(uri);
QVersitContactImporter imp;
QVersitReader reader(QByteArray(
"BEGIN:VCARD\r\nFN:Alice\r\nN:Alice\r\nTEL:12345\r\nEND:VCARD\r\n"
"BEGIN:VCARD\r\nFN:Bob\r\nN:Bob\r\nTEL:5678\r\nEND:VCARD\r\n"
"BEGIN:VCARD\r\nFN:Carol\r\nN:Carol\r\nEMAIL:[email protected]\r\nEND:VCARD\r\n"
"BEGIN:VCARD\r\nFN:David\r\nN:David\r\nORG:DavidCorp\r\nEND:VCARD\r\n"));
reader.startReading();
reader.waitForFinished();
QCOMPARE(reader.error(), QVersitReader::NoError);
QCOMPARE(reader.results().count(), 4);
QVERIFY(imp.importDocuments(reader.results()));
QCOMPARE(imp.contacts().count(), 4);
QVERIFY(imp.contacts()[0].displayLabel() == QLatin1String("Alice"));
QVERIFY(imp.contacts()[1].displayLabel() == QLatin1String("Bob"));
QVERIFY(imp.contacts()[2].displayLabel() == QLatin1String("Carol"));
QVERIFY(imp.contacts()[3].displayLabel() == QLatin1String("David"));
QList<QContact> contacts = imp.contacts();
QMap<int, QContactManager::Error> errorMap;
// First save these contacts
QVERIFY(cm->saveContacts(&contacts, &errorMap));
QList<QContact> originalContacts = contacts;
// Now try some partial save operations
// 0) empty mask == full save
// 1) Ignore an added phonenumber
// 2) Only save a modified phonenumber, not a modified email
// 3) Remove an email address & phone, mask out phone
// 4) new contact, no details in the mask
// 5) new contact, some details in the mask
// 6) Have a bad manager uri in the middle
// 7) Have a non existing contact in the middle
QContactPhoneNumber pn;
pn.setNumber("111111");
contacts[0].saveDetail(&pn);
// 0) empty mask
QVERIFY(cm->saveContacts(&contacts, QStringList(), &errorMap));
// That should have updated everything
QContact a = cm->contact(originalContacts[0].localId());
QVERIFY(a.details<QContactPhoneNumber>().count() == 2);
// 1) Add a phone number to b, mask it out
contacts[1].saveDetail(&pn);
QVERIFY(cm->saveContacts(&contacts, QStringList(QContactEmailAddress::DefinitionName), &errorMap));
QVERIFY(errorMap.isEmpty());
QContact b = cm->contact(originalContacts[1].localId());
QVERIFY(b.details<QContactPhoneNumber>().count() == 1);
// 2) save a modified detail in the mask
QContactEmailAddress e;
e.setEmailAddress("[email protected]");
contacts[1].saveDetail(&e); // contacts[1] should have both phone and email
QVERIFY(cm->saveContacts(&contacts, QStringList(QContactEmailAddress::DefinitionName), &errorMap));
QVERIFY(errorMap.isEmpty());
b = cm->contact(originalContacts[1].localId());
QVERIFY(b.details<QContactPhoneNumber>().count() == 1);
QVERIFY(b.details<QContactEmailAddress>().count() == 1);
// 3) Remove an email address and a phone number
QVERIFY(contacts[1].removeDetail(&e));
QVERIFY(contacts[1].removeDetail(&pn));
QVERIFY(contacts[1].details<QContactEmailAddress>().count() == 0);
QVERIFY(contacts[1].details<QContactPhoneNumber>().count() == 1);
QVERIFY(cm->saveContacts(&contacts, QStringList(QContactEmailAddress::DefinitionName), &errorMap));
QVERIFY(errorMap.isEmpty());
b = cm->contact(originalContacts[1].localId());
QVERIFY(b.details<QContactPhoneNumber>().count() == 1);
QVERIFY(b.details<QContactEmailAddress>().count() == 0);
// 4 - New contact, no details in the mask
QContact newContact = originalContacts[3];
newContact.setId(QContactId());
contacts.append(newContact);
QVERIFY(cm->saveContacts(&contacts, QStringList(QContactEmailAddress::DefinitionName), &errorMap));
QVERIFY(errorMap.isEmpty());
QVERIFY(contacts[4].localId() != 0); // Saved
b = cm->contact(contacts[4].localId());
QVERIFY(b.details<QContactOrganization>().count() == 0); // not saved
QVERIFY(b.details<QContactName>().count() == 0); // not saved
// 5 - New contact, some details in the mask
newContact = originalContacts[2];
newContact.setId(QContactId());
contacts.append(newContact);
QVERIFY(cm->saveContacts(&contacts, QStringList(QContactEmailAddress::DefinitionName), &errorMap));
QVERIFY(errorMap.isEmpty());
QVERIFY(contacts[5].localId() != 0); // Saved
b = cm->contact(contacts[5].localId());
QVERIFY(b.details<QContactEmailAddress>().count() == 1);
QVERIFY(b.details<QContactName>().count() == 0); // not saved
// 6) Have a bad manager uri in the middle followed by a save error
QContactId id4(contacts[4].id());
QContactId badId(id4);
badId.setManagerUri(QString());
contacts[4].setId(badId);
QContactDetail badDetail("BadDetail");
badDetail.setValue("BadField", "BadValue");
contacts[5].saveDetail(&badDetail);
QVERIFY(!cm->saveContacts(&contacts, QStringList("BadDetail"), &errorMap));
QCOMPARE(errorMap.count(), 2);
QCOMPARE(errorMap[4], QContactManager::DoesNotExistError);
QCOMPARE(errorMap[5], QContactManager::InvalidDetailError);
// 7) Have a non existing contact in the middle followed by a save error
badId = id4;
badId.setLocalId(987234); // something nonexistent
contacts[4].setId(badId);
QVERIFY(!cm->saveContacts(&contacts, QStringList("BadDetail"), &errorMap));
QCOMPARE(errorMap.count(), 2);
QCOMPARE(errorMap[4], QContactManager::DoesNotExistError);
QCOMPARE(errorMap[5], QContactManager::InvalidDetailError);
}
#endif
QTEST_MAIN(tst_QContactManager)
#include "tst_qcontactmanager.moc"
| lgpl-2.1 |
metlos/rhq-plugin-annotation-processor | annotations/src/main/java/org/rhq/plugin/annotation/AgentPlugin.java | 1787 | /*
* RHQ Management Platform
* Copyright (C) 2013 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.rhq.plugin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.rhq.core.pluginapi.plugin.PluginContext;
import org.rhq.core.pluginapi.plugin.PluginLifecycleListener;
/**
* @author Lukas Krejci
* @since 4.9
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PACKAGE)
public @interface AgentPlugin {
public static class NoopLifecycleListener implements PluginLifecycleListener {
@Override
public void initialize(PluginContext context) throws Exception {
}
@Override
public void shutdown() {
}
}
public @interface Dependency {
String pluginName();
boolean useClasses() default false;
}
Dependency[] dependencies() default {};
Class<? extends PluginLifecycleListener> pluginLifecycleListener() default NoopLifecycleListener.class;
String version();
String ampsVersion() default "2.0";
}
| lgpl-2.1 |
gitkhs/cms-kq | modules/member/lang.korean/pages/_pc/mypage/info.php | 22757 | <?php include_once $g['dir_module_skin'].'_menu.php'?>
<div id="pages_join">
<form name="procForm" action="<?php echo $g['s']?>/" method="post" target="_action_frame_<?php echo $m?>" onsubmit="return saveCheck(this);">
<input type="hidden" name="r" value="<?php echo $r?>" />
<input type="hidden" name="m" value="<?php echo $m?>" />
<input type="hidden" name="front" value="<?php echo $front?>" />
<input type="hidden" name="a" value="info_update" />
<input type="hidden" name="check_nic" value="<?php echo $my['nic']?1:0?>" />
<input type="hidden" name="check_email" value="<?php echo $my['email']?1:0?>" />
<div class="msg">
<span class="b">(*)</span> 표시가 있는 항목은 반드시 입력해야 합니다.<br />
허위로 작성된 정보일 경우 승인이 보류되거나 임의로 삭제처리될 수 있으니 주의해 주세요.
</div>
<table summary="회원가입 기본정보를 입력받는 표입니다.">
<caption>회원가입 기본정보</caption>
<colgroup>
<col width="100">
<col>
</colgroup>
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="key">이름(실명)<span>*</span></td>
<td>
<input type="text" name="name" value="<?php echo $my['name']?>" maxlength="10" class="input"/>
</td>
</tr>
<?php if($d['member']['form_nic']):?>
<tr>
<td class="key">닉네임<?php if($d['member']['form_nic_p']):?><span>*</span><?php endif?></td>
<td>
<input type="text" name="nic" value="<?php echo $my['nic']?>" maxlength="20" class="input" onblur="sameCheck(this,'hLayernic');" />
<span class="hmsg" id="hLayernic"></span>
<div>닉네임은 자신을 표현할 수 있는 단어로 20자까지 자유롭게 사용할 수 있습니다.</div>
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_birth']):?>
<tr>
<td class="key">생년월일<?php if($d['member']['form_birth_p']):?><span>*</span><?php endif?></td>
<td>
<select name="birth_1">
<option value="">년도</option>
<?php for($i = substr($date['today'],0,4); $i > 1930; $i--):?>
<option value="<?php echo $i?>"<?php if($my['birth1']==$i):?> selected="selected"<?php endif?>><?php echo $i?></option>
<?php endfor?>
</select>
<select name="birth_2">
<option value="">월</option>
<?php $birth_2=substr($my['birth2'],0,2)?>
<?php for($i = 1; $i < 13; $i++):?>
<option value="<?php echo sprintf('%02d',$i)?>"<?php if($birth_2==$i):?> selected="selected"<?php endif?>><?php echo $i?></option>
<?php endfor?>
</select>
<select name="birth_3">
<option value="">일</option>
<?php $birth_3=substr($my['birth2'],2,2)?>
<?php for($i = 1; $i < 32; $i++):?>
<option value="<?php echo sprintf('%02d',$i)?>"<?php if($birth_3==$i):?> selected="selected"<?php endif?>><?php echo $i?></option>
<?php endfor?>
</select>
<input type="checkbox" name="birthtype" value="1"<?php if($my['birthtype']):?> checked="checked"<?php endif?> />음력<br />
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_sex']):?>
<tr>
<td class="key">성별<?php if($d['member']['form_sex_p']):?><span>*</span><?php endif?></td>
<td class="shift">
<input type="radio" name="sex" value="1"<?php if($my['sex']==1):?> checked="checked"<?php endif?> />남성
<input type="radio" name="sex" value="2"<?php if($my['sex']==2):?> checked="checked"<?php endif?> />여성
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_qa']):?>
<tr>
<td class="key">비번찾기 질문<?php if($d['member']['form_qa_p']):?><span>*</span><?php endif?></td>
<td>
<input type="text" name="pw_q" value="<?php echo $my['pw_q']?>" class="input pw_q2" />
</td>
</tr>
<tr>
<td class="key">비번찾기 답변<?php if($d['member']['form_qa_p']):?><span>*</span><?php endif?></td>
<td>
<input type="text" name="pw_a" value="<?php echo $my['pw_a']?>" class="input" />
<div>
비밀번호찾기 질문에 대한 답변을 혼자만 알 수 있는 단어나 기호로 입력해 주세요.<br />
비밀번호를 찾을 때 필요하므로 반드시 기억해 주세요.
</div>
</td>
</tr>
<?php endif?>
<tr>
<td class="key">이메일<span>*</span></td>
<td>
<input type="text" name="email" value="<?php echo $my['email']?>" size="35" class="input" onblur="sameCheck(this,'hLayeremail');" />
<span class="hmsg" id="hLayeremail"></span>
<div>주로 사용하는 이메일 주소를 입력해 주세요. 비밀번호 잊어버렸을 때 확인 받을 수 있습니다.</div>
<div class="remail"><input type="checkbox" name="remail" value="1"<?php if($my['mailing']):?> checked="checked"<?php endif?> />뉴스레터나 공지이메일을 수신받겠습니다.</div>
</td>
</tr>
<?php if($d['member']['form_home']):?>
<tr>
<td class="key">홈페이지<?php if($d['member']['form_home_p']):?><span>*</span><?php endif?></td>
<td>
<input type="text" name="home" value="<?php echo $my['home']?>" size="35" class="input" />
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_tel2']):?>
<tr>
<td class="key">휴대전화<?php if($d['member']['form_tel2_p']):?><span>*</span><?php endif?></td>
<td><?php $tel2=explode('-',$my['tel2'])?>
<input type="text" name="tel2_1" value="<?php echo $tel2[0]?>" maxlength="3" size="4" class="input" />-
<input type="text" name="tel2_2" value="<?php echo $tel2[1]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="tel2_3" value="<?php echo $tel2[2]?>" maxlength="4" size="4" class="input" />
<div class="remail"><input type="checkbox" name="sms" value="1"<?php if($my['sms']):?> checked="checked"<?php endif?> />알림문자를 받겠습니다.</div>
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_tel1']):?>
<tr>
<td class="key">전화번호<?php if($d['member']['form_tel1_p']):?><span>*</span><?php endif?></td>
<td><?php $tel1=explode('-',$my['tel1'])?>
<input type="text" name="tel1_1" value="<?php echo $tel1[0]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="tel1_2" value="<?php echo $tel1[1]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="tel1_3" value="<?php echo $tel1[2]?>" maxlength="4" size="4" class="input" />
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_addr']):?>
<tr>
<td class="key">주소<?php if($d['member']['form_addr_p']):?><span>*</span><?php endif?></td>
<td>
<div id="addrbox"<?php if($my['addr0']=='해외'):?> class="hide"<?php endif?>>
<div>
<input type="text" name="zip_1" id="zip1" value="<?php echo substr($my['zip'],0,3)?>" maxlength="3" size="3" readonly="readonly" class="input" />-
<input type="text" name="zip_2" id="zip2" value="<?php echo substr($my['zip'],3,3)?>" maxlength="3" size="3" readonly="readonly" class="input" />
<input type="button" value="우편번호" class="btngray btn" onclick="OpenWindow('<?php echo $g['s']?>/?r=<?php echo $r?>&m=zipsearch&zip1=zip1&zip2=zip2&addr1=addr1&focusfield=addr2');" />
</div>
<div><input type="text" name="addr1" id="addr1" value="<?php echo $my['addr1']?>" size="55" readonly="readonly" class="input" /></div>
<div><input type="text" name="addr2" id="addr2" value="<?php echo $my['addr2']?>" size="55" class="input" /></div>
</div>
<?php if($d['member']['form_foreign']):?>
<div class="remail shift">
<?php if($my['addr0']=='해외'):?>
<input type="checkbox" name="foreign" value="1" checked="checked" onclick="foreignChk(this);" /><span id="foreign_ment">해외거주자 입니다.</span>
<?php else:?>
<input type="checkbox" name="foreign" value="1" onclick="foreignChk(this);" /><span id="foreign_ment">해외거주자일 경우 체크해 주세요.</span>
<?php endif?>
</div>
<?php endif?>
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_job']):?>
<tr>
<td class="key">직업<?php if($d['member']['form_job_p']):?><span>*</span><?php endif?></td>
<td>
<select name="job">
<option value=""> + 선택하세요</option>
<option value="">------------------</option>
<?php $_job=file($g['dir_module'].'var/job.txt')?>
<?php foreach($_job as $_val):?>
<option value="<?php echo trim($_val)?>"<?php if(trim($_val)==$my['job']):?> selected="selected"<?php endif?>>ㆍ<?php echo trim($_val)?></option>
<?php endforeach?>
</select>
</td>
</tr>
<?php endif?>
<?php if($d['member']['form_marr']):?>
<tr>
<td class="key">결혼기념일<?php if($d['member']['form_marr_p']):?><span>*</span><?php endif?></td>
<td>
<select name="marr_1">
<option value="">년도</option>
<?php for($i = substr($date['today'],0,4); $i > 1930; $i--):?>
<option value="<?php echo $i?>"<?php if($i==$my['marr1']):?> selected="selected"<?php endif?>><?php echo $i?></option>
<?php endfor?>
</select>
<select name="marr_2">
<option value="">월</option>
<?php for($i = 1; $i < 13; $i++):?>
<option value="<?php echo sprintf('%02d',$i)?>"<?php if($i==substr($my['marr2'],0,2)):?> selected="selected"<?php endif?>><?php echo $i?></option>
<?php endfor?>
</select>
<select name="marr_3">
<option value="">일</option>
<?php for($i = 1; $i < 32; $i++):?>
<option value="<?php echo sprintf('%02d',$i)?>"<?php if($i==substr($my['marr2'],2,2)):?> selected="selected"<?php endif?>><?php echo $i?></option>
<?php endfor?>
</select>
</td>
</tr>
<?php endif?>
<?php $_add = file($g['dir_module'].'var/add_field.txt')?>
<?php foreach($_add as $_key):?>
<?php $_val = explode('|',trim($_key))?>
<?php if($_val[6]) continue?>
<?php $_myadd1 = explode($_val[0].'^^^',$my['addfield'])?>
<?php $_myadd2 = explode('|||',$_myadd1[1])?>
<tr>
<td class="key"><?php echo $_val[1]?><?php if($_val[5]):?><span>*</span><?php endif?></td>
<td>
<?php if($_val[2]=='text'):?>
<input type="text" name="add_<?php echo $_val[0]?>" class="input" style="width:<?php echo $_val[4]?>px;" value="<?php echo $_myadd2[0]?>" />
<?php endif?>
<?php if($_val[2]=='password'):?>
<input type="password" name="add_<?php echo $_val[0]?>" class="input" style="width:<?php echo $_val[4]?>px;" value="<?php echo $_myadd2[0]?>" />
<?php endif?>
<?php if($_val[2]=='select'): $_skey=explode(',',$_val[3])?>
<select name="add_<?php echo $_val[0]?>" style="width:<?php echo $_val[4]?>px;">
<option value=""> + 선택하세요</option>
<?php foreach($_skey as $_sval):?>
<option value="<?php echo trim($_sval)?>"<?php if(trim($_sval)==$_myadd2[0]):?> selected="selected"<?php endif?>>ㆍ<?php echo trim($_sval)?></option>
<?php endforeach?>
</select>
<?php endif?>
<?php if($_val[2]=='radio'): $_skey=explode(',',$_val[3])?>
<div class="shift">
<?php foreach($_skey as $_sval):?>
<input type="radio" name="add_<?php echo $_val[0]?>" value="<?php echo trim($_sval)?>"<?php if(trim($_sval)==$_myadd2[0]):?> checked="checked"<?php endif?> /><?php echo trim($_sval)?>
<?php endforeach?>
</div>
<?php endif?>
<?php if($_val[2]=='checkbox'): $_skey=explode(',',$_val[3])?>
<div class="shift">
<?php foreach($_skey as $_sval):?>
<input type="checkbox" name="add_<?php echo $_val[0]?>[]" value="<?php echo trim($_sval)?>"<?php if(strstr($_myadd2[0],'['.trim($_sval).']')):?> checked="checked"<?php endif?> /><?php echo trim($_sval)?>
<?php endforeach?>
</div>
<?php endif?>
<?php if($_val[2]=='textarea'):?>
<textarea name="add_<?php echo $_val[0]?>" rows="5" style="width:<?php echo $_val[4]?>px;"><?php echo $_myadd2[0]?></textarea>
<?php endif?>
</tr>
<?php endforeach?>
</tbody>
</table>
<?php if($d['member']['form_comp']):?>
<?php if($my['comp']) $myc = getDbData($table['s_mbrcomp'],'memberuid='.$my['uid'],'*')?>
<?php $tel = explode('-',$myc['comp_tel'])?>
<?php $fax = explode('-',$myc['comp_fax'])?>
<div class="tt_comp">
기업정보
<?php if(!$my['comp']):?>
<span class="tt_check">(<input type="checkbox" name="comp" value="1" />기업정보를 등록합니다)</span>
<?php else:?>
<input type="checkbox" name="comp" value="1" checked="checked" class="hide" />
<?php endif?>
</div>
<table summary="회원가입 기업정보를 입력받는 표입니다.">
<caption>회원가입 기업정보</caption>
<colgroup>
<col width="100">
<col>
</colgroup>
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="key">사업자등록번호<span>*</span></td>
<td colspan="3">
<input type="text" name="comp_num_1" size="4" maxlength="3" class="input" value="<?php echo substr($myc['comp_num'],0,3)?>" /> -
<input type="text" name="comp_num_2" size="3" maxlength="2" class="input" value="<?php echo substr($myc['comp_num'],3,2)?>" /> -
<input type="text" name="comp_num_3" size="5" maxlength="5" class="input" value="<?php echo substr($myc['comp_num'],5,5)?>" />
<input type="radio" name="comp_type" value="1"<?php if($myc['comp_type']==1||!$myc['comp_type']):?> checked="checked"<?php endif?> />개인
<input type="radio" name="comp_type" value="2"<?php if($myc['comp_type']==2):?> checked="checked"<?php endif?> />법인
</td>
</tr>
<tr>
<td class="key">회사명<span>*</span></td>
<td>
<input type="text" name="comp_name" class="input" value="<?php echo $myc['comp_name']?>" />
</td>
<td class="key">대표자명<span>*</span></td>
<td>
<input type="text" name="comp_ceo" class="input" value="<?php echo $myc['comp_ceo']?>" />
</td>
</tr>
<tr>
<td class="key">업태<span>*</span></td>
<td>
<input type="text" name="comp_upte" class="input" value="<?php echo $myc['comp_upte']?>" />
</td>
<td class="key">종목<span>*</span></td>
<td>
<input type="text" name="comp_jongmok" class="input" value="<?php echo $myc['comp_jongmok']?>" />
</td>
</tr>
<tr>
<td class="key">대표전화<span>*</span></td>
<td>
<input type="text" name="comp_tel_1" value="<?php echo $tel[0]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="comp_tel_2" value="<?php echo $tel[1]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="comp_tel_3" value="<?php echo $tel[2]?>" maxlength="4" size="4" class="input" />
</td>
<td class="key">팩스</td>
<td>
<input type="text" name="comp_fax_1" value="<?php echo $fax[0]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="comp_fax_2" value="<?php echo $fax[1]?>" maxlength="4" size="4" class="input" />-
<input type="text" name="comp_fax_3" value="<?php echo $fax[2]?>" maxlength="4" size="4" class="input" />
</td>
</tr>
<tr>
<td class="key">소속부서</td>
<td>
<input type="text" name="comp_part" class="input" value="<?php echo $myc['comp_part']?>" />
</td>
<td class="key">직책</td>
<td>
<input type="text" name="comp_level" class="input" value="<?php echo $myc['comp_level']?>" />
</td>
</tr>
<tr>
<td class="key">사업장주소<span>*</span></td>
<td colspan="3">
<div>
<input type="text" name="comp_zip_1" id="comp_zip1" value="<?php echo substr($myc['comp_zip'],0,3)?>" maxlength="3" size="3" readonly="readonly" class="input" />-
<input type="text" name="comp_zip_2" id="comp_zip2" value="<?php echo substr($myc['comp_zip'],3,3)?>" maxlength="3" size="3" readonly="readonly" class="input" />
<input type="button" value="우편번호" class="btngray btn" onclick="OpenWindow('<?php echo $g['s']?>/?r=<?php echo $r?>&m=zipsearch&zip1=comp_zip1&zip2=comp_zip2&addr1=comp_addr1&focusfield=comp_addr2');" />
</div>
<div><input type="text" name="comp_addr1" id="comp_addr1" value="<?php echo $myc['comp_addr1']?>" size="55" readonly="readonly" class="input" /></div>
<div><input type="text" name="comp_addr2" id="comp_addr2" value="<?php echo $myc['comp_addr2']?>" size="55" class="input" /></div>
</div>
</td>
</tr>
</tbody>
</table>
<?php endif?>
<div class="submitbox">
<input type="submit" value="정보수정" class="btnblue" />
</div>
</form>
</div>
<script type="text/javascript">
//<![CDATA[
function foreignChk(obj)
{
if (obj.checked == true)
{
getId('addrbox').style.display = 'none';
getId('foreign_ment').innerHTML= '해외거주자 입니다.';
}
else {
getId('addrbox').style.display = 'block';
getId('foreign_ment').innerHTML= '해외거주자일 경우 체크해 주세요.';
}
}
function sameCheck(obj,layer)
{
if (!obj.value)
{
eval('obj.form.check_'+obj.name).value = '0';
getId(layer).innerHTML = '';
}
else
{
if (obj.name == 'email')
{
if (!chkEmailAddr(obj.value))
{
obj.form.check_email.value = '0';
obj.focus();
getId(layer).innerHTML = '이메일형식이 아닙니다.';
return false;
}
}
frames._action_frame_<?php echo $m?>.location.href = '<?php echo $g['s']?>/?r=<?php echo $r?>&m=<?php echo $m?>&a=same_check&fname=' + obj.name + '&fvalue=' + obj.value + '&flayer=' + layer;
}
}
function saveCheck(f)
{
<?php if($d['member']['form_nic_p']):?>
if (f.check_nic.value == '0')
{
alert('닉네임을 확인해 주세요.');
f.nic.focus();
return false;
}
<?php endif?>
<?php if($d['member']['form_birth']&&$d['member']['form_birth_p']):?>
if (f.birth_1.value == '')
{
alert('생년월일을 지정해 주세요.');
f.birth_1.focus();
return false;
}
if (f.birth_2.value == '')
{
alert('생년월일을 지정해 주세요.');
f.birth_2.focus();
return false;
}
if (f.birth_3.value == '')
{
alert('생년월일을 지정해 주세요.');
f.birth_3.focus();
return false;
}
<?php endif?>
<?php if($d['member']['form_sex']&&$d['member']['form_sex_p']):?>
if (f.sex[0].checked == false && f.sex[1].checked == false)
{
alert('성별을 선택해 주세요. ');
return false;
}
<?php endif?>
<?php if($d['member']['form_qa']&&$d['member']['form_qa_p']):?>
if (f.pw_q.value == '')
{
alert('비밀번호 찾기 질문을 입력해 주세요.');
f.pw_q.focus();
return false;
}
if (f.pw_a.value == '')
{
alert('비밀번호 찾기 답변을 입력해 주세요.');
f.pw_a.focus();
return false;
}
<?php endif?>
if (f.check_email.value == '0')
{
alert('이메일을 확인해 주세요.');
f.email.focus();
return false;
}
<?php if($d['member']['form_home']&&$d['member']['form_home_p']):?>
if (f.home.value == '')
{
alert('홈페이지 주소를 입력해 주세요.');
f.home.focus();
return false;
}
<?php endif?>
<?php if($d['member']['form_tel2']&&$d['member']['form_tel2_p']):?>
if (f.tel2_1.value == '')
{
alert('휴대폰번호를 입력해 주세요.');
f.tel2_1.focus();
return false;
}
if (f.tel2_2.value == '')
{
alert('휴대폰번호를 입력해 주세요.');
f.tel2_2.focus();
return false;
}
if (f.tel2_3.value == '')
{
alert('휴대폰번호를 입력해 주세요.');
f.tel2_3.focus();
return false;
}
<?php endif?>
<?php if($d['member']['form_tel1']&&$d['member']['form_tel1_p']):?>
if (f.tel1_1.value == '')
{
alert('전화번호를 입력해 주세요.');
f.tel1_1.focus();
return false;
}
if (f.tel1_2.value == '')
{
alert('전화번호를 입력해 주세요.');
f.tel1_2.focus();
return false;
}
if (f.tel1_3.value == '')
{
alert('전화번호를 입력해 주세요.');
f.tel1_3.focus();
return false;
}
<?php endif?>
<?php if($d['member']['form_addr']&&$d['member']['form_addr_p']):?>
if (!f.foreign || f.foreign.checked == false)
{
if (f.addr1.value == ''||f.addr2.value == '')
{
alert('주소를 입력해 주세요.');
f.addr2.focus();
return false;
}
}
<?php endif?>
<?php if($d['member']['form_job']&&$d['member']['form_job_p']):?>
if (f.job.value == '')
{
alert('직업을 선택해 주세요.');
f.job.focus();
return false;
}
<?php endif?>
<?php if($d['member']['form_marr']&&$d['member']['form_marr_p']):?>
if (f.marr_1.value == '')
{
alert('결혼기념일을 지정해 주세요.');
f.marr_1.focus();
return false;
}
if (f.marr_2.value == '')
{
alert('결혼기념일을 지정해 주세요.');
f.marr_2.focus();
return false;
}
if (f.marr_3.value == '')
{
alert('결혼기념일을 지정해 주세요.');
f.marr_3.focus();
return false;
}
<?php endif?>
var radioarray;
var checkarray;
var i;
var j = 0;
<?php foreach($_add as $_key):?>
<?php $_val = explode('|',trim($_key))?>
<?php if(!$_val[5]||$_val[6]) continue?>
<?php if($_val[2]=='text' || $_val[2]=='password' || $_val[2]=='select' || $_val[2]=='textarea'):?>
if (f.add_<?php echo $_val[0]?>.value == '')
{
alert('<?php echo $_val[1]?>이(가) <?php echo $_val[2]=='select'?'선택':'입력'?>되지 않았습니다. ');
f.add_<?php echo $_val[0]?>.focus();
return false;
}
<?php endif?>
<?php if($_val[2]=='radio'):?>
j = 0;
radioarray = f.add_<?php echo $_val[0]?>;
for (i = 0; i < radioarray.length; i++)
{
if (radioarray[i].checked == true) j++;
}
if (!j)
{
alert('<?php echo $_val[1]?>이(가) 선택되지 않았습니다. ');
radioarray[0].focus();
return false;
}
<?php endif?>
<?php if($_val[2]=='checkbox'):?>
j = 0;
checkarray = document.getElementsByName("add_<?php echo $_val[0]?>[]");
for (i = 0; i < checkarray.length; i++)
{
if (checkarray[i].checked == true) j++;
}
if (!j)
{
alert('<?php echo $_val[1]?>이(가) 선택되지 않았습니다. ');
checkarray[0].focus();
return false;
}
<?php endif?>
<?php endforeach?>
<?php if($d['member']['form_comp']):?>
if (f.comp.checked == true)
{
if (f.comp_num_1.value == '')
{
alert('사업자등록번호를 입력해 주세요. ');
f.comp_num_1.focus();
return false;
}
if (f.comp_num_2.value == '')
{
alert('사업자등록번호를 입력해 주세요. ');
f.comp_num_2.focus();
return false;
}
if (f.comp_num_3.value == '')
{
alert('사업자등록번호를 입력해 주세요. ');
f.comp_num_3.focus();
return false;
}
if (f.comp_name.value == '')
{
alert('회사명을 입력해 주세요. ');
f.comp_name.focus();
return false;
}
if (f.comp_ceo.value == '')
{
alert('대표자명을 입력해 주세요. ');
f.comp_ceo.focus();
return false;
}
if (f.comp_upte.value == '')
{
alert('업태를 입력해 주세요. ');
f.comp_upte.focus();
return false;
}
if (f.comp_jongmok.value == '')
{
alert('종목을 입력해 주세요. ');
f.comp_jongmok.focus();
return false;
}
if (f.comp_tel_1.value == '')
{
alert('대표전화번호를 입력해 주세요.');
f.comp_tel_1.focus();
return false;
}
if (f.comp_tel_2.value == '')
{
alert('대표전화번호를 입력해 주세요.');
f.comp_tel_2.focus();
return false;
}
if (f.comp_addr1.value == '')
{
alert('사업장주소를 입력해 주세요.');
f.comp_addr2.focus();
return false;
}
}
<?php endif?>
return confirm('정말로 수정하시겠습니까? ');
}
//]]>
</script>
| lgpl-2.1 |
agentlab/powerloom-osgi | plugins/edu.isi.powerloom/src/edu/isi/powerloom/logic/SubsumptionInferenceLevel.java | 9537 | // -*- Mode: Java -*-
//
// SubsumptionInferenceLevel.java
/*
+---------------------------- BEGIN LICENSE BLOCK ---------------------------+
| |
| Version: MPL 1.1/GPL 2.0/LGPL 2.1 |
| |
| The contents of this file are subject to the Mozilla Public License |
| Version 1.1 (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.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" basis, |
| WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License |
| for the specific language governing rights and limitations under the |
| License. |
| |
| The Original Code is the PowerLoom KR&R System. |
| |
| The Initial Developer of the Original Code is |
| UNIVERSITY OF SOUTHERN CALIFORNIA, INFORMATION SCIENCES INSTITUTE |
| 4676 Admiralty Way, Marina Del Rey, California 90292, U.S.A. |
| |
| Portions created by the Initial Developer are Copyright (C) 1997-2012 |
| the Initial Developer. All Rights Reserved. |
| |
| Contributor(s): |
| |
| Alternatively, the contents of this file may be used under the terms of |
| either the GNU General Public License Version 2 or later (the "GPL"), or |
| the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), |
| in which case the provisions of the GPL or the LGPL are applicable instead |
| of those above. If you wish to allow use of your version of this file only |
| under the terms of either the GPL or the LGPL, and not to allow others to |
| use your version of this file under the terms of the MPL, indicate your |
| decision by deleting the provisions above and replace them with the notice |
| and other provisions required by the GPL or the LGPL. If you do not delete |
| the provisions above, a recipient may use your version of this file under |
| the terms of any one of the MPL, the GPL or the LGPL. |
| |
+----------------------------- END LICENSE BLOCK ----------------------------+
*/
package edu.isi.powerloom.logic;
import edu.isi.stella.javalib.Native;
import edu.isi.stella.javalib.StellaSpecialVariable;
import edu.isi.stella.*;
/** Specifies lookup augmented with cached
* subsumption links and equality reasoning.
* @author Stella Java Translator
*/
public class SubsumptionInferenceLevel extends BacktrackingInferenceLevel {
public static SubsumptionInferenceLevel newSubsumptionInferenceLevel() {
{ SubsumptionInferenceLevel self = null;
self = new SubsumptionInferenceLevel();
self.keyword = null;
return (self);
}
}
public Cons levellizedAllSlotValueTypes(LogicObject self, Surrogate relation) {
{ SubsumptionInferenceLevel level = this;
{ Cons valuetypes = Logic.SHALLOW_INFERENCE.levellizedAllSlotValueTypes(self, relation);
{ NamedDescription superrelation = null;
Cons iter000 = NamedDescription.allSuperrelations(Logic.getDescription(relation), false);
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
superrelation = ((NamedDescription)(iter000.value));
{ Stella_Object supertype = null;
Cons iter001 = Logic.allRelationValues(Logic.SGT_PL_KERNEL_KB_RANGE_TYPE, Cons.consList(Cons.cons(superrelation, Cons.cons(self, Stella.NIL))));
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
supertype = iter001.value;
if (!valuetypes.memberP(supertype)) {
valuetypes = Cons.cons(supertype, valuetypes);
}
}
}
}
}
return (Logic.filterOutUnnamedDescriptions(valuetypes));
}
}
}
public int levellizedGetSlotMaximumCardinality(LogicObject self, Surrogate relation) {
{ SubsumptionInferenceLevel level = this;
{ int maxcardinality = Logic.SHALLOW_INFERENCE.levellizedGetSlotMaximumCardinality(self, relation);
{ NamedDescription superdescription = null;
Cons iter000 = NamedDescription.allSuperrelations(Logic.getDescription(relation), false);
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
superdescription = ((NamedDescription)(iter000.value));
{ Stella_Object supermaxcardinality = Logic.allRelationValues(Logic.SGT_PL_KERNEL_KB_RANGE_MAX_CARDINALITY, Cons.consList(Cons.cons(superdescription, Cons.cons(self, Stella.NIL)))).value;
if (supermaxcardinality != null) {
if (maxcardinality != Stella.NULL_INTEGER) {
maxcardinality = Stella.integer_min(maxcardinality, ((IntegerWrapper)(supermaxcardinality)).wrapperValue);
}
else {
maxcardinality = ((IntegerWrapper)(supermaxcardinality)).wrapperValue;
}
}
}
}
}
return (maxcardinality);
}
}
}
public int levellizedGetSlotMinimumCardinality(LogicObject self, Surrogate relation) {
{ SubsumptionInferenceLevel level = this;
{ int mincardinality = Logic.SHALLOW_INFERENCE.levellizedGetSlotMinimumCardinality(self, relation);
{ NamedDescription subdescription = null;
Cons iter000 = NamedDescription.allSubrelations(Logic.getDescription(relation), false);
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
subdescription = ((NamedDescription)(iter000.value));
{ Stella_Object submincardinality = Logic.allRelationValues(Logic.SGT_PL_KERNEL_KB_RANGE_MIN_CARDINALITY, Cons.consList(Cons.cons(subdescription, Cons.cons(self, Stella.NIL)))).value;
if (submincardinality != null) {
mincardinality = Stella.integer_max(mincardinality, ((IntegerWrapper)(submincardinality)).wrapperValue);
}
}
}
}
return (mincardinality);
}
}
}
public boolean levellizedTestRelationOnArgumentsP(Surrogate relation, Cons arguments) {
{ SubsumptionInferenceLevel level = this;
{ boolean foundP000 = false;
{ ConsIterator p = Logic.allPropositionsMatchingArguments(arguments, relation, level == Logic.SUBSUMPTION_INFERENCE).allocateIterator();
loop000 : while (p.nextP()) {
foundP000 = true;
break loop000;
}
}
{ boolean value000 = foundP000;
return (value000);
}
}
}
}
public Cons levellizedAllRelationValues(Surrogate relation, Cons nminusonearguments) {
{ SubsumptionInferenceLevel level = this;
{ Cons values = Stella.NIL;
{ Proposition p = null;
Cons iter000 = Logic.allPropositionsMatchingArguments(nminusonearguments, relation, level == Logic.SUBSUMPTION_INFERENCE);
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
p = ((Proposition)(iter000.value));
{ Stella_Object value000 = Logic.valueOf((p.arguments.theArray)[(p.arguments.length() - 1)]);
values = (values.memberP(value000) ? values : Cons.cons(value000, values));
}
}
}
return (values);
}
}
}
public Cons levellizedAllClassInstances(Surrogate type) {
{ SubsumptionInferenceLevel level = this;
{ Cons members = Stella.NIL;
{ Stella_Object m = null;
Cons iter000 = Logic.assertedCollectionMembers(Logic.getDescription(type), false).theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
m = iter000.value;
members = Cons.cons(m, members);
}
}
return (members);
}
}
}
public boolean levellizedTestTypeOnInstanceP(Stella_Object self, Surrogate type) {
{ SubsumptionInferenceLevel level = this;
{ boolean foundP000 = false;
{ Proposition p = null;
Iterator iter000 = Logic.allTrueDependentPropositions(self, type, true);
loop000 : while (iter000.nextP()) {
p = ((Proposition)(iter000.value));
if (p.kind == Logic.KWD_ISA) {
foundP000 = true;
break loop000;
}
}
}
{ boolean value000 = foundP000;
return (value000);
}
}
}
}
public Surrogate primaryType() {
{ SubsumptionInferenceLevel self = this;
return (Logic.SGT_LOGIC_SUBSUMPTION_INFERENCE_LEVEL);
}
}
}
| lgpl-2.1 |
JojoCMS/Jojo-CMS | plugins/jojo_core/classes/Jojo/Field/Textarea.php | 2092 | <?php
/**
* Jojo CMS
* ================
*
* Copyright 2007-2008 Harvey Kane <[email protected]>
* Copyright 2007-2008 Michael Holt <[email protected]>
* Copyright 2007 Melanie Schulz <[email protected]>
*
* See the enclosed file license.txt for license information (LGPL). If you
* did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
*
* @author Harvey Kane <[email protected]>
* @author Michael Cochrane <[email protected]>
* @author Melanie Schulz <[email protected]>
* @license http://www.fsf.org/copyleft/lgpl.html GNU Lesser General Public License
* @link http://www.jojocms.org JojoCMS
* @package jojo_core
*/
class Jojo_Field_textarea extends Jojo_Field
{
var $rows;
var $cols;
var $counter = 0;
var $texttype;
function __construct($fielddata = array())
{
parent::__construct($fielddata);
$this->rows = 5;
$this->cols = 50;
if (!empty($fielddata['fd_rows'])) $this->rows = $fielddata['fd_rows'];
if (!empty($fielddata['fd_cols'])) $this->cols = $fielddata['fd_cols'];
}
function displayedit()
{
global $smarty;
if ($this->texttype == 'metadescription') {
$this->counter = 155;
} elseif ($this->fd_options == 'metadescription') {
$this->counter = 155;
} elseif (is_numeric($this->fd_options)) {
$this->counter = $this->fd_options;
} else {
$this->counter = 0;
}
$smarty->assign('rows', $this->rows);
$smarty->assign('cols', $this->cols);
$smarty->assign('counterstrlen', $this->counter - strlen($this->value));
$smarty->assign('value', $this->value);
$smarty->assign('counter', $this->counter);
$smarty->assign('fd_field', $this->fd_field);
$smarty->assign('readonly', $this->fd_readonly);
$smarty->assign('fd_help', htmlentities($this->fd_help));
return $smarty->fetch('admin/fields/textarea.tpl');
}
} | lgpl-2.1 |
gambess/ERP-Arica | htdocs/lib/antivir.class.php | 4836 | <?php
/* Copyright (C) 2000-2005 Rodolphe Quiedeville <[email protected]>
* Copyright (C) 2003 Jean-Louis Bergamo <[email protected]>
* Copyright (C) 2004-2009 Laurent Destailleur <[email protected]>
* Copyright (C) 2005-2009 Regis Houssin <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/lib/antivir.class.php
* \brief File of class to scan viruses
* \version $Id: antivir.class.php,v 1.8 2011/07/31 23:25:40 eldy Exp $
* \author Laurent Destailleur.
*/
/**
* \class AntiVir
* \brief Class to scan for virus
*/
class AntiVir
{
var $error;
var $errors;
var $output;
var $db;
/**
* Constructor
*
* @param $db
* @return AntiVir
*/
function AntiVir($db)
{
$this->db=$db;
}
/**
* Scan a file with antivirus.
* This function runs the command defined in setup. This antivirus command must return 0 if OK.
* @param file File to scan
* @return int <0 if KO (-98 if error, -99 if virus), 0 if OK
*/
function dol_avscan_file($file)
{
global $conf;
$return = 0;
$fullcommand=$this->getCliCommand($file);
//$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"';
$fullcommand.=' 2>&1'; // This is to get error output
$output=array();
$return_var=0;
$safemode=ini_get("safe_mode");
// Create a clean fullcommand
dol_syslog("AntiVir::dol_avscan_file Run command=".$fullcommand." with safe_mode ".($safe_mode?"on":"off"));
// Run CLI command. If run of Windows, you can get return with echo %ERRORLEVEL%
$lastline=exec($fullcommand, $output, $return_var);
//print "x".$lastline." - ".join(',',$output)." - ".$return_var."y";exit;
/*
$outputfile=$conf->admin->dir_temp.'/dol_avscan_file.out.'.session_id();
$handle = fopen($outputfile, 'w');
if ($handle)
{
$handlein = popen($fullcommand, 'r');
while (!feof($handlein))
{
$read = fgets($handlein);
fwrite($handle,$read);
}
pclose($handlein);
$errormsg = fgets($handle,2048);
$this->output=$errormsg;
fclose($handle);
if (! empty($conf->global->MAIN_UMASK))
@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
}
else
{
$langs->load("errors");
dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
$this->error="ErrorFailedToWriteInDir";
$return=-1;
}
*/
dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',',$output));
$returncodevirus=1;
if ($return_var == $returncodevirus) // Virus found
{
$this->errors=$output;
return -99;
}
if ($return_var > 0) // If other error
{
$this->errors=$output;
return -98;
}
// If return code = 0
return 1;
}
/**
* \brief get full Command Line to run
* \param file File to scan
* \return string Full command line to run
*/
function getCliCommand($file)
{
global $conf;
$maxreclevel = 5 ; // maximal recursion level
$maxfiles = 1000; // maximal number of files to be scanned within archive
$maxratio = 200; // maximal compression ratio
$bz2archivememlim = 0; // limit memory usage for bzip2 (0/1)
$maxfilesize = 10485760; // archived files larger than this value (in bytes) will not be scanned
$command=$conf->global->MAIN_ANTIVIRUS_COMMAND;
$param=$conf->global->MAIN_ANTIVIRUS_PARAM;
$param=preg_replace('/%maxreclevel/',$maxreclevel,$param);
$param=preg_replace('/%maxfiles/',$maxfiles,$param);
$param=preg_replace('/%maxratio/',$maxratio,$param);
$param=preg_replace('/%bz2archivememlim/',$bz2archivememlim,$param);
$param=preg_replace('/%maxfilesize/',$maxfilesize,$param);
$param=preg_replace('/%file/',trim($file),$param);
if (! preg_match('/%file/',$conf->global->MAIN_ANTIVIRUS_PARAM))
$param=$param." ".escapeshellarg(trim($file));
if (preg_match("/\s/",$command)) $command=escapeshellarg($command); // Use quotes on command. Using escapeshellcmd fails.
$ret=$command.' '.$param;
//$ret=$command.' '.$param.' 2>&1';
//print "xx".$ret."xx";exit;
return $ret;
}
}
?> | lgpl-2.1 |
usox/PHPTAL | tests/BlockTest.php | 1599 | <?php
declare(strict_types=1);
/**
* PHPTAL templating engine
*
* Originally developed by Laurent Bedubourg and Kornel Lesiński
*
* @category HTML
* @package PHPTAL
* @author Laurent Bedubourg <[email protected]>
* @author Kornel Lesiński <[email protected]>
* @author See contributors list @ github
* @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
* @link http://phptal.org/
* @link https://github.com/SC-Networks/PHPTAL
*/
namespace Tests;
use PhpTal\Exception\ParserException;
use Tests\Testcase\PhpTalTestCase;
class BlockTest extends PhpTalTestCase
{
function testTalBlock()
{
$t = $this->newPHPTAL();
$t->setSource('<tal:block content="string:content"></tal:block>');
$res = $t->execute();
static::assertSame('content', $res);
}
function testMetalBlock()
{
$t = $this->newPHPTAL();
$t->setSource('<metal:block>foo</metal:block>');
$res = $t->execute();
static::assertSame('foo', $res);
}
function testSomeNamespaceBlock()
{
$t = $this->newPHPTAL();
$t->setSource('<foo:block xmlns:foo="http://phptal.example.com">foo</foo:block>');
$res = $t->execute();
static::assertSame('<foo:block xmlns:foo="http://phptal.example.com">foo</foo:block>', $res);
}
function testInvalidNamespaceBlock()
{
$this->expectException(ParserException::class);
$t = $this->newPHPTAL();
$t->setSource('<foo:block>foo</foo:block>');
$t->execute();
}
}
| lgpl-2.1 |
jbosgi/jbosgi-framework | itest/src/test/java/org/jboss/test/osgi/framework/resolver/support/b/BC.java | 1021 | package org.jboss.test.osgi.framework.resolver.support.b;
/*
* #%L
* JBossOSGi Framework
* %%
* Copyright (C) 2010 - 2012 JBoss by Red Hat
* %%
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.jboss.test.osgi.framework.resolver.support.c.C;
/**
* @author <a href="[email protected]">David Bosschaert</a>
*/
public class BC {
public BC(C a) {
}
}
| lgpl-2.1 |
cytoscape/cytoscape-impl | ding-impl/ding-presentation-impl/src/main/java/org/cytoscape/ding/dependency/NodeSizeDependencyFactory.java | 2031 | package org.cytoscape.ding.dependency;
/*
* #%L
* Cytoscape Ding View/Presentation Impl (ding-presentation-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2021 The Cytoscape Consortium
* %%
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Set;
import org.cytoscape.view.model.VisualLexicon;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
import org.cytoscape.view.vizmap.VisualPropertyDependencyFactory;
public class NodeSizeDependencyFactory implements VisualPropertyDependencyFactory<Double> {
private final VisualLexicon lexicon;
public NodeSizeDependencyFactory(final VisualLexicon lexicon) {
this.lexicon = lexicon;
}
@Override
public VisualPropertyDependency<Double> createVisualPropertyDependency() {
// Node Size Dependency
final Set<VisualProperty<Double>> nodeSizeVisualProperties = new HashSet<VisualProperty<Double>>();
nodeSizeVisualProperties.add(BasicVisualLexicon.NODE_WIDTH);
nodeSizeVisualProperties.add(BasicVisualLexicon.NODE_HEIGHT);
VisualPropertyDependency<Double> vpDep = new VisualPropertyDependency<Double>("nodeSizeLocked", "Lock node width and height", nodeSizeVisualProperties, lexicon);
vpDep.setDependency(true);
return vpDep;
}
}
| lgpl-2.1 |
Mbewu/libmesh | src/fe/inf_fe_base_radial.C | 5140 | // The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
#include "libmesh/inf_fe.h"
#include "libmesh/inf_fe_macro.h"
#include "libmesh/fe.h"
#include "libmesh/elem.h"
namespace libMesh
{
// ------------------------------------------------------------
// InfFE::Base class members
template <unsigned int Dim, FEFamily T_radial, InfMapType T_base>
Elem* InfFE<Dim,T_radial,T_base>::Base::build_elem (const Elem* inf_elem)
{
AutoPtr<Elem> ape(inf_elem->build_side(0));
return ape.release();
}
template <unsigned int Dim, FEFamily T_radial, InfMapType T_base>
ElemType InfFE<Dim,T_radial,T_base>::Base::get_elem_type (const ElemType type)
{
switch (type)
{
// 3D infinite elements:
// with Dim=3 -> infinite elements on their own
case INFHEX8:
return QUAD4;
case INFHEX16:
return QUAD8;
case INFHEX18:
return QUAD9;
case INFPRISM6:
return TRI3;
case INFPRISM12:
return TRI6;
// 2D infinite elements:
// with Dim=3 -> used as boundary condition,
// with Dim=2 -> infinite elements on their own
case INFQUAD4:
return EDGE2;
case INFQUAD6:
return EDGE3;
// 1D infinite elements:
// with Dim=2 -> used as boundary condition,
// with Dim=1 -> infinite elements on their own,
// but no base element!
case INFEDGE2:
return INVALID_ELEM;
default:
libmesh_error_msg("ERROR: Unsupported element type!: " << type);
}
libmesh_error_msg("We'll never get here!");
return INVALID_ELEM;
}
template <unsigned int Dim, FEFamily T_radial, InfMapType T_base>
unsigned int InfFE<Dim,T_radial,T_base>::Base::n_base_mapping_sf (const ElemType base_elem_type,
const Order base_mapping_order)
{
if (Dim == 1)
return 1;
else if (Dim == 2)
return FE<1,LAGRANGE>::n_shape_functions (base_elem_type,
base_mapping_order);
else if (Dim == 3)
return FE<2,LAGRANGE>::n_shape_functions (base_elem_type,
base_mapping_order);
else
{
libmesh_error_msg("Unsupported Dim = " << Dim);
return 0;
}
}
// ------------------------------------------------------------
// InfFE::Radial class members
template <unsigned int Dim, FEFamily T_radial, InfMapType T_map>
unsigned int InfFE<Dim,T_radial,T_map>::Radial::n_dofs_at_node (const Order o_radial,
const unsigned int n_onion)
{
libmesh_assert_less (n_onion, 2);
if (n_onion == 0)
/*
* in the base, no matter what, we have 1 node associated
* with radial direction
*/
return 1;
else
/*
* this works, since for Order o_radial=CONST=0, we still
* have the (1-v)/2 mode, associated to the base
*/
return static_cast<unsigned int>(o_radial);
}
//--------------------------------------------------------------
// Explicit instantiations
INSTANTIATE_INF_FE_MBRF(1,CARTESIAN,Elem*,Base::build_elem(const Elem*));
INSTANTIATE_INF_FE_MBRF(2,CARTESIAN,Elem*,Base::build_elem(const Elem*));
INSTANTIATE_INF_FE_MBRF(3,CARTESIAN,Elem*,Base::build_elem(const Elem*));
INSTANTIATE_INF_FE_MBRF(1,CARTESIAN,ElemType,Base::get_elem_type(const ElemType type));
INSTANTIATE_INF_FE_MBRF(2,CARTESIAN,ElemType,Base::get_elem_type(const ElemType type));
INSTANTIATE_INF_FE_MBRF(3,CARTESIAN,ElemType,Base::get_elem_type(const ElemType type));
INSTANTIATE_INF_FE_MBRF(1,CARTESIAN,unsigned int,Base::n_base_mapping_sf(const ElemType,const Order));
INSTANTIATE_INF_FE_MBRF(2,CARTESIAN,unsigned int,Base::n_base_mapping_sf(const ElemType,const Order));
INSTANTIATE_INF_FE_MBRF(3,CARTESIAN,unsigned int,Base::n_base_mapping_sf(const ElemType,const Order));
INSTANTIATE_INF_FE_MBRF(1,CARTESIAN,unsigned int,Radial::n_dofs_at_node (const Order,const unsigned int));
INSTANTIATE_INF_FE_MBRF(2,CARTESIAN,unsigned int,Radial::n_dofs_at_node (const Order,const unsigned int));
INSTANTIATE_INF_FE_MBRF(3,CARTESIAN,unsigned int,Radial::n_dofs_at_node (const Order,const unsigned int));
} // namespace libMesh
#endif //ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
| lgpl-2.1 |
guigarage/LessFX | src/test/java/com/guigarage/lessfx/converters/MathematicsTest.java | 632 | package com.guigarage.lessfx.converters;
import org.junit.Test;
/**
* @author Robin Küster
* @since 2015-02-18
*/
public abstract class MathematicsTest {
@Test
public abstract void testInteger();
@Test
public abstract void testDouble();
@Test
public abstract void testNegInteger();
@Test
public abstract void testNegDouble();
@Test
public abstract void testMultipleParameters();
@Test
public abstract void testOneParameter();
@Test
public abstract void testUnits();
@Test
public abstract void testNaN();
@Test
public abstract void testEmpty();
}
| lgpl-2.1 |
kata198/python-nonblock | nonblock/BackgroundRead.py | 6107 | '''
Copyright (c) 2015-2016 Timothy Savannah under terms of LGPLv2. You should have received a copy of this LICENSE with this distribution.
read.py Contains pure-python functions for non-blocking reads in python
'''
# vim: ts=4 sw=4 expandtab
import time
import threading
from .read import nonblock_read
from .common import detect_stream_mode
__all__ = ('BackgroundReadData', 'bgread' )
def bgread(stream, blockSizeLimit=65535, pollTime=.03, closeStream=True):
'''
bgread - Start a thread which will read from the given stream in a non-blocking fashion, and automatically populate data in the returned object.
@param stream <object> - A stream on which to read. Socket, file, etc.
@param blockSizeLimit <None/int> - Number of bytes. Default 65535.
If None, the stream will be read from until there is no more available data (not closed, but you've read all that's been flushed to straem). This is okay for smaller datasets, but this number effectively controls the amount of CPU time spent in I/O on this stream VS everything else in your application. The default of 65535 bytes is a fair amount of data.
@param pollTime <float> - Default .03 (30ms) After all available data has been read from the stream, wait this many seconds before checking again for more data.
A low number here means a high priority, i.e. more cycles will be devoted to checking and collecting the background data. Since this is a non-blocking read, this value is the "block", which will return execution context to the remainder of the application. The default of 100ms should be fine in most cases. If it's really idle data collection, you may want to try a value of 1 second.
@param closeStream <bool> - Default True. If True, the "close" method on the stream object will be called when the other side has closed and all data has been read.
NOTES --
blockSizeLimit / pollTime is your effective max-throughput. Real throughput will be lower than this number, as the actual throughput is be defined by:
T = (blockSizeLimit / pollTime) - DeviceReadTime(blockSizeLimit)
Using the defaults of .03 and 65535 means you'll read up to 2 MB per second. Keep in mind that the more time spent in I/O means less time spent doing other tasks.
@return - The return of this function is a BackgroundReadData object. This object contains an attribute "blocks" which is a list of the non-zero-length blocks that were read from the stream. The object also contains a calculated property, "data", which is a string/bytes (depending on stream mode) of all the data currently read. The property "isFinished" will be set to True when the stream has been closed. The property "error" will be set to any exception that occurs during reading which will terminate the thread. @see BackgroundReadData for more info.
'''
try:
pollTime = float(pollTime)
except ValueError:
raise ValueError('Provided poll time must be a float.')
if not hasattr(stream, 'read') and not hasattr(stream, 'recv'):
raise ValueError('Cannot read off provided stream, does not implement "read" or "recv"')
if blockSizeLimit is not None:
try:
blockSizeLimit = int(blockSizeLimit)
if blockSizeLimit <= 0:
raise ValueError()
except ValueError:
raise ValueError('Provided block size limit must be "None" for no limit, or a positive integer.')
streamMode = detect_stream_mode(stream)
results = BackgroundReadData(streamMode)
thread = threading.Thread(target=_do_bgread, args=(stream, blockSizeLimit, pollTime, closeStream, results))
thread.daemon = True # Automatically terminate this thread if program closes
thread.start()
return results
class BackgroundReadData(object):
'''
BackgroundReadData - An object returned by the bgread function. This object is automatically populated in the background by a thread with data read off the stream.
It contains the following attributes:
blocks - The raw non-zero length blocks read from the stream, in order.
data - A calculated property, which is a bytes/str (depending on stream mode). It is the joining of all the read blocks, and contains all the data read to-date.
isFinished - starts False, and becomes True after all data has been read from the stream. Will remain False if there is an exception raised during I/O
error - starts None, and is set to any exception that is raised during reading (which will also terminate the thread)
'''
def __init__(self, dataType):
self.blocks = []
self.dataType = dataType
self.emptyStr = dataType()
self.isFinished = False
self.error = None
def addBlock(self, block):
self.blocks.append(block)
@property
def data(self):
'''
data - property to get the data as a string or bytes.
Use "blocks" to access the individual blocks of data
@return <str or bytes> - All data currently read, as a string or bytes (depending on the dataType)
'''
return self.emptyStr.join(self.blocks)
def _do_bgread(stream, blockSizeLimit, pollTime, closeStream, results):
'''
_do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData>
'''
# Put the whole function in a try instead of just the read portion for performance reasons.
try:
while True:
nextData = nonblock_read(stream, limit=blockSizeLimit)
if nextData is None:
break
elif nextData:
results.addBlock(nextData)
time.sleep(pollTime)
except Exception as e:
results.error = e
return
if closeStream and hasattr(stream, 'close'):
stream.close()
results.isFinished = True
| lgpl-2.1 |
rspavel/spack | var/spack/repos/builtin/packages/rocgdb/package.py | 1999 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Rocgdb(AutotoolsPackage):
"""This is ROCgdb, the ROCm source-level debugger for Linux,
based on GDB, the GNU source-level debugger."""
homepage = "https://github.com/ROCm-Developer-Tools/ROCgdb/"
url = "https://github.com/ROCm-Developer-Tools/ROCgdb/archive/rocm-3.5.0.tar.gz"
maintainers = ['srekolam', 'arjun-raj-kuppala']
version('3.5.0', sha256='cf36d956e84c7a5711b71f281a44b0a9708e13e941d8fca0247d01567e7ee7d1')
depends_on('cmake@3:', type='build')
depends_on('texinfo', type='build')
depends_on('bison', type='build')
depends_on('flex', type='build')
depends_on('libunwind', type='build')
depends_on('expat', type='build')
depends_on('python', type='build')
depends_on('zlib', type='link')
for ver in ['3.5.0']:
depends_on('rocm-dbgapi@' + ver, type='link', when='@' + ver)
depends_on('comgr@' + ver, type='link', when='@' + ver)
build_directory = 'spack-build'
def configure_args(self):
# Generic options to compile GCC
options = [
# Distributor options
'--program-prefix=roc',
'--enable-64-bit-bfd',
'--with-bugurl=https://github.com/ROCm-Developer-Tools/ROCgdb/issues',
'--with-pkgversion=-ROCm',
'--enable-targets=x86_64-linux-gnu,amdgcn-amd-amdhsa',
'--disable-ld',
'--disable-gas',
'--disable-gdbserver',
'--disable-sim',
'--enable-tui',
'--disable-gdbtk',
'--disable-shared',
'--with-expat',
'--with-system-zlib'
'--without-guile',
'--with-babeltrace',
'--with-lzma',
'--with-python'
]
return options
| lgpl-2.1 |
sgeh/JSTools.net | Branches/JSTools 0.30/JSTools.Parser/JSTools/Parser/Cruncher/HtmlCommentBeginItem.cs | 2019 | /*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
namespace JSTools.Parser.Cruncher
{
/// <summary>
/// Represents a comment line item, which holds strings like "<!--".
/// </summary>
public class HtmlCommentBeginItem : HtmlCommentItem
{
//--------------------------------------------------------------------
// Declarations
//--------------------------------------------------------------------
private const string COMMENT_STRING = "<!--";
public const string ITEM_NAME = "HTML Comment Begin Item";
/// <summary>
/// Returns the name of this parse item.
/// </summary>
public override string ItemName
{
get { return ITEM_NAME; }
}
/// <summary>
/// Returns the comment string (e.g. <!--).
/// </summary>
protected override string CommentString
{
get { return COMMENT_STRING; }
}
//--------------------------------------------------------------------
// Constructors / Destructor
//--------------------------------------------------------------------
/// <summary>
/// Creates a new HtmlCommentBeginItem instance.
/// </summary>
public HtmlCommentBeginItem()
{
}
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}
}
| lgpl-2.1 |
gavin-hu/focusns | focusns-base/focusns-runtime/src/test/java/org/focusns/service/msg/MessageServiceTest.java | 1786 | package org.focusns.service.msg;
/*
* #%L
* FocusSNS Runtime
* %%
* Copyright (C) 2011 - 2013 FocusSNS
* %%
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Date;
import org.focusns.model.common.Page;
import org.focusns.model.msg.Message;
import org.focusns.service.AbstractServiceTest;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@Ignore
public class MessageServiceTest extends AbstractServiceTest {
@Autowired
private MessageService messageService;
@Test
public void testCreateMessage() {
Message message = new Message();
message.setTitle("xinxi");
message.setContent("neirong");
message.setCreatedAt(new Date());
message.setProjectId(1);
message.setCreatedById(1);
message.setToProjectId(1);
//
messageService.createMessage(message);
}
@Test
public void testFetchPage() {
Page<Message> page = new Page(10);
page = messageService.fetchPageByBox(page, "in", 1);
System.out.println(page.getTotalCount());
}
}
| lgpl-2.1 |
bhulliger/CRF | src/demos/crfTest/crfStressTest/src/IlluminatedModel.cpp | 2690 | /*
* Filename: IlluminatedIlluminatedModel.cpp
* Project: crfStressTest
* Author: Stefan Broder ([email protected])
* Creation Date: 05.06.2009
* Purpose: Container class for a model with two rotating lights
*
*/
#include "IlluminatedModel.h"
using namespace osg;
using namespace std;
IlluminatedModel::IlluminatedModel(std::string filename, StateSet *ss) : Model::Model(filename) {
_patLight1 = new PositionAttitudeTransform;
_patLight2 = new PositionAttitudeTransform;
//void createLight(int lightNum, PositionAttitudeTransform *patLight, StateSet *ss, Vec3d position,
// Vec3d ambient, Vec3d diffuse, Vec3d specular) {
createLight(0, _patLight1.get(), ss, Vec3d(0.0,-2.5,3.0),
Vec3d(0.0,0.0,0.0), Vec3d(0.2,0.8,0.1), Vec3d(0.2,0.8,0.1));
createLight(1, _patLight2.get(), ss, Vec3d(0.0,2.5,0.0),
Vec3d(0.0,0.0,0.0), Vec3d(0.7,0.1,0.1), Vec3d(0.7,0.1,0.1));
isIlluminated = false;
}
IlluminatedModel::IlluminatedModel(Node* model, StateSet *ss) : Model::Model(model) {
}
IlluminatedModel::~IlluminatedModel() {
}
void IlluminatedModel::toggleLights() {
if(isIlluminated) {
_group->removeChild(_patLight1.get());
_group->removeChild(_patLight2.get());
} else {
_group->addChild(_patLight1.get());
_group->addChild(_patLight2.get());
}
isIlluminated = !isIlluminated;
}
void IlluminatedModel::rotateLights() {
Quat rotate1( DegreesToRadians(0.5), Vec3d(1.0, 1.0, 0.0) );
Quat rotate2( DegreesToRadians(0.3), Vec3d(0.0, 1.0, 1.0) );
_patLight1->setAttitude(_patLight1->getAttitude() * rotate1);
_patLight2->setAttitude(_patLight2->getAttitude() * rotate2);
}
void IlluminatedModel::createLight(int lightNum, PositionAttitudeTransform *patLight, StateSet *ss, Vec3d position,
Vec3d ambient, Vec3d diffuse, Vec3d specular) {
ref_ptr<Group> lightGroup = new Group;
ref_ptr<StateSet> lightSS (ss);
ref_ptr<LightSource> lightSource = new LightSource;
ref_ptr<Light> light = new Light;
Vec4d lightPosition (Vec4d(position,1.0));
light->setLightNum(lightNum);
light->setPosition(lightPosition);
light->setAmbient(Vec4(ambient,1.0));
light->setDiffuse(Vec4(diffuse,1.0));
light->setSpecular(Vec4(specular,1.0));
light->setConstantAttenuation(1.0);
// light->setSpotCutoff(80.0);
lightSource->setLight(light.get());
lightSource->setLocalStateSetModes(StateAttribute::ON);
lightSource->setStateSetModes(*lightSS,StateAttribute::ON);
ref_ptr<Geode> lightMarkerGeode (new Geode);
lightMarkerGeode->addDrawable(new ShapeDrawable(new Sphere(position,0.1)));
lightGroup->addChild(lightSource.get());
lightGroup->addChild(lightMarkerGeode.get());
patLight->addChild(lightGroup.get());
}
| lgpl-2.1 |
joevandyk/osg | examples/osgsimplifier/osgsimplifier.cpp | 5334 | /* OpenSceneGraph example, osgsimplifier.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgUtil/Simplifier>
#include <osgViewer/Viewer>
#include <osgGA/TrackballManipulator>
#include <iostream>
class KeyboardEventHandler : public osgGA::GUIEventHandler
{
public:
KeyboardEventHandler(unsigned int& flag) : _flag(flag)
{}
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='n')
{
_flag = 1;
return true;
}
if (ea.getKey()=='p')
{
_flag = 2;
return true;
}
break;
}
default:
break;
}
return false;
}
private:
unsigned int& _flag;
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" examples illustrates simplification of triangle meshes.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--ratio <ratio>","Specify the sample ratio","0.5]");
arguments.getApplicationUsage()->addCommandLineOption("--max-error <error>","Specify the maximum error","4.0");
float sampleRatio = 0.5f;
float maxError = 4.0f;
// construct the viewer.
osgViewer::Viewer viewer;
// read the sample ratio if one is supplied
while (arguments.read("--ratio",sampleRatio)) {}
while (arguments.read("--max-error",maxError)) {}
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
// if not loaded assume no arguments passed in, try use default mode instead.
if (!loadedModel) loadedModel = osgDB::readNodeFile("dumptruck.osg");
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
//loadedModel->accept(simplifier);
unsigned int keyFlag = 0;
viewer.addEventHandler(new KeyboardEventHandler(keyFlag));
// set the scene to render
viewer.setSceneData(loadedModel.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
// create the windows and run the threads.
viewer.realize();
float multiplier = 0.8f;
float minRatio = 0.001f;
float ratio = sampleRatio;
while( !viewer.done() )
{
// fire off the cull and draw traversals of the scene.
viewer.frame();
if (keyFlag == 1 || keyFlag == 2)
{
if (keyFlag == 1) ratio *= multiplier;
if (keyFlag == 2) ratio /= multiplier;
if (ratio<minRatio) ratio=minRatio;
osgUtil::Simplifier simplifier(ratio, maxError);
std::cout<<"Runing osgUtil::Simplifier with SampleRatio="<<ratio<<" maxError="<<maxError<<" ...";
std::cout.flush();
osg::ref_ptr<osg::Node> root = (osg::Node*)loadedModel->clone(osg::CopyOp::DEEP_COPY_ALL);
root->accept(simplifier);
std::cout<<"done"<<std::endl;
viewer.setSceneData(root.get());
keyFlag = 0;
}
}
return 0;
}
| lgpl-2.1 |
lucee/Lucee | core/src/main/java/lucee/print.java | 59 | package lucee;
public final class print extends aprint {
} | lgpl-2.1 |
herculeshssj/imobiliariaweb | src/br/com/hslife/imobiliaria/service/CEPService.java | 2883 | /***
Copyright (c) 2011, 2014 Hércules S. S. José
Este arquivo é parte do programa Imobiliária Web.
Imobiliária Web é um software livre; você pode redistribui-lo e/ou
modificá-lo dentro dos termos da Licença Pública Geral Menor GNU como
publicada pela Fundação do Software Livre (FSF); na versão 2.1 da
Licença.
Este programa é distribuído na esperança que possa ser util,
mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral Menor GNU em
português para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral Menor GNU sob o
nome de "LICENSE.TXT" junto com este programa, se não, acesse o site HSlife no
endereco www.hslife.com.br ou escreva para a Fundação do Software Livre(FSF) Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
Para mais informações sobre o programa Imobiliária Web e seus autores acesso o
endereço www.hslife.com.br, pelo e-mail [email protected] ou escreva para
Hércules S. S. José, Av. Ministro Lafaeyte de Andrade, 1683 - Bl. 3 Apt 404,
Marco II - Nova Iguaçu, RJ, Brasil.
***/
package br.com.hslife.imobiliaria.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import br.com.hslife.imobiliaria.exception.ServiceException;
import br.com.hslife.imobiliaria.model.Endereco;
public class CEPService {
private Connection conn = null;
private ResultSet result = null;
private void getConnection() throws Exception {
// Inicializa a conexão
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://mysql.hslife.com.br:3306/hslife01","hslife01","l0gr4d0vr0s");
}
public Endereco getEndereco(String cep) throws ServiceException {
// Instancia um novo objeto Endereco
Endereco endereco = new Endereco();
// SQL de consulta
String sqlQuery = "select * from enderecos where cep = " + cep + " limit 1";
try {
// Inicialização da conexão
getConnection();
// Executa a consulta
result = conn.createStatement().executeQuery(sqlQuery);
// Carrega os dados no objeto Endereco
while(result.next()) {
endereco.setTipoLogradouro(result.getString("tipoLogradouro"));
endereco.setLogradouro(result.getString("logradouro"));
endereco.setBairro(result.getString("bairro"));
endereco.setCidade(result.getString("cidade"));
endereco.setUf(result.getString("uf"));
endereco.setCep(result.getString("cep"));
}
} catch (Exception e) {
throw new ServiceException(e);
}
return endereco;
}
}
| lgpl-2.1 |
dudochkin-victor/libgogootouch | src/extensions/mashup/appletcommunication/mappletclient.cpp | 2585 | /***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mappletclient.h"
#include <MDebug>
static const int MAX_CONNECTION_ATTEMPTS = 100;
MAppletClient::MAppletClient()
{
}
MAppletClient::~MAppletClient()
{
closeConnection();
}
bool MAppletClient::connectToServer(const QString &serverName)
{
closeConnection();
// Connect to the specified server
socket = new QLocalSocket;
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError)));
socket->connectToServer(serverName);
int attempt = 1;
while (socket->state() != QLocalSocket::ConnectedState) {
if (attempt >= MAX_CONNECTION_ATTEMPTS) break;
#ifndef Q_OS_WIN
usleep(100000);
#else
#include <windows.h>
Sleep(100);
#endif
++attempt;
socket->connectToServer(serverName);
}
if (attempt < MAX_CONNECTION_ATTEMPTS) {
mDebug("MAppletClient") << "Connection took" << attempt << "attempts";
return true;
} else {
mDebug("MAppletClient") << "Couldn't establish connection to server";
return false;
}
}
void MAppletClient::closeConnection()
{
if (socket) {
socket->disconnectFromServer();
delete socket;
socket = NULL;
delete stream;
stream = NULL;
}
}
void MAppletClient::connected()
{
// Don't accept any additional connections
disconnect(socket, SIGNAL(connected()), this, SLOT(connected()));
// Create a stream for the socket data
stream = new QDataStream(socket);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
emit connectionEstablished();
}
void MAppletClient::socketError(QLocalSocket::LocalSocketError error)
{
mDebug("MAppletClient") << Q_FUNC_INFO << error << socket->errorString();
}
| lgpl-2.1 |
shabanovd/exist | test/src/org/exist/xquery/AnnotationsTest.java | 8815 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2004-2012 The eXist Project
* http://exist-db.org
*
* This program 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
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $Id$
*/
package org.exist.xquery;
import org.exist.TestUtils;
import org.exist.xmldb.DatabaseInstanceManager;
import org.exist.xmldb.XmldbURI;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import static org.junit.Assert.*;
import org.junit.Test;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XPathQueryService;
public class AnnotationsTest {
private static Database database;
public AnnotationsTest() {
}
@BeforeClass
public static void setUp() throws XMLDBException, ClassNotFoundException, InstantiationException, IllegalAccessException {
// initialize driver
Class<?> cl = Class.forName("org.exist.xmldb.DatabaseImpl");
database = (Database) cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
Collection root = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, "admin", "");
CollectionManagementService service = (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
Collection testCollection = service.createCollection("test");
assertNotNull(testCollection);
}
/*
* @see TestCase#tearDown()
*/
@AfterClass
public static void tearDown() throws Exception {
// testCollection.removeResource( testCollection .getResource(file_name));
TestUtils.cleanupDB();
DatabaseInstanceManager dim =
(DatabaseInstanceManager) DatabaseManager.getCollection("xmldb:exist:///db", "admin", null).getService("DatabaseInstanceManager", "1.0");
dim.shutdown();
DatabaseManager.deregisterDatabase(database);
database = null;
}
private Collection getTestCollection() throws XMLDBException {
return DatabaseManager.getCollection("xmldb:exist:///db/test", "admin", null);
}
@Test
public void annotation() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://world.com';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
final ResourceSet result = service.query(query);
assertEquals(1, result.getSize());
Resource res = result.getIterator().nextResource();
assertEquals(TEST_VALUE_CONSTANT, res.getContent());
}
@Test
public void annotationWithLiterals() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://world.com';\n"
+ "declare\n"
+ "%hello:world('a=b', 'b=c')\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
final ResourceSet result = service.query(query);
assertEquals(1, result.getSize());
Resource res = result.getIterator().nextResource();
assertEquals(TEST_VALUE_CONSTANT, res.getContent());
}
@Test(expected = XMLDBException.class)
public void annotationInXMLNamespaceFails() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://www.w3.org/XML/1998/namespace';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
service.query(query);
}
@Test(expected = XMLDBException.class)
public void annotationInXMLSchemaNamespaceFails() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://www.w3.org/2001/XMLSchema';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
service.query(query);
}
@Test(expected = XMLDBException.class)
public void annotationInXMLSchemaInstanceNamespaceFails() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://www.w3.org/2001/XMLSchema-instance';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
service.query(query);
}
@Test(expected = XMLDBException.class)
public void annotationInXPathFunctionsNamespaceFails() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://www.w3.org/2005/xpath-functions';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
service.query(query);
}
@Test(expected = XMLDBException.class)
public void annotationInXPathFunctionsMathNamespaceFails() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://www.w3.org/2005/xpath-functions/math';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
service.query(query);
}
@Test(expected = XMLDBException.class)
public void annotationInXQueryOptionsNamespaceFails() throws XMLDBException {
final String TEST_VALUE_CONSTANT = "hello world";
final String query =
"declare namespace hello = 'http://www.w3.org/2011/xquery-options';\n"
+ "declare\n"
+ "%hello:world\n"
+ "function local:hello() {\n"
+ "'" + TEST_VALUE_CONSTANT + "'\n"
+ "};\n"
+ "local:hello()";
final XPathQueryService service = getQueryService();
service.query(query);
}
private XPathQueryService getQueryService() throws XMLDBException {
Collection testCollection = getTestCollection();
XPathQueryService service = (XPathQueryService) testCollection.getService("XPathQueryService", "1.0");
return service;
}
} | lgpl-2.1 |
RPCS3/discord-bot | CompatBot/Database/Migrations/BotDb/20190129194930_AddE3Schedule.cs | 1242 | using Microsoft.EntityFrameworkCore.Migrations;
namespace CompatBot.Database.Migrations
{
public partial class AddE3Schedule : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "e3_schedule",
columns: table => new
{
id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
year = table.Column<int>(nullable: false),
start = table.Column<long>(nullable: false),
end = table.Column<long>(nullable: false),
name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("id", x => x.id);
});
migrationBuilder.CreateIndex(
name: "e3schedule_year",
table: "e3_schedule",
column: "year");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "e3_schedule");
}
}
}
| lgpl-2.1 |
fazz/digidoc4j | src/eu/europa/ec/markt/dss/validation102853/ocsp/SKOnlineOCSPSource.java | 8466 | /* DigiDoc4J library
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*/
package eu.europa.ec.markt.dss.validation102853.ocsp;
import eu.europa.ec.markt.dss.DSSRevocationUtils;
import eu.europa.ec.markt.dss.exception.DSSException;
import eu.europa.ec.markt.dss.exception.DSSNullException;
import eu.europa.ec.markt.dss.validation102853.CertificatePool;
import eu.europa.ec.markt.dss.validation102853.CertificateToken;
import eu.europa.ec.markt.dss.validation102853.OCSPToken;
import eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader;
import eu.europa.ec.markt.dss.validation102853.https.OCSPDataLoader;
import eu.europa.ec.markt.dss.validation102853.loader.DataLoader;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.cert.ocsp.*;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.digidoc4j.Configuration;
import org.digidoc4j.SignatureToken;
import org.digidoc4j.exceptions.ConfigurationException;
import org.digidoc4j.exceptions.DigiDoc4JException;
import org.digidoc4j.signers.PKCS12SignatureToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.List;
/**
* SK OCSP source location.
*/
public abstract class SKOnlineOCSPSource implements OCSPSource {
final Logger logger = LoggerFactory.getLogger(SKOnlineOCSPSource.class);
// TODO: A hack for testing, to be removed later
public static volatile Listener listener = null;
/**
* The data loader used to retrieve the OCSP response.
*/
private DataLoader dataLoader;
private Configuration configuration;
/**
* SK Online OCSP Source constructor
*
* @param configuration configuration to use for this source
*/
public SKOnlineOCSPSource(Configuration configuration) {
this();
this.configuration = configuration;
}
/**
* SK Online OCSP Source constructor
*/
public SKOnlineOCSPSource() {
dataLoader = new OCSPDataLoader();
}
/**
* Returns SK OCSP source location.
*
* @return OCSP source location
*/
public String getAccessLocation() {
logger.debug("");
String location = Configuration.TEST_OCSP_URL;
if (configuration != null)
location = configuration.getOcspSource();
logger.debug("OCSP Access location: " + location);
return location;
}
private byte[] buildOCSPRequest(final X509Certificate signCert, final X509Certificate issuerCert, Extension nonceExtension) throws
DSSException {
try {
final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(signCert, issuerCert);
final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
ocspReqBuilder.addRequest(certId);
ocspReqBuilder.setRequestExtensions(new Extensions(nonceExtension));
if (configuration.hasToBeOCSPRequestSigned()) {
JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA1withRSA");
if (!configuration.isOCSPSigningConfigurationAvailable()) {
throw new ConfigurationException("Configuration needed for OCSP request signing is not complete.");
}
SignatureToken ocspSigner = new PKCS12SignatureToken(configuration.getOCSPAccessCertificateFileName(),
configuration.getOCSPAccessCertificatePassword());
ContentSigner contentSigner = signerBuilder.build(ocspSigner.getPrivateKey());
X509Certificate ocspSignerCert = ocspSigner.getCertificate();
X509CertificateHolder[] chain = {new X509CertificateHolder(ocspSignerCert.getEncoded())};
GeneralName generalName = new GeneralName(new JcaX509CertificateHolder(ocspSignerCert).getSubject());
ocspReqBuilder.setRequestorName(generalName);
return ocspReqBuilder.build(contentSigner, chain).getEncoded();
}
return ocspReqBuilder.build().getEncoded();
} catch (Exception e) {
throw new DSSException(e);
}
}
/**
* sets given string as http header User-Agent
*
* @param userAgent user agent value
*/
public void setUserAgent(String userAgent) {
//((CommonsDataLoader) dataLoader).setUserAgent(userAgent);
}
@Override
public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificatePool certificatePool) {
if(listener != null) {
listener.onGetOCSPToken(certificateToken, certificatePool);
}
if (dataLoader == null) {
throw new DSSNullException(DataLoader.class);
}
try {
final String dssIdAsString = certificateToken.getDSSIdAsString();
if (logger.isTraceEnabled()) {
logger.trace("--> OnlineOCSPSource queried for " + dssIdAsString);
}
final X509Certificate certificate = certificateToken.getCertificate();
// final X509Certificate issuerCertificate = certificateToken.getIssuerToken().getCertificate();
X500Principal issuerX500Principal = certificateToken.getIssuerX500Principal();
List<CertificateToken> issuerTokens = certificatePool.get(issuerX500Principal);
if (issuerTokens == null || issuerTokens.size() == 0)
throw new DSSException("Not possible to find issuer " + issuerX500Principal + " certificate");
final X509Certificate issuerCertificate = issuerTokens.get(0).getCertificate();
final String ocspUri = getAccessLocation();
if (logger.isDebugEnabled()) {
logger.debug("OCSP URI: " + ocspUri);
}
if (ocspUri == null) {
return null;
}
Extension nonceExtension = createNonce();
final byte[] content = buildOCSPRequest(certificate, issuerCertificate, nonceExtension);
final byte[] ocspRespBytes = dataLoader.post(ocspUri, content);
final OCSPResp ocspResp = new OCSPResp(ocspRespBytes);
BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
checkNonce(basicOCSPResp, nonceExtension);
Date bestUpdate = null;
SingleResp bestSingleResp = null;
final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificate, issuerCertificate);
for (final SingleResp singleResp : basicOCSPResp.getResponses()) {
if (DSSRevocationUtils.matches(certId, singleResp)) {
final Date thisUpdate = singleResp.getThisUpdate();
if (bestUpdate == null || thisUpdate.after(bestUpdate)) {
bestSingleResp = singleResp;
bestUpdate = thisUpdate;
}
}
}
if (bestSingleResp != null) {
final OCSPToken ocspToken = new OCSPToken(basicOCSPResp, bestSingleResp, certificatePool);
ocspToken.setSourceURI(ocspUri);
certificateToken.setRevocationToken(ocspToken);
return ocspToken;
}
} catch (NullPointerException e) {
logger.error("OCSP error: Encountered a case when the OCSPResp is initialised with a null OCSP response...", e);
} catch (OCSPException e) {
logger.error("OCSP error: " + e.getMessage(), e);
} catch (IOException e) {
throw new DSSException(e);
}
return null;
}
protected void checkNonce(BasicOCSPResp basicOCSPResp, Extension expectedNonceExtension) {
final Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
final DEROctetString expectedNonce = (DEROctetString) expectedNonceExtension.getExtnValue();
final DEROctetString receivedNonce = (DEROctetString) extension.getExtnValue();
if (!receivedNonce.equals(expectedNonce)) {
throw new DigiDoc4JException("The OCSP request was the victim of replay attack: nonce[sent:" + expectedNonce + "," +
" received:" + receivedNonce);
}
}
abstract Extension createNonce();
public interface Listener {
void onGetOCSPToken(CertificateToken certificateToken, CertificatePool certificatePool);
}
}
| lgpl-2.1 |
johnlee175/john4j | src/com/johnsoft/library/swing/component/mergetable/JohnMergeTableHeaderUI.java | 5878 | package com.johnsoft.library.swing.component.mergetable;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Enumeration;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import com.johnsoft.library.swing.component.mergetable.JohnCellMergeData.HeaderMergeInfo;
import com.sun.java.swing.plaf.windows.WindowsTableHeaderUI;
/**
* 可合并单元格的表头UI
* @author 李哲浩
*/
public class JohnMergeTableHeaderUI extends WindowsTableHeaderUI
{
@Override
public void paint(Graphics g, JComponent c)
{
if (header.getColumnModel().getColumnCount() <= 0)
{
return;
}
boolean ltr = header.getComponentOrientation().isLeftToRight();
Rectangle clip = g.getClipBounds();
Point left = clip.getLocation();
Point right = new Point(clip.x + clip.width - 1, clip.y);
TableColumnModel cm = header.getColumnModel();
int cMin = header.columnAtPoint(ltr ? left : right);
int cMax = header.columnAtPoint(ltr ? right : left);
if (cMin == -1)
{
cMin = 0;
}
if (cMax == -1)
{
cMax = cm.getColumnCount() - 1;
}
int columnWidth;
TableColumn aColumn;
JohnMergeTableHeader gHeader = (JohnMergeTableHeader) header;
JohnCellMergeData data = gHeader.getCellMergeData();
for (int row = 0, rowCount = data.getRowCount(); row < rowCount; row++)
{
Rectangle cellRect = gHeader.getHeaderRect(row, ltr ? cMin : cMax);
if (ltr)
{
for (int column = cMin; column <= cMax; column++)
{
HeaderMergeInfo info = data.getHeaderMergeInfo(row, column);
cellRect.width = 0;
for (int from = info.cell.col, to = from + info.span.col
- 1; from <= to; from++)
{
aColumn = cm.getColumn(from);
columnWidth = aColumn.getWidth();
cellRect.width += columnWidth;
}
cellRect.y = gHeader.getYOfHeaderMergeInfo(info);
cellRect.height = gHeader.getHeightOfHeaderMergeInfo(info);
aColumn = cm.getColumn(column);
paintCell(g, cellRect, row, column);
cellRect.x += cellRect.width;
column += info.span.col - 1;
}
} else
{
for (int column = cMax; column >= cMin; column--)
{
HeaderMergeInfo info = data.getHeaderMergeInfo(row, column);
cellRect.width = 0;
for (int from = info.cell.col, to = from + info.span.col
- 1; from <= to; from++)
{
aColumn = cm.getColumn(from);
columnWidth = aColumn.getWidth();
cellRect.width += columnWidth;
}
aColumn = cm.getColumn(column);
paintCell(g, cellRect, row, column);
cellRect.x += cellRect.width;
column -= info.span.col - 1;
}
}
}
rendererPane.removeAll();
}
private void paintCell(Graphics g, Rectangle cellRect, int rowIndex,
int columnIndex)
{
Component component = getHeaderRenderer(rowIndex, columnIndex);
if (component instanceof JLabel)
{
((JLabel) component).setHorizontalAlignment(JLabel.CENTER);
}
rendererPane.paintComponent(g, component, header, cellRect.x,
cellRect.y, cellRect.width, cellRect.height, true);
}
private Component getHeaderRenderer(int rowIndex, int columnIndex)
{
JohnMergeTableHeader gHeader = (JohnMergeTableHeader) header;
JohnCellMergeData data = gHeader.getCellMergeData();
HeaderMergeInfo info = data.getHeaderMergeInfo(rowIndex, columnIndex);
TableCellRenderer renderer = header.getDefaultRenderer();
return renderer.getTableCellRendererComponent(header.getTable(),
info.value, false, false, -1, columnIndex);
}
private int getHeaderHeight()
{
int height = 0;
int tempHeight = 0;
JohnMergeTableHeader gHeader = (JohnMergeTableHeader) header;
JohnCellMergeData data = gHeader.getCellMergeData();
TableColumnModel cm = header.getColumnModel();
for (int column = 0, columnCount = cm.getColumnCount(); column < columnCount; column++)
{
tempHeight = 0;
List<HeaderMergeInfo> list = data
.getHeaderMergeInfoAtColumn(column);
for (HeaderMergeInfo info : list)
{
TableCellRenderer renderer = gHeader.getDefaultRenderer();
Component comp = renderer
.getTableCellRendererComponent(header.getTable(),
info.value, false, false, -1, column);
int rendererHeight = comp.getPreferredSize().height;
tempHeight += rendererHeight;
}
height = Math.max(height, tempHeight);
}
return height;
}
private Dimension createHeaderSize(long width)
{
// TableColumnModel columnModel = header.getColumnModel();
// None of the callers include the intercell spacing, do it here.
if (width > Integer.MAX_VALUE)
{
width = Integer.MAX_VALUE;
}
return new Dimension((int) width, getHeaderHeight());
}
public Dimension getMinimumSize(JComponent c)
{
long width = 0;
Enumeration<TableColumn> enumeration = header.getColumnModel()
.getColumns();
while (enumeration.hasMoreElements())
{
TableColumn aColumn = (TableColumn) enumeration.nextElement();
width = width + aColumn.getMinWidth();
}
return createHeaderSize(width);
}
public Dimension getPreferredSize(JComponent c)
{
long width = 0;
Enumeration<TableColumn> enumeration = header.getColumnModel()
.getColumns();
while (enumeration.hasMoreElements())
{
TableColumn aColumn = (TableColumn) enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createHeaderSize(width);
}
public Dimension getMaximumSize(JComponent c)
{
long width = 0;
Enumeration<TableColumn> enumeration = header.getColumnModel()
.getColumns();
while (enumeration.hasMoreElements())
{
TableColumn aColumn = (TableColumn) enumeration.nextElement();
width = width + aColumn.getMaxWidth();
}
return createHeaderSize(width);
}
}
| lgpl-2.1 |
CodeDJ/qt5-hidpi | qt/qtbase/tests/auto/gui/image/qimage/tst_qimage.cpp | 84936 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qimage.h>
#include <qimagereader.h>
#include <qlist.h>
#include <qmatrix.h>
#include <stdio.h>
#include <qpainter.h>
#include <private/qdrawhelper_p.h>
Q_DECLARE_METATYPE(QImage::Format)
Q_DECLARE_METATYPE(Qt::GlobalColor)
class tst_QImage : public QObject
{
Q_OBJECT
public:
tst_QImage();
private slots:
void swap();
void create();
void createInvalidXPM();
void createFromUChar();
void formatHandlersInput_data();
void formatHandlersInput();
void setAlphaChannel_data();
void setAlphaChannel();
void alphaChannel();
void convertToFormat_data();
void convertToFormat();
void convertToFormatRgb888ToRGB32();
void createAlphaMask_data();
void createAlphaMask();
#ifndef QT_NO_IMAGE_HEURISTIC_MASK
void createHeuristicMask();
#endif
void dotsPerMeterZero();
void dotsPerMeterAndDpi();
void convertToFormatPreserveDotsPrMeter();
void convertToFormatPreserveText();
void rotate_data();
void rotate();
void copy();
void load();
void loadFromData();
#if !defined(QT_NO_DATASTREAM)
void loadFromDataStream();
#endif
void setPixel_data();
void setPixel();
void setColorCount();
void setColor();
void rasterClipping();
void pointOverloads();
void destructor();
void cacheKey();
void smoothScale();
void smoothScale2();
void smoothScale3();
void smoothScaleBig();
void smoothScaleAlpha();
void transformed_data();
void transformed();
void transformed2();
void scaled();
void paintEngine();
void setAlphaChannelWhilePainting();
void smoothScaledSubImage();
void nullSize_data();
void nullSize();
void premultipliedAlphaConsistency();
void compareIndexed();
void fillColor_data();
void fillColor();
void fillColorWithAlpha();
void fillRGB888();
void rgbSwapped_data();
void rgbSwapped();
void deepCopyWhenPaintingActive();
void scaled_QTBUG19157();
void cleanupFunctions();
};
tst_QImage::tst_QImage()
{
}
void tst_QImage::swap()
{
QImage i1( 16, 16, QImage::Format_RGB32 ), i2( 32, 32, QImage::Format_RGB32 );
i1.fill( Qt::white );
i2.fill( Qt::black );
const qint64 i1k = i1.cacheKey();
const qint64 i2k = i2.cacheKey();
i1.swap(i2);
QCOMPARE(i1.cacheKey(), i2k);
QCOMPARE(i1.size(), QSize(32,32));
QCOMPARE(i2.cacheKey(), i1k);
QCOMPARE(i2.size(), QSize(16,16));
}
// Test if QImage (or any functions called from QImage) throws an
// exception when creating an extremely large image.
// QImage::create() should return "false" in this case.
void tst_QImage::create()
{
bool cr = true;
#if !defined(Q_OS_WINCE)
QT_TRY {
#endif
//QImage image(7000000, 7000000, 8, 256, QImage::IgnoreEndian);
QImage image(7000000, 7000000, QImage::Format_Indexed8);
image.setColorCount(256);
cr = !image.isNull();
#if !defined(Q_OS_WINCE)
} QT_CATCH (...) {
}
#endif
QVERIFY( !cr );
}
void tst_QImage::createInvalidXPM()
{
QTest::ignoreMessage(QtWarningMsg, "QImage::QImage(), XPM is not supported");
const char *xpm[] = {""};
QImage invalidXPM(xpm);
QVERIFY(invalidXPM.isNull());
}
void tst_QImage::createFromUChar()
{
uchar data[] = {
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
0xFF,
#endif
1,1,1, 0xFF, 2,2,2, 0xFF, 3,3,3, 0xFF, 4,4,4,
#if Q_BYTE_ORDER != Q_BIG_ENDIAN
0xFF,
#endif
};
// When the data is const, nothing you do to the image will change the source data.
QImage i1((const uchar*)data, 2, 2, 8, QImage::Format_RGB32);
QCOMPARE(i1.pixel(0,0), 0xFF010101U);
QCOMPARE(i1.pixel(1,0), 0xFF020202U);
QCOMPARE(i1.pixel(0,1), 0xFF030303U);
QCOMPARE(i1.pixel(1,1), 0xFF040404U);
{
QImage i(i1);
i.setPixel(0,0,5);
}
QCOMPARE(i1.pixel(0,0), 0xFF010101U);
QCOMPARE(*(QRgb*)data, 0xFF010101U);
*((QRgb*)i1.bits()) = 7U;
QCOMPARE(i1.pixel(0,0), 7U);
QCOMPARE(*(QRgb*)data, 0xFF010101U);
// Changing copies should not change the original image or data.
{
QImage i(i1);
i.setPixel(0,0,5);
QCOMPARE(*(QRgb*)data, 0xFF010101U);
i1.setPixel(0,0,9);
QCOMPARE(i1.pixel(0,0), 0xFF000009U);
QCOMPARE(i.pixel(0,0), 0xFF000005U);
}
QCOMPARE(i1.pixel(0,0), 0xFF000009U);
// When the data is non-const, nothing you do to copies of the image will change the source data,
// but changing the image (here via bits()) will change the source data.
QImage i2((uchar*)data, 2, 2, 8, QImage::Format_RGB32);
QCOMPARE(i2.pixel(0,0), 0xFF010101U);
QCOMPARE(i2.pixel(1,0), 0xFF020202U);
QCOMPARE(i2.pixel(0,1), 0xFF030303U);
QCOMPARE(i2.pixel(1,1), 0xFF040404U);
{
QImage i(i2);
i.setPixel(0,0,5);
}
QCOMPARE(i2.pixel(0,0), 0xFF010101U);
QCOMPARE(*(QRgb*)data, 0xFF010101U);
*((QRgb*)i2.bits()) = 7U;
QCOMPARE(i2.pixel(0,0), 7U);
QCOMPARE(*(QRgb*)data, 7U);
// Changing the data will change the image in either case.
QImage i3((uchar*)data, 2, 2, 8, QImage::Format_RGB32);
QImage i4((const uchar*)data, 2, 2, 8, QImage::Format_RGB32);
*(QRgb*)data = 6U;
QCOMPARE(i3.pixel(0,0), 6U);
QCOMPARE(i4.pixel(0,0), 6U);
}
void tst_QImage::formatHandlersInput_data()
{
QTest::addColumn<QString>("testFormat");
QTest::addColumn<QString>("testFile");
const QString prefix = QFINDTESTDATA("images/");
if (prefix.isEmpty())
QFAIL("can not find images directory!");
// add a new line here when a file is added
QTest::newRow("ICO") << "ICO" << prefix + "image.ico";
QTest::newRow("PNG") << "PNG" << prefix + "image.png";
QTest::newRow("GIF") << "GIF" << prefix + "image.gif";
QTest::newRow("BMP") << "BMP" << prefix + "image.bmp";
QTest::newRow("JPEG") << "JPEG" << prefix + "image.jpg";
QTest::newRow("PBM") << "PBM" << prefix + "image.pbm";
QTest::newRow("PGM") << "PGM" << prefix + "image.pgm";
QTest::newRow("PPM") << "PPM" << prefix + "image.ppm";
QTest::newRow("XBM") << "XBM" << prefix + "image.xbm";
QTest::newRow("XPM") << "XPM" << prefix + "image.xpm";
}
void tst_QImage::formatHandlersInput()
{
QFETCH(QString, testFormat);
QFETCH(QString, testFile);
QList<QByteArray> formats = QImageReader::supportedImageFormats();
// qDebug("Image input formats : %s", formats.join(" | ").latin1());
bool formatSupported = false;
for (QList<QByteArray>::Iterator it = formats.begin(); it != formats.end(); ++it) {
if (*it == testFormat.toLower()) {
formatSupported = true;
break;
}
}
if (formatSupported) {
// qDebug(QImage::imageFormat(testFile));
QCOMPARE(testFormat.toLatin1().toLower(), QImageReader::imageFormat(testFile));
} else {
QString msg = "Format not supported : ";
QSKIP(QString(msg + testFormat).toLatin1());
}
}
void tst_QImage::setAlphaChannel_data()
{
QTest::addColumn<int>("red");
QTest::addColumn<int>("green");
QTest::addColumn<int>("blue");
QTest::addColumn<int>("alpha");
QTest::addColumn<bool>("gray");
QTest::newRow("red at 0%, gray") << 255 << 0 << 0 << 0 << true;
QTest::newRow("red at 25%, gray") << 255 << 0 << 0 << 63 << true;
QTest::newRow("red at 50%, gray") << 255 << 0 << 0 << 127 << true;
QTest::newRow("red at 100%, gray") << 255 << 0 << 0 << 191 << true;
QTest::newRow("red at 0%, 32bit") << 255 << 0 << 0 << 0 << false;
QTest::newRow("red at 25%, 32bit") << 255 << 0 << 0 << 63 << false;
QTest::newRow("red at 50%, 32bit") << 255 << 0 << 0 << 127 << false;
QTest::newRow("red at 100%, 32bit") << 255 << 0 << 0 << 191 << false;
QTest::newRow("green at 0%, gray") << 0 << 255 << 0 << 0 << true;
QTest::newRow("green at 25%, gray") << 0 << 255 << 0 << 63 << true;
QTest::newRow("green at 50%, gray") << 0 << 255 << 0 << 127 << true;
QTest::newRow("green at 100%, gray") << 0 << 255 << 0 << 191 << true;
QTest::newRow("green at 0%, 32bit") << 0 << 255 << 0 << 0 << false;
QTest::newRow("green at 25%, 32bit") << 0 << 255 << 0 << 63 << false;
QTest::newRow("green at 50%, 32bit") << 0 << 255 << 0 << 127 << false;
QTest::newRow("green at 100%, 32bit") << 0 << 255 << 0 << 191 << false;
QTest::newRow("blue at 0%, gray") << 0 << 0 << 255 << 0 << true;
QTest::newRow("blue at 25%, gray") << 0 << 0 << 255 << 63 << true;
QTest::newRow("blue at 50%, gray") << 0 << 0 << 255 << 127 << true;
QTest::newRow("blue at 100%, gray") << 0 << 0 << 255 << 191 << true;
QTest::newRow("blue at 0%, 32bit") << 0 << 0 << 255 << 0 << false;
QTest::newRow("blue at 25%, 32bit") << 0 << 0 << 255 << 63 << false;
QTest::newRow("blue at 50%, 32bit") << 0 << 0 << 255 << 127 << false;
QTest::newRow("blue at 100%, 32bit") << 0 << 0 << 255 << 191 << false;
}
void tst_QImage::setAlphaChannel()
{
QFETCH(int, red);
QFETCH(int, green);
QFETCH(int, blue);
QFETCH(int, alpha);
QFETCH(bool, gray);
int width = 100;
int height = 100;
QImage image(width, height, QImage::Format_RGB32);
image.fill(qRgb(red, green, blue));
// Create the alpha channel
QImage alphaChannel;
if (gray) {
alphaChannel = QImage(width, height, QImage::Format_Indexed8);
alphaChannel.setColorCount(256);
for (int i=0; i<256; ++i)
alphaChannel.setColor(i, qRgb(i, i, i));
alphaChannel.fill(alpha);
} else {
alphaChannel = QImage(width, height, QImage::Format_ARGB32);
alphaChannel.fill(qRgb(alpha, alpha, alpha));
}
image.setAlphaChannel(alphaChannel);
image = image.convertToFormat(QImage::Format_ARGB32);
QVERIFY(image.format() == QImage::Format_ARGB32);
// alpha of 0 becomes black at a=0 due to premultiplication
QRgb pixel = alpha == 0 ? 0 : qRgba(red, green, blue, alpha);
bool allPixelsOK = true;
for (int y=0; y<height; ++y) {
for (int x=0; x<width; ++x) {
allPixelsOK &= image.pixel(x, y) == pixel;
}
}
QVERIFY(allPixelsOK);
QImage outAlpha = image.alphaChannel();
QCOMPARE(outAlpha.size(), image.size());
bool allAlphaOk = true;
for (int y=0; y<height; ++y) {
for (int x=0; x<width; ++x) {
allAlphaOk &= outAlpha.pixelIndex(x, y) == alpha;
}
}
QVERIFY(allAlphaOk);
}
void tst_QImage::alphaChannel()
{
QImage img(10, 10, QImage::Format_Mono);
img.setColor(0, Qt::transparent);
img.setColor(1, Qt::black);
img.fill(0);
QPainter p(&img);
p.fillRect(2, 2, 6, 6, Qt::black);
p.end();
QCOMPARE(img.alphaChannel(), img.convertToFormat(QImage::Format_ARGB32).alphaChannel());
}
void tst_QImage::convertToFormat_data()
{
QTest::addColumn<int>("inFormat");
QTest::addColumn<uint>("inPixel");
QTest::addColumn<int>("resFormat");
QTest::addColumn<uint>("resPixel");
QTest::newRow("red rgb32 -> argb32") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green rgb32 -> argb32") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue rgb32 -> argb32") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("red rgb32 -> rgb16") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_RGB16) << 0xffff0000;
QTest::newRow("green rgb32 -> rgb16") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_RGB16) << 0xff00ff00;
QTest::newRow("blue rgb32 -> rgb16") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_RGB16) << 0xff0000ff;
QTest::newRow("funky rgb32 -> rgb16") << int(QImage::Format_RGB32) << 0xfff0c080
<< int(QImage::Format_RGB16) << 0xfff7c384;
QTest::newRow("red rgb32 -> argb32_pm") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_ARGB32_Premultiplied) << 0xffff0000;
QTest::newRow("green rgb32 -> argb32_pm") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_ARGB32_Premultiplied) <<0xff00ff00;
QTest::newRow("blue rgb32 -> argb32_pm") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_ARGB32_Premultiplied) << 0xff0000ff;
QTest::newRow("semired argb32 -> pm") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u;
QTest::newRow("semigreen argb32 -> pm") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u;
QTest::newRow("semiblue argb32 -> pm") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu;
QTest::newRow("semiwhite argb32 -> pm") << int(QImage::Format_ARGB32) << 0x7fffffffu
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu;
QTest::newRow("semiblack argb32 -> pm") << int(QImage::Format_ARGB32) << 0x7f000000u
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u;
QTest::newRow("semired pm -> argb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_ARGB32) << 0x7fff0000u;
QTest::newRow("semigreen pm -> argb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_ARGB32) << 0x7f00ff00u;
QTest::newRow("semiblue pm -> argb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_ARGB32) << 0x7f0000ffu;
QTest::newRow("semiwhite pm -> argb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_ARGB32) << 0x7fffffffu;
QTest::newRow("semiblack pm -> argb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_ARGB32) << 0x7f000000u;
QTest::newRow("semired pm -> rgb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_RGB32) << 0xffff0000u;
QTest::newRow("semigreen pm -> rgb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_RGB32) << 0xff00ff00u;
QTest::newRow("semiblue pm -> rgb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_RGB32) << 0xff0000ffu;
QTest::newRow("semiwhite pm -> rgb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_RGB32) << 0xffffffffu;
QTest::newRow("semiblack pm -> rgb32") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_RGB32) << 0xff000000u;
QTest::newRow("semired argb32 -> rgb32") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_RGB32) << 0xffff0000u;
QTest::newRow("semigreen argb32 -> rgb32") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_RGB32) << 0xff00ff00u;
QTest::newRow("semiblue argb32 -> rgb32") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_RGB32) << 0xff0000ffu;
QTest::newRow("semiwhite argb -> rgb32") << int(QImage::Format_ARGB32) << 0x7fffffffu
<< int(QImage::Format_RGB32) << 0xffffffffu;
QTest::newRow("semiblack argb -> rgb32") << int(QImage::Format_ARGB32) << 0x7f000000u
<< int(QImage::Format_RGB32) << 0xff000000u;
QTest::newRow("black mono -> rgb32") << int(QImage::Format_Mono) << 0x00000000u
<< int(QImage::Format_RGB32) << 0xff000000u;
QTest::newRow("white mono -> rgb32") << int(QImage::Format_Mono) << 0x00000001u
<< int(QImage::Format_RGB32) << 0xffffffffu;
QTest::newRow("red rgb16 -> argb32") << int(QImage::Format_RGB16) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green rgb16 -> argb32") << int(QImage::Format_RGB16) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue rgb16 -> argb32") << int(QImage::Format_RGB16) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("red rgb16 -> rgb16") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_RGB16) << 0xffff0000;
QTest::newRow("green rgb16 -> rgb16") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_RGB16) << 0xff00ff00;
QTest::newRow("blue rgb16 -> rgb16") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_RGB16) << 0xff0000ff;
QTest::newRow("semired argb32 -> rgb16") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_RGB16) << 0xffff0000;
QTest::newRow("semigreen argb32 -> rgb16") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_RGB16) << 0xff00ff00;
QTest::newRow("semiblue argb32 -> rgb16") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_RGB16) << 0xff0000ff;
QTest::newRow("semired pm -> rgb16") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_RGB16) << 0xffff0000u;
QTest::newRow("semigreen pm -> rgb16") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_RGB16) << 0xff00ff00u;
QTest::newRow("semiblue pm -> rgb16") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_RGB16) << 0xff0000ffu;
QTest::newRow("semiwhite pm -> rgb16") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_RGB16) << 0xffffffffu;
QTest::newRow("semiblack pm -> rgb16") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_RGB16) << 0xff000000u;
QTest::newRow("mono -> mono lsb") << int(QImage::Format_Mono) << 1u
<< int(QImage::Format_MonoLSB) << 0xffffffffu;
QTest::newRow("mono lsb -> mono") << int(QImage::Format_MonoLSB) << 1u
<< int(QImage::Format_Mono) << 0xffffffffu;
QTest::newRow("red rgb32 -> rgb666") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_RGB666) << 0xffff0000;
QTest::newRow("green rgb32 -> rgb666") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_RGB666) << 0xff00ff00;
QTest::newRow("blue rgb32 -> rgb666") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_RGB666) << 0xff0000ff;
QTest::newRow("red rgb16 -> rgb666") << int(QImage::Format_RGB16) << 0xffff0000
<< int(QImage::Format_RGB666) << 0xffff0000;
QTest::newRow("green rgb16 -> rgb666") << int(QImage::Format_RGB16) << 0xff00ff00
<< int(QImage::Format_RGB666) << 0xff00ff00;
QTest::newRow("blue rgb16 -> rgb666") << int(QImage::Format_RGB16) << 0xff0000ff
<< int(QImage::Format_RGB666) << 0xff0000ff;
QTest::newRow("red rgb32 -> rgb15") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_RGB555) << 0xffff0000;
QTest::newRow("green rgb32 -> rgb15") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_RGB555) << 0xff00ff00;
QTest::newRow("blue rgb32 -> rgb15") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_RGB555) << 0xff0000ff;
QTest::newRow("funky rgb32 -> rgb15") << int(QImage::Format_RGB32) << 0xfff0c080
<< int(QImage::Format_RGB555) << 0xfff7c684;
QTest::newRow("red rgb16 -> rgb15") << int(QImage::Format_RGB16) << 0xffff0000
<< int(QImage::Format_RGB555) << 0xffff0000;
QTest::newRow("green rgb16 -> rgb15") << int(QImage::Format_RGB16) << 0xff00ff00
<< int(QImage::Format_RGB555) << 0xff00ff00;
QTest::newRow("blue rgb16 -> rgb15") << int(QImage::Format_RGB16) << 0xff0000ff
<< int(QImage::Format_RGB555) << 0xff0000ff;
QTest::newRow("funky rgb16 -> rgb15") << int(QImage::Format_RGB16) << 0xfff0c080
<< int(QImage::Format_RGB555) << 0xfff7c684;
QTest::newRow("red rgb32 -> argb8565") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_ARGB8565_Premultiplied) << 0xffff0000;
QTest::newRow("green rgb32 -> argb8565") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_ARGB8565_Premultiplied) << 0xff00ff00;
QTest::newRow("blue rgb32 -> argb8565") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_ARGB8565_Premultiplied) << 0xff0000ff;
QTest::newRow("red rgb16 -> argb8565") << int(QImage::Format_RGB16) << 0xffff0000
<< int(QImage::Format_ARGB8565_Premultiplied) << 0xffff0000;
QTest::newRow("green rgb16 -> argb8565") << int(QImage::Format_RGB16) << 0xff00ff00
<< int(QImage::Format_ARGB8565_Premultiplied) << 0xff00ff00;
QTest::newRow("blue rgb16 -> argb8565") << int(QImage::Format_RGB16) << 0xff0000ff
<< int(QImage::Format_ARGB8565_Premultiplied) << 0xff0000ff;
QTest::newRow("red argb8565 -> argb32") << int(QImage::Format_ARGB8565_Premultiplied) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green argb8565 -> argb32") << int(QImage::Format_ARGB8565_Premultiplied) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue argb8565 -> argb32") << int(QImage::Format_ARGB8565_Premultiplied) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("semired argb32 -> argb8565") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f7b0000u;
QTest::newRow("semigreen argb32 -> argb8565") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f007d00u;
QTest::newRow("semiblue argb32 -> argb8565") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f00007bu;
QTest::newRow("semired pm -> argb8565") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f7b0000u;
QTest::newRow("semigreen pm -> argb8565") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f007d00u;
QTest::newRow("semiblue pm -> argb8565") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f00007bu;
QTest::newRow("semiwhite pm -> argb8565") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f7b7d7bu;
QTest::newRow("semiblack pm -> argb8565") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_ARGB8565_Premultiplied) << 0x7f000000u;
QTest::newRow("red rgb666 -> argb32") << int(QImage::Format_RGB666) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green rgb666 -> argb32") << int(QImage::Format_RGB666) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue rgb666 -> argb32") << int(QImage::Format_RGB666) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("semired argb32 -> rgb666") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_RGB666) << 0xffff0000;
QTest::newRow("semigreen argb32 -> rgb666") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_RGB666) << 0xff00ff00;
QTest::newRow("semiblue argb32 -> rgb666") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_RGB666) << 0xff0000ff;
QTest::newRow("semired pm -> rgb666") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_RGB666) << 0xffff0000u;
QTest::newRow("semigreen pm -> rgb666") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_RGB666) << 0xff00ff00u;
QTest::newRow("semiblue pm -> rgb666") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_RGB666) << 0xff0000ffu;
QTest::newRow("semiwhite pm -> rgb666") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_RGB666) << 0xffffffffu;
QTest::newRow("semiblack pm -> rgb666") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_RGB666) << 0xff000000u;
QTest::newRow("red rgb15 -> argb32") << int(QImage::Format_RGB555) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green rgb15 -> argb32") << int(QImage::Format_RGB555) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue rgb15 -> argb32") << int(QImage::Format_RGB555) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("semired argb32 -> rgb15") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_RGB555) << 0xffff0000;
QTest::newRow("semigreen argb32 -> rgb15") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_RGB555) << 0xff00ff00;
QTest::newRow("semiblue argb32 -> rgb15") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_RGB555) << 0xff0000ff;
QTest::newRow("semired pm -> rgb15") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_RGB555) << 0xffff0000u;
QTest::newRow("semigreen pm -> rgb15") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_RGB555) << 0xff00ff00u;
QTest::newRow("semiblue pm -> rgb15") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_RGB555) << 0xff0000ffu;
QTest::newRow("semiwhite pm -> rgb15") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_RGB555) << 0xffffffffu;
QTest::newRow("semiblack pm -> rgb15") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_RGB555) << 0xff000000u;
QTest::newRow("red rgb32 -> argb8555") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_ARGB8555_Premultiplied) << 0xffff0000;
QTest::newRow("green rgb32 -> argb8555") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_ARGB8555_Premultiplied) << 0xff00ff00;
QTest::newRow("blue rgb32 -> argb8555") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_ARGB8555_Premultiplied) << 0xff0000ff;
QTest::newRow("red rgb16 -> argb8555") << int(QImage::Format_RGB16) << 0xffff0000
<< int(QImage::Format_ARGB8555_Premultiplied) << 0xffff0000;
QTest::newRow("green rgb16 -> argb8555") << int(QImage::Format_RGB16) << 0xff00ff00
<< int(QImage::Format_ARGB8555_Premultiplied) << 0xff00ff00;
QTest::newRow("blue rgb16 -> argb8555") << int(QImage::Format_RGB16) << 0xff0000ff
<< int(QImage::Format_ARGB8555_Premultiplied) << 0xff0000ff;
QTest::newRow("red argb8555 -> argb32") << int(QImage::Format_ARGB8555_Premultiplied) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green argb8555 -> argb32") << int(QImage::Format_ARGB8555_Premultiplied) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue argb8555 -> argb32") << int(QImage::Format_ARGB8555_Premultiplied) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("semired argb32 -> argb8555") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f7b0000u;
QTest::newRow("semigreen argb32 -> argb8555") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f007b00u;
QTest::newRow("semiblue argb32 -> argb8555") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f00007bu;
QTest::newRow("semired pm -> argb8555") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f7b0000u;
QTest::newRow("semigreen pm -> argb8555") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f007b00u;
QTest::newRow("semiblue pm -> argb8555") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f00007bu;
QTest::newRow("semiwhite pm -> argb8555") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f7b7b7bu;
QTest::newRow("semiblack pm -> argb8555") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_ARGB8555_Premultiplied) << 0x7f000000u;
QTest::newRow("red rgb32 -> rgb888") << int(QImage::Format_RGB32) << 0xffff0000
<< int(QImage::Format_RGB888) << 0xffff0000;
QTest::newRow("green rgb32 -> rgb888") << int(QImage::Format_RGB32) << 0xff00ff00
<< int(QImage::Format_RGB888) << 0xff00ff00;
QTest::newRow("blue rgb32 -> rgb888") << int(QImage::Format_RGB32) << 0xff0000ff
<< int(QImage::Format_RGB888) << 0xff0000ff;
QTest::newRow("red rgb16 -> rgb888") << int(QImage::Format_RGB16) << 0xffff0000
<< int(QImage::Format_RGB888) << 0xffff0000;
QTest::newRow("green rgb16 -> rgb888") << int(QImage::Format_RGB16) << 0xff00ff00
<< int(QImage::Format_RGB888) << 0xff00ff00;
QTest::newRow("blue rgb16 -> rgb888") << int(QImage::Format_RGB16) << 0xff0000ff
<< int(QImage::Format_RGB888) << 0xff0000ff;
QTest::newRow("red rgb888 -> argb32") << int(QImage::Format_RGB888) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green rgb888 -> argb32") << int(QImage::Format_RGB888) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue rgb888 -> argb32") << int(QImage::Format_RGB888) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("semired argb32 -> rgb888") << int(QImage::Format_ARGB32) << 0x7fff0000u
<< int(QImage::Format_RGB888) << 0xffff0000;
QTest::newRow("semigreen argb32 -> rgb888") << int(QImage::Format_ARGB32) << 0x7f00ff00u
<< int(QImage::Format_RGB888) << 0xff00ff00;
QTest::newRow("semiblue argb32 -> rgb888") << int(QImage::Format_ARGB32) << 0x7f0000ffu
<< int(QImage::Format_RGB888) << 0xff0000ff;
QTest::newRow("semired pm -> rgb888") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u
<< int(QImage::Format_RGB888) << 0xffff0000u;
QTest::newRow("semigreen pm -> rgb888") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u
<< int(QImage::Format_RGB888) << 0xff00ff00u;
QTest::newRow("semiblue pm -> rgb888") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu
<< int(QImage::Format_RGB888) << 0xff0000ffu;
QTest::newRow("semiwhite pm -> rgb888") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu
<< int(QImage::Format_RGB888) << 0xffffffffu;
QTest::newRow("semiblack pm -> rgb888") << int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u
<< int(QImage::Format_RGB888) << 0xff000000u;
QTest::newRow("red rgba8888 -> argb32") << int(QImage::Format_RGBA8888) << 0xffff0000
<< int(QImage::Format_ARGB32) << 0xffff0000;
QTest::newRow("green rgba8888 -> argb32") << int(QImage::Format_RGBA8888) << 0xff00ff00
<< int(QImage::Format_ARGB32) << 0xff00ff00;
QTest::newRow("blue rgba8888 -> argb32") << int(QImage::Format_RGBA8888) << 0xff0000ff
<< int(QImage::Format_ARGB32) << 0xff0000ff;
QTest::newRow("semired rgba8888 -> argb pm") << int(QImage::Format_RGBA8888) << 0x7fff0000u
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f0000u;
QTest::newRow("semigreen rgba8888 -> argb pm") << int(QImage::Format_RGBA8888) << 0x7f00ff00u
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f007f00u;
QTest::newRow("semiblue rgba8888 -> argb pm") << int(QImage::Format_RGBA8888) << 0x7f0000ffu
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f00007fu;
QTest::newRow("semiwhite rgba8888 -> argb pm") << int(QImage::Format_RGBA8888) << 0x7fffffffu
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f7f7f7fu;
QTest::newRow("semiblack rgba8888 -> argb pm") << int(QImage::Format_RGBA8888) << 0x7f000000u
<< int(QImage::Format_ARGB32_Premultiplied) << 0x7f000000u;
}
void tst_QImage::convertToFormat()
{
QFETCH(int, inFormat);
QFETCH(uint, inPixel);
QFETCH(int, resFormat);
QFETCH(uint, resPixel);
QImage src(32, 32, QImage::Format(inFormat));
if (inFormat == QImage::Format_Mono) {
src.setColor(0, qRgba(0,0,0,0xff));
src.setColor(1, qRgba(255,255,255,0xff));
}
for (int y=0; y<src.height(); ++y)
for (int x=0; x<src.width(); ++x)
src.setPixel(x, y, inPixel);
QImage result = src.convertToFormat(QImage::Format(resFormat));
QCOMPARE(src.width(), result.width());
QCOMPARE(src.height(), result.height());
bool same = true;
for (int y=0; y<result.height(); ++y) {
for (int x=0; x<result.width(); ++x) {
QRgb pixel = result.pixel(x, y);
same &= (pixel == resPixel);
if (!same) {
printf("expect=%08x, result=%08x\n", resPixel, pixel);
y = 100000;
break;
}
}
}
QVERIFY(same);
// repeat tests converting from an image with nonstandard stride
int dp = (src.depth() < 8 || result.depth() < 8) ? 8 : 1;
QImage src2(src.bits() + (dp*src.depth())/8,
src.width() - dp*2,
src.height() - 1, src.bytesPerLine(),
src.format());
if (src.depth() < 8)
src2.setColorTable(src.colorTable());
const QImage result2 = src2.convertToFormat(QImage::Format(resFormat));
QCOMPARE(src2.width(), result2.width());
QCOMPARE(src2.height(), result2.height());
QImage expected2(result.bits() + (dp*result.depth())/8,
result.width() - dp*2,
result.height() - 1, result.bytesPerLine(),
result.format());
if (result.depth() < 8)
expected2.setColorTable(result.colorTable());
result2.save("result2.xpm", "XPM");
expected2.save("expected2.xpm", "XPM");
QCOMPARE(result2, expected2);
QFile::remove(QLatin1String("result2.xpm"));
QFile::remove(QLatin1String("expected2.xpm"));
}
void tst_QImage::convertToFormatRgb888ToRGB32()
{
// 545 so width % 4 != 0. This ensure there is padding at the end of the scanlines
const int height = 545;
const int width = 545;
QImage source(width, height, QImage::Format_RGB888);
for (int y = 0; y < height; ++y) {
uchar *srcPixels = source.scanLine(y);
for (int x = 0; x < width * 3; ++x)
srcPixels[x] = x;
}
QImage rgb32Image = source.convertToFormat(QImage::Format_RGB888);
QCOMPARE(rgb32Image.format(), QImage::Format_RGB888);
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y)
QCOMPARE(rgb32Image.pixel(x, y), source.pixel(x, y));
}
}
void tst_QImage::createAlphaMask_data()
{
QTest::addColumn<int>("x");
QTest::addColumn<int>("y");
QTest::addColumn<int>("alpha1");
QTest::addColumn<int>("alpha2");
int alphas[] = { 0, 127, 255 };
for (unsigned a1 = 0; a1 < sizeof(alphas) / sizeof(int); ++a1) {
for (unsigned a2 = 0; a2 < sizeof(alphas) / sizeof(int); ++a2) {
if (a1 == a2)
continue;
for (int x=10; x<18; x+=3) {
for (int y=100; y<108; y+=3) {
QTest::newRow(qPrintable(QString::fromLatin1("x=%1, y=%2, a1=%3, a2=%4").arg(x).arg(y).arg(alphas[a1]).arg(alphas[a2])))
<< x << y << alphas[a1] << alphas[a2];
}
}
}
}
}
void tst_QImage::createAlphaMask()
{
QFETCH(int, x);
QFETCH(int, y);
QFETCH(int, alpha1);
QFETCH(int, alpha2);
QSize size(255, 255);
int pixelsInLines = size.width() + size.height() - 1;
int pixelsOutofLines = size.width() * size.height() - pixelsInLines;
// Generate an white image with two lines, horizontal at y and vertical at x.
// Lines have alpha of alpha2, rest has alpha of alpha1
QImage image(size, QImage::Format_ARGB32);
for (int cy=0; cy<image.height(); ++cy) {
for (int cx=0; cx<image.width(); ++cx) {
int alpha = (y == cy || x == cx) ? alpha2 : alpha1;
image.setPixel(cx, cy, qRgba(255, 255, 255, alpha));
}
}
QImage mask = image.createAlphaMask(Qt::OrderedAlphaDither);
// Sanity check...
QCOMPARE(mask.width(), image.width());
QCOMPARE(mask.height(), image.height());
// Sum up the number of pixels set for both lines and other area
int sumAlpha1 = 0;
int sumAlpha2 = 0;
for (int cy=0; cy<image.height(); ++cy) {
for (int cx=0; cx<image.width(); ++cx) {
int *alpha = (y == cy || x == cx) ? &sumAlpha2 : &sumAlpha1;
*alpha += mask.pixelIndex(cx, cy);
}
}
// Compare the set bits to whats expected for that alpha.
const int threshold = 5;
QVERIFY(qAbs(sumAlpha1 * 255 / pixelsOutofLines - alpha1) < threshold);
QVERIFY(qAbs(sumAlpha2 * 255 / pixelsInLines - alpha2) < threshold);
}
void tst_QImage::dotsPerMeterZero()
{
QImage img(100, 100, QImage::Format_RGB32);
QVERIFY(!img.isNull());
int defaultDpmX = img.dotsPerMeterX();
int defaultDpmY = img.dotsPerMeterY();
QVERIFY(defaultDpmX != 0);
QVERIFY(defaultDpmY != 0);
img.setDotsPerMeterX(0);
img.setDotsPerMeterY(0);
QCOMPARE(img.dotsPerMeterX(), defaultDpmX);
QCOMPARE(img.dotsPerMeterY(), defaultDpmY);
}
// verify that setting dotsPerMeter has an effect on the dpi.
void tst_QImage::dotsPerMeterAndDpi()
{
QImage img(100, 100, QImage::Format_RGB32);
QVERIFY(!img.isNull());
QPoint defaultLogicalDpi(img.logicalDpiX(), img.logicalDpiY());
QPoint defaultPhysicalDpi(img.physicalDpiX(), img.physicalDpiY());
img.setDotsPerMeterX(100); // set x
QCOMPARE(img.logicalDpiY(), defaultLogicalDpi.y()); // no effect on y
QCOMPARE(img.physicalDpiY(), defaultPhysicalDpi.y());
QVERIFY(img.logicalDpiX() != defaultLogicalDpi.x()); // x changed
QVERIFY(img.physicalDpiX() != defaultPhysicalDpi.x());
img.setDotsPerMeterY(200); // set y
QVERIFY(img.logicalDpiY() != defaultLogicalDpi.y()); // y changed
QVERIFY(img.physicalDpiY() != defaultPhysicalDpi.y());
}
void tst_QImage::rotate_data()
{
QTest::addColumn<QImage::Format>("format");
QTest::addColumn<int>("degrees");
QVector<int> degrees;
degrees << 0 << 90 << 180 << 270;
foreach (int d, degrees) {
QString title = QString("%1 %2").arg(d);
QTest::newRow(qPrintable(title.arg("Format_RGB32")))
<< QImage::Format_RGB32 << d;
QTest::newRow(qPrintable(title.arg("Format_ARGB32")))
<< QImage::Format_ARGB32 << d;
QTest::newRow(qPrintable(title.arg("Format_ARGB32_Premultiplied")))
<< QImage::Format_ARGB32_Premultiplied << d;
QTest::newRow(qPrintable(title.arg("Format_RGB16")))
<< QImage::Format_RGB16 << d;
QTest::newRow(qPrintable(title.arg("Format_ARGB8565_Premultiplied")))
<< QImage::Format_ARGB8565_Premultiplied << d;
QTest::newRow(qPrintable(title.arg("Format_RGB666")))
<< QImage::Format_RGB666 << d;
QTest::newRow(qPrintable(title.arg("Format_RGB555")))
<< QImage::Format_RGB555 << d;
QTest::newRow(qPrintable(title.arg("Format_ARGB8555_Premultiplied")))
<< QImage::Format_ARGB8555_Premultiplied << d;
QTest::newRow(qPrintable(title.arg("Format_RGB888")))
<< QImage::Format_RGB888 << d;
QTest::newRow(qPrintable(title.arg("Format_Indexed8")))
<< QImage::Format_Indexed8 << d;
QTest::newRow(qPrintable(title.arg("Format_RGBX8888")))
<< QImage::Format_RGBX8888 << d;
QTest::newRow(qPrintable(title.arg("Format_RGBA8888_Premultiplied")))
<< QImage::Format_RGBA8888_Premultiplied << d;
}
}
void tst_QImage::rotate()
{
QFETCH(QImage::Format, format);
QFETCH(int, degrees);
// test if rotate90 is lossless
int w = 54;
int h = 13;
QImage original(w, h, format);
original.fill(qRgb(255,255,255));
if (format == QImage::Format_Indexed8) {
original.setColorCount(256);
for (int i = 0; i < 255; ++i)
original.setColor(i, qRgb(0, i, i));
}
if (original.colorTable().isEmpty()) {
for (int x = 0; x < w; ++x) {
original.setPixel(x,0, qRgb(x,0,128));
original.setPixel(x,h - 1, qRgb(0,255 - x,128));
}
for (int y = 0; y < h; ++y) {
original.setPixel(0, y, qRgb(y,0,255));
original.setPixel(w - 1, y, qRgb(0,255 - y,255));
}
} else {
const int n = original.colorTable().size();
for (int x = 0; x < w; ++x) {
original.setPixel(x, 0, x % n);
original.setPixel(x, h - 1, n - (x % n) - 1);
}
for (int y = 0; y < h; ++y) {
original.setPixel(0, y, y % n);
original.setPixel(w - 1, y, n - (y % n) - 1);
}
}
// original.save("rotated90_original.png", "png");
// Initialize the matrix manually (do not use rotate) to avoid rounding errors
QMatrix matRotate90;
matRotate90.rotate(degrees);
QImage dest = original;
// And rotate it 4 times, then the image should be identical to the original
for (int i = 0; i < 4 ; ++i) {
dest = dest.transformed(matRotate90);
}
// Make sure they are similar in format before we compare them.
dest = dest.convertToFormat(format);
// dest.save("rotated90_result.png","png");
QCOMPARE(original, dest);
// Test with QMatrix::rotate 90 also, since we trust that now
matRotate90.rotate(degrees);
dest = original;
// And rotate it 4 times, then the image should be identical to the original
for (int i = 0; i < 4 ; ++i) {
dest = dest.transformed(matRotate90);
}
// Make sure they are similar in format before we compare them.
dest = dest.convertToFormat(format);
QCOMPARE(original, dest);
}
void tst_QImage::copy()
{
// Task 99250
{
QImage img(16,16,QImage::Format_ARGB32);
img.copy(QRect(1000,1,1,1));
}
}
void tst_QImage::load()
{
const QString prefix = QFINDTESTDATA("images/");
if (prefix.isEmpty())
QFAIL("can not find images directory!");
const QString filePath = prefix + QLatin1String("image.jpg");
QImage dest(filePath);
QVERIFY(!dest.isNull());
QVERIFY(!dest.load("image_that_does_not_exist.png"));
QVERIFY(dest.isNull());
QVERIFY(dest.load(filePath));
QVERIFY(!dest.isNull());
}
void tst_QImage::loadFromData()
{
const QString prefix = QFINDTESTDATA("images/");
if (prefix.isEmpty())
QFAIL("can not find images directory!");
const QString filePath = prefix + QLatin1String("image.jpg");
QImage original(filePath);
QVERIFY(!original.isNull());
QByteArray ba;
{
QBuffer buf(&ba);
QVERIFY(buf.open(QIODevice::WriteOnly));
QVERIFY(original.save(&buf, "BMP"));
}
QVERIFY(!ba.isEmpty());
QImage dest;
QVERIFY(dest.loadFromData(ba, "BMP"));
QVERIFY(!dest.isNull());
QCOMPARE(original, dest);
QVERIFY(!dest.loadFromData(QByteArray()));
QVERIFY(dest.isNull());
}
#if !defined(QT_NO_DATASTREAM)
void tst_QImage::loadFromDataStream()
{
const QString prefix = QFINDTESTDATA("images/");
if (prefix.isEmpty())
QFAIL("can not find images directory!");
const QString filePath = prefix + QLatin1String("image.jpg");
QImage original(filePath);
QVERIFY(!original.isNull());
QByteArray ba;
{
QDataStream s(&ba, QIODevice::WriteOnly);
s << original;
}
QVERIFY(!ba.isEmpty());
QImage dest;
{
QDataStream s(&ba, QIODevice::ReadOnly);
s >> dest;
}
QVERIFY(!dest.isNull());
QCOMPARE(original, dest);
{
ba.clear();
QDataStream s(&ba, QIODevice::ReadOnly);
s >> dest;
}
QVERIFY(dest.isNull());
}
#endif // QT_NO_DATASTREAM
void tst_QImage::setPixel_data()
{
QTest::addColumn<int>("format");
QTest::addColumn<uint>("value");
QTest::addColumn<uint>("expected");
QTest::newRow("ARGB32 red") << int(QImage::Format_ARGB32)
<< 0xffff0000 << 0xffff0000;
QTest::newRow("ARGB32 green") << int(QImage::Format_ARGB32)
<< 0xff00ff00 << 0xff00ff00;
QTest::newRow("ARGB32 blue") << int(QImage::Format_ARGB32)
<< 0xff0000ff << 0xff0000ff;
QTest::newRow("RGB16 red") << int(QImage::Format_RGB16)
<< 0xffff0000 << 0xf800u;
QTest::newRow("RGB16 green") << int(QImage::Format_RGB16)
<< 0xff00ff00 << 0x07e0u;
QTest::newRow("RGB16 blue") << int(QImage::Format_RGB16)
<< 0xff0000ff << 0x001fu;
QTest::newRow("ARGB8565_Premultiplied red") << int(QImage::Format_ARGB8565_Premultiplied)
<< 0xffff0000 << 0xf800ffu;
QTest::newRow("ARGB8565_Premultiplied green") << int(QImage::Format_ARGB8565_Premultiplied)
<< 0xff00ff00 << 0x07e0ffu;
QTest::newRow("ARGB8565_Premultiplied blue") << int(QImage::Format_ARGB8565_Premultiplied)
<< 0xff0000ff << 0x001fffu;
QTest::newRow("RGB666 red") << int(QImage::Format_RGB666)
<< 0xffff0000 << 0x03f000u;
QTest::newRow("RGB666 green") << int(QImage::Format_RGB666)
<< 0xff00ff00 << 0x000fc0u;
QTest::newRow("RGB666 blue") << int(QImage::Format_RGB666)
<< 0xff0000ff << 0x00003fu;
QTest::newRow("RGB555 red") << int(QImage::Format_RGB555)
<< 0xffff0000 << 0x7c00u;
QTest::newRow("RGB555 green") << int(QImage::Format_RGB555)
<< 0xff00ff00 << 0x03e0u;
QTest::newRow("RGB555 blue") << int(QImage::Format_RGB555)
<< 0xff0000ff << 0x001fu;
QTest::newRow("ARGB8555_Premultiplied red") << int(QImage::Format_ARGB8555_Premultiplied)
<< 0xffff0000 << 0x7c00ffu;
QTest::newRow("ARGB8555_Premultiplied green") << int(QImage::Format_ARGB8555_Premultiplied)
<< 0xff00ff00 << 0x03e0ffu;
QTest::newRow("ARGB8555_Premultiplied blue") << int(QImage::Format_ARGB8555_Premultiplied)
<< 0xff0000ff << 0x001fffu;
QTest::newRow("RGB888 red") << int(QImage::Format_RGB888)
<< 0xffff0000 << 0xff0000u;
QTest::newRow("RGB888 green") << int(QImage::Format_RGB888)
<< 0xff00ff00 << 0x00ff00u;
QTest::newRow("RGB888 blue") << int(QImage::Format_RGB888)
<< 0xff0000ff << 0x0000ffu;
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
QTest::newRow("RGBA8888 red") << int(QImage::Format_RGBA8888)
<< 0xffff0000u << 0xff0000ffu;
QTest::newRow("RGBA8888 green") << int(QImage::Format_RGBA8888)
<< 0xff00ff00u << 0x00ff00ffu;
QTest::newRow("RGBA8888 blue") << int(QImage::Format_RGBA8888)
<< 0xff0000ffu << 0x0000ffffu;
#else
QTest::newRow("RGBA8888 red") << int(QImage::Format_RGBA8888)
<< 0xffff0000u << 0xff0000ffu;
QTest::newRow("RGBA8888 green") << int(QImage::Format_RGBA8888)
<< 0xff00ff00u << 0xff00ff00u;
QTest::newRow("RGBA8888 blue") << int(QImage::Format_RGBA8888)
<< 0xff0000ffu << 0xffff0000u;
#endif
}
void tst_QImage::setPixel()
{
QFETCH(int, format);
QFETCH(uint, value);
QFETCH(uint, expected);
const int w = 13;
const int h = 15;
QImage img(w, h, QImage::Format(format));
// fill image
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
img.setPixel(x, y, value);
// check pixel values
switch (format) {
case int(QImage::Format_RGB32):
case int(QImage::Format_ARGB32):
case int(QImage::Format_ARGB32_Premultiplied):
case int(QImage::Format_RGBX8888):
case int(QImage::Format_RGBA8888):
case int(QImage::Format_RGBA8888_Premultiplied):
{
for (int y = 0; y < h; ++y) {
const quint32 *row = (const quint32*)(img.scanLine(y));
for (int x = 0; x < w; ++x) {
quint32 result = row[x];
if (result != expected)
printf("[x,y]: %d,%d, expected=%08x, result=%08x\n",
x, y, expected, result);
QCOMPARE(uint(result), expected);
}
}
break;
}
case int(QImage::Format_RGB555):
case int(QImage::Format_RGB16):
{
for (int y = 0; y < h; ++y) {
const quint16 *row = (const quint16*)(img.scanLine(y));
for (int x = 0; x < w; ++x) {
quint16 result = row[x];
if (result != expected)
printf("[x,y]: %d,%d, expected=%04x, result=%04x\n",
x, y, expected, result);
QCOMPARE(uint(result), expected);
}
}
break;
}
case int(QImage::Format_RGB666):
case int(QImage::Format_ARGB8565_Premultiplied):
case int(QImage::Format_ARGB8555_Premultiplied):
case int(QImage::Format_RGB888):
{
for (int y = 0; y < h; ++y) {
const quint24 *row = (const quint24*)(img.scanLine(y));
for (int x = 0; x < w; ++x) {
quint32 result = row[x];
if (result != expected)
printf("[x,y]: %d,%d, expected=%04x, result=%04x\n",
x, y, expected, result);
QCOMPARE(result, expected);
}
}
break;
}
default:
qFatal("Test not implemented for format %d", format);
}
}
void tst_QImage::convertToFormatPreserveDotsPrMeter()
{
QImage img(100, 100, QImage::Format_ARGB32_Premultiplied);
int dpmx = 123;
int dpmy = 234;
img.setDotsPerMeterX(dpmx);
img.setDotsPerMeterY(dpmy);
img.fill(0x12345678);
img = img.convertToFormat(QImage::Format_RGB32);
QCOMPARE(img.dotsPerMeterX(), dpmx);
QCOMPARE(img.dotsPerMeterY(), dpmy);
}
void tst_QImage::convertToFormatPreserveText()
{
QImage img(100, 100, QImage::Format_ARGB32_Premultiplied);
img.setText("foo", "bar");
img.setText("foo2", "bar2");
img.fill(0x12345678);
QStringList listResult;
listResult << "foo" << "foo2";
QString result = "foo: bar\n\nfoo2: bar2";
QImage imgResult1 = img.convertToFormat(QImage::Format_RGB32);
QCOMPARE(imgResult1.text(), result);
QCOMPARE(imgResult1.textKeys(), listResult);
QVector<QRgb> colorTable(4);
for (int i = 0; i < 4; ++i)
colorTable[i] = QRgb(42);
QImage imgResult2 = img.convertToFormat(QImage::Format_MonoLSB,
colorTable);
QCOMPARE(imgResult2.text(), result);
QCOMPARE(imgResult2.textKeys(), listResult);
}
void tst_QImage::setColorCount()
{
QImage img(0, 0, QImage::Format_Indexed8);
QTest::ignoreMessage(QtWarningMsg, "QImage::setColorCount: null image");
img.setColorCount(256);
QCOMPARE(img.colorCount(), 0);
}
void tst_QImage::setColor()
{
QImage img(0, 0, QImage::Format_Indexed8);
img.setColor(0, qRgba(18, 219, 108, 128));
QCOMPARE(img.colorCount(), 0);
QImage img2(1, 1, QImage::Format_Indexed8);
img2.setColor(0, qRgba(18, 219, 108, 128));
QCOMPARE(img2.colorCount(), 1);
}
/* Just some sanity checking that we don't draw outside the buffer of
* the image. Hopefully this will create crashes or at least some
* random test fails when broken.
*/
void tst_QImage::rasterClipping()
{
QImage image(10, 10, QImage::Format_RGB32);
image.fill(0xffffffff);
QPainter p(&image);
p.drawLine(-1000, 5, 5, 5);
p.drawLine(-1000, 5, 1000, 5);
p.drawLine(5, 5, 1000, 5);
p.drawLine(5, -1000, 5, 5);
p.drawLine(5, -1000, 5, 1000);
p.drawLine(5, 5, 5, 1000);
p.setBrush(Qt::red);
p.drawEllipse(3, 3, 4, 4);
p.drawEllipse(-100, -100, 210, 210);
p.drawEllipse(-1000, 0, 2010, 2010);
p.drawEllipse(0, -1000, 2010, 2010);
p.drawEllipse(-2010, -1000, 2010, 2010);
p.drawEllipse(-1000, -2010, 2010, 2010);
QVERIFY(true);
}
// Tests the new QPoint overloads in QImage in Qt 4.2
void tst_QImage::pointOverloads()
{
QImage image(100, 100, QImage::Format_RGB32);
image.fill(0xff00ff00);
// IsValid
QVERIFY(image.valid(QPoint(0, 0)));
QVERIFY(image.valid(QPoint(99, 0)));
QVERIFY(image.valid(QPoint(0, 99)));
QVERIFY(image.valid(QPoint(99, 99)));
QVERIFY(!image.valid(QPoint(50, -1))); // outside on the top
QVERIFY(!image.valid(QPoint(50, 100))); // outside on the bottom
QVERIFY(!image.valid(QPoint(-1, 50))); // outside on the left
QVERIFY(!image.valid(QPoint(100, 50))); // outside on the right
// Test the pixel setter
image.setPixel(QPoint(10, 10), 0xff0000ff);
QCOMPARE(image.pixel(10, 10), 0xff0000ff);
// pixel getter
QCOMPARE(image.pixel(QPoint(10, 10)), 0xff0000ff);
// pixelIndex()
QImage indexed = image.convertToFormat(QImage::Format_Indexed8);
QCOMPARE(indexed.pixelIndex(10, 10), indexed.pixelIndex(QPoint(10, 10)));
}
void tst_QImage::destructor()
{
QPolygon poly(6);
poly.setPoint(0,-1455, 1435);
QImage image(100, 100, QImage::Format_RGB32);
QPainter ptPix(&image);
ptPix.setPen(Qt::black);
ptPix.setBrush(Qt::black);
ptPix.drawPolygon(poly, Qt::WindingFill);
ptPix.end();
}
/* XPM */
static const char *monoPixmap[] = {
/* width height ncolors chars_per_pixel */
"4 4 2 1",
"x c #000000",
". c #ffffff",
/* pixels */
"xxxx",
"x..x",
"x..x",
"xxxx"
};
#ifndef QT_NO_IMAGE_HEURISTIC_MASK
void tst_QImage::createHeuristicMask()
{
QImage img(monoPixmap);
img = img.convertToFormat(QImage::Format_MonoLSB);
QImage mask = img.createHeuristicMask();
QImage newMask = mask.convertToFormat(QImage::Format_ARGB32_Premultiplied);
// line 2
QVERIFY(newMask.pixel(0,1) != newMask.pixel(1,1));
QVERIFY(newMask.pixel(1,1) == newMask.pixel(2,1));
QVERIFY(newMask.pixel(2,1) != newMask.pixel(3,1));
// line 3
QVERIFY(newMask.pixel(0,2) != newMask.pixel(1,2));
QVERIFY(newMask.pixel(1,2) == newMask.pixel(2,2));
QVERIFY(newMask.pixel(2,2) != newMask.pixel(3,2));
}
#endif
void tst_QImage::cacheKey()
{
QImage image1(2, 2, QImage::Format_RGB32);
qint64 image1_key = image1.cacheKey();
QImage image2 = image1;
QVERIFY(image2.cacheKey() == image1.cacheKey());
image2.detach();
QVERIFY(image2.cacheKey() != image1.cacheKey());
QVERIFY(image1.cacheKey() == image1_key);
}
void tst_QImage::smoothScale()
{
unsigned int data[2] = { qRgba(0, 0, 0, 0), qRgba(128, 128, 128, 128) };
QImage imgX((unsigned char *)data, 2, 1, QImage::Format_ARGB32_Premultiplied);
QImage imgY((unsigned char *)data, 1, 2, QImage::Format_ARGB32_Premultiplied);
QImage scaledX = imgX.scaled(QSize(4, 1), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QImage scaledY = imgY.scaled(QSize(1, 4), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
uint *scaled[2] = {
(unsigned int *)scaledX.bits(),
(unsigned int *)scaledY.bits()
};
int expected[4] = { 0, 32, 96, 128 };
for (int image = 0; image < 2; ++image) {
for (int index = 0; index < 4; ++index) {
for (int component = 0; component < 4; ++component) {
int pixel = scaled[image][index];
int val = (pixel >> (component * 8)) & 0xff;
QCOMPARE(val, expected[index]);
}
}
}
}
// test area sampling
void tst_QImage::smoothScale2()
{
int sizes[] = { 2, 4, 8, 10, 16, 20, 32, 40, 64, 100, 101, 128, 0 };
QImage::Format formats[] = { QImage::Format_ARGB32, QImage::Format_RGB32, QImage::Format_Invalid };
for (int i = 0; sizes[i] != 0; ++i) {
for (int j = 0; formats[j] != QImage::Format_Invalid; ++j) {
int size = sizes[i];
QRgb expected = formats[j] == QImage::Format_ARGB32 ? qRgba(63, 127, 255, 255) : qRgb(63, 127, 255);
QImage img(size, size, formats[j]);
img.fill(expected);
// scale x down, y down
QImage scaled = img.scaled(QSize(1, 1), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QRgb pixel = scaled.pixel(0, 0);
QCOMPARE(qAlpha(pixel), qAlpha(expected));
QCOMPARE(qRed(pixel), qRed(expected));
QCOMPARE(qGreen(pixel), qGreen(expected));
QCOMPARE(qBlue(pixel), qBlue(expected));
// scale x down, y up
scaled = img.scaled(QSize(1, size * 2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
for (int y = 0; y < scaled.height(); ++y) {
pixel = scaled.pixel(0, y);
QCOMPARE(qAlpha(pixel), qAlpha(expected));
QCOMPARE(qRed(pixel), qRed(expected));
QCOMPARE(qGreen(pixel), qGreen(expected));
QCOMPARE(qBlue(pixel), qBlue(expected));
}
// scale x up, y down
scaled = img.scaled(QSize(size * 2, 1), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
for (int x = 0; x < scaled.width(); ++x) {
pixel = scaled.pixel(x, 0);
QCOMPARE(qAlpha(pixel), qAlpha(expected));
QCOMPARE(qRed(pixel), qRed(expected));
QCOMPARE(qGreen(pixel), qGreen(expected));
QCOMPARE(qBlue(pixel), qBlue(expected));
}
// scale x up, y up
scaled = img.scaled(QSize(size * 2, size * 2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
for (int y = 0; y < scaled.height(); ++y) {
for (int x = 0; x < scaled.width(); ++x) {
pixel = scaled.pixel(x, y);
QCOMPARE(qAlpha(pixel), qAlpha(expected));
QCOMPARE(qRed(pixel), qRed(expected));
QCOMPARE(qGreen(pixel), qGreen(expected));
QCOMPARE(qBlue(pixel), qBlue(expected));
}
}
}
}
}
static inline int rand8()
{
return int(256. * (qrand() / (RAND_MAX + 1.0)));
}
// compares img.scale against the bilinear filtering used by QPainter
void tst_QImage::smoothScale3()
{
QImage img(128, 128, QImage::Format_RGB32);
for (int y = 0; y < img.height(); ++y) {
for (int x = 0; x < img.width(); ++x) {
const int red = rand8();
const int green = rand8();
const int blue = rand8();
const int alpha = 255;
img.setPixel(x, y, qRgba(red, green, blue, alpha));
}
}
qreal scales[2] = { .5, 2 };
for (int i = 0; i < 2; ++i) {
QImage a = img.scaled(img.size() * scales[i], Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QImage b(a.size(), a.format());
b.fill(0x0);
QPainter p(&b);
p.setRenderHint(QPainter::SmoothPixmapTransform);
p.scale(scales[i], scales[i]);
p.drawImage(0, 0, img);
p.end();
int err = 0;
for (int y = 0; y < a.height(); ++y) {
for (int x = 0; x < a.width(); ++x) {
QRgb ca = a.pixel(x, y);
QRgb cb = b.pixel(x, y);
// tolerate a little bit of rounding errors
bool r = true;
r &= qAbs(qRed(ca) - qRed(cb)) <= 18;
r &= qAbs(qGreen(ca) - qGreen(cb)) <= 18;
r &= qAbs(qBlue(ca) - qBlue(cb)) <= 18;
if (!r)
err++;
}
}
QCOMPARE(err, 0);
}
}
void tst_QImage::smoothScaleBig()
{
#if defined(Q_OS_WINCE)
int bigValue = 2000;
#else
int bigValue = 200000;
#endif
QImage tall(4, bigValue, QImage::Format_ARGB32);
tall.fill(0x0);
QImage wide(bigValue, 4, QImage::Format_ARGB32);
wide.fill(0x0);
QImage tallScaled = tall.scaled(4, tall.height() / 4, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QImage wideScaled = wide.scaled(wide.width() / 4, 4, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QCOMPARE(tallScaled.pixel(0, 0), QRgb(0x0));
QCOMPARE(wideScaled.pixel(0, 0), QRgb(0x0));
}
void tst_QImage::smoothScaleAlpha()
{
QImage src(128, 128, QImage::Format_ARGB32_Premultiplied);
src.fill(0x0);
QPainter srcPainter(&src);
srcPainter.setPen(Qt::NoPen);
srcPainter.setBrush(Qt::white);
srcPainter.drawEllipse(QRect(QPoint(), src.size()));
srcPainter.end();
QImage dst(32, 32, QImage::Format_ARGB32_Premultiplied);
dst.fill(0xffffffff);
QImage expected = dst;
QPainter dstPainter(&dst);
dstPainter.drawImage(0, 0, src.scaled(dst.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
dstPainter.end();
QCOMPARE(dst, expected);
}
static int count(const QImage &img, int x, int y, int dx, int dy, QRgb pixel)
{
int i = 0;
while (x >= 0 && x < img.width() && y >= 0 && y < img.height()) {
i += (img.pixel(x, y) == pixel);
x += dx;
y += dy;
}
return i;
}
const int transformed_image_width = 128;
const int transformed_image_height = 128;
void tst_QImage::transformed_data()
{
QTest::addColumn<QTransform>("transform");
{
QTransform transform;
transform.translate(10.4, 10.4);
QTest::newRow("Translate") << transform;
}
{
QTransform transform;
transform.scale(1.5, 1.5);
QTest::newRow("Scale") << transform;
}
{
QTransform transform;
transform.rotate(30);
QTest::newRow("Rotate 30") << transform;
}
{
QTransform transform;
transform.rotate(90);
QTest::newRow("Rotate 90") << transform;
}
{
QTransform transform;
transform.rotate(180);
QTest::newRow("Rotate 180") << transform;
}
{
QTransform transform;
transform.rotate(270);
QTest::newRow("Rotate 270") << transform;
}
{
QTransform transform;
transform.translate(transformed_image_width/2, transformed_image_height/2);
transform.rotate(155, Qt::XAxis);
transform.translate(-transformed_image_width/2, -transformed_image_height/2);
QTest::newRow("Perspective 1") << transform;
}
{
QTransform transform;
transform.rotate(155, Qt::XAxis);
transform.translate(-transformed_image_width/2, -transformed_image_height/2);
QTest::newRow("Perspective 2") << transform;
}
}
void tst_QImage::transformed()
{
QFETCH(QTransform, transform);
QImage img(transformed_image_width, transformed_image_height, QImage::Format_ARGB32_Premultiplied);
QPainter p(&img);
p.fillRect(0, 0, img.width(), img.height(), Qt::red);
p.drawRect(0, 0, img.width()-1, img.height()-1);
p.end();
QImage transformed = img.transformed(transform, Qt::SmoothTransformation);
// all borders should have touched pixels
QVERIFY(count(transformed, 0, 0, 1, 0, 0x0) < transformed.width());
QVERIFY(count(transformed, 0, 0, 0, 1, 0x0) < transformed.height());
QVERIFY(count(transformed, 0, img.height() - 1, 1, 0, 0x0) < transformed.width());
QVERIFY(count(transformed, img.width() - 1, 0, 0, 1, 0x0) < transformed.height());
QImage transformedPadded(transformed.width() + 2, transformed.height() + 2, img.format());
transformedPadded.fill(0x0);
p.begin(&transformedPadded);
p.setRenderHint(QPainter::SmoothPixmapTransform);
p.setRenderHint(QPainter::Antialiasing);
p.setTransform(transformed.trueMatrix(transform, img.width(), img.height()) * QTransform().translate(1, 1));
p.drawImage(0, 0, img);
p.end();
// no borders should have touched pixels since we have a one-pixel padding
QCOMPARE(count(transformedPadded, 0, 0, 1, 0, 0x0), transformedPadded.width());
QCOMPARE(count(transformedPadded, 0, 0, 0, 1, 0x0), transformedPadded.height());
QCOMPARE(count(transformedPadded, 0, transformedPadded.height() - 1, 1, 0, 0x0), transformedPadded.width());
QCOMPARE(count(transformedPadded, transformedPadded.width() - 1, 0, 0, 1, 0x0), transformedPadded.height());
}
void tst_QImage::transformed2()
{
QImage img(3, 3, QImage::Format_Mono);
QPainter p(&img);
p.fillRect(0, 0, 3, 3, Qt::white);
p.fillRect(0, 0, 3, 3, Qt::Dense4Pattern);
p.end();
QTransform transform;
transform.scale(3, 3);
QImage expected(9, 9, QImage::Format_Mono);
p.begin(&expected);
p.fillRect(0, 0, 9, 9, Qt::white);
p.setBrush(Qt::black);
p.setPen(Qt::NoPen);
p.drawRect(3, 0, 3, 3);
p.drawRect(0, 3, 3, 3);
p.drawRect(6, 3, 3, 3);
p.drawRect(3, 6, 3, 3);
p.end();
{
QImage actual = img.transformed(transform);
QCOMPARE(actual.format(), expected.format());
QCOMPARE(actual.size(), expected.size());
QCOMPARE(actual, expected);
}
{
transform.rotate(-90);
QImage actual = img.transformed(transform);
QCOMPARE(actual.convertToFormat(QImage::Format_ARGB32_Premultiplied),
expected.convertToFormat(QImage::Format_ARGB32_Premultiplied));
}
}
void tst_QImage::scaled()
{
QImage img(102, 3, QImage::Format_Mono);
QPainter p(&img);
p.fillRect(0, 0, img.width(), img.height(), Qt::white);
p.end();
QImage scaled = img.scaled(1994, 10);
QImage expected(1994, 10, QImage::Format_Mono);
p.begin(&expected);
p.fillRect(0, 0, expected.width(), expected.height(), Qt::white);
p.end();
QCOMPARE(scaled, expected);
}
void tst_QImage::paintEngine()
{
QImage img;
QPaintEngine *engine;
{
QImage temp(100, 100, QImage::Format_RGB32);
temp.fill(0xff000000);
QPainter p(&temp);
p.fillRect(80,80,10,10,Qt::blue);
p.end();
img = temp;
engine = temp.paintEngine();
}
{
QPainter p(&img);
p.fillRect(80,10,10,10,Qt::yellow);
p.end();
}
QImage expected(100, 100, QImage::Format_RGB32);
expected.fill(0xff000000);
QPainter p(&expected);
p.fillRect(80,80,10,10,Qt::blue);
p.fillRect(80,10,10,10,Qt::yellow);
p.end();
QCOMPARE(engine, img.paintEngine());
QCOMPARE(img, expected);
}
void tst_QImage::setAlphaChannelWhilePainting()
{
QImage image(100, 100, QImage::Format_ARGB32);
image.fill(Qt::black);
QPainter p(&image);
image.setAlphaChannel(image.createMaskFromColor(QColor(Qt::black).rgb(), Qt::MaskInColor));
}
// See task 240047 for details
void tst_QImage::smoothScaledSubImage()
{
QImage original(128, 128, QImage::Format_RGB32);
QPainter p(&original);
p.fillRect(0, 0, 64, 128, Qt::black);
p.fillRect(64, 0, 64, 128, Qt::white);
p.end();
QImage subimage(((const QImage &) original).bits(), 32, 32, original.bytesPerLine(), QImage::Format_RGB32); // only in the black part of the source...
QImage scaled = subimage.scaled(8, 8, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
for (int y=0; y<scaled.height(); ++y)
for (int x=0; x<scaled.width(); ++x)
QCOMPARE(scaled.pixel(x, y), 0xff000000);
}
void tst_QImage::nullSize_data()
{
QTest::addColumn<QImage>("image");
QTest::newRow("null image") << QImage();
QTest::newRow("zero-size image") << QImage(0, 0, QImage::Format_RGB32);
}
void tst_QImage::nullSize()
{
QFETCH(QImage, image);
QCOMPARE(image.isNull(), true);
QCOMPARE(image.width(), image.size().width());
QCOMPARE(image.height(), image.size().height());
}
void tst_QImage::premultipliedAlphaConsistency()
{
QImage img(256, 1, QImage::Format_ARGB32);
for (int x = 0; x < 256; ++x)
img.setPixel(x, 0, (x << 24) | 0xffffff);
QImage converted = img.convertToFormat(QImage::Format_ARGB8565_Premultiplied);
QImage pm32 = converted.convertToFormat(QImage::Format_ARGB32_Premultiplied);
for (int i = 0; i < pm32.width(); ++i) {
QRgb pixel = pm32.pixel(i, 0);
QVERIFY(qRed(pixel) <= qAlpha(pixel));
QVERIFY(qGreen(pixel) <= qAlpha(pixel));
QVERIFY(qBlue(pixel) <= qAlpha(pixel));
}
}
void tst_QImage::compareIndexed()
{
QImage img(256, 1, QImage::Format_Indexed8);
QVector<QRgb> colorTable(256);
for (int i = 0; i < 256; ++i)
colorTable[i] = qRgb(i, i, i);
img.setColorTable(colorTable);
for (int i = 0; i < 256; ++i) {
img.setPixel(i, 0, i);
}
QImage imgInverted(256, 1, QImage::Format_Indexed8);
QVector<QRgb> invertedColorTable(256);
for (int i = 0; i < 256; ++i)
invertedColorTable[255-i] = qRgb(i, i, i);
imgInverted.setColorTable(invertedColorTable);
for (int i = 0; i < 256; ++i) {
imgInverted.setPixel(i, 0, (255-i));
}
QCOMPARE(img, imgInverted);
}
void tst_QImage::fillColor_data()
{
QTest::addColumn<QImage::Format>("format");
QTest::addColumn<Qt::GlobalColor>("color");
QTest::addColumn<uint>("pixelValue");
QTest::newRow("Mono, color0") << QImage::Format_Mono << Qt::color0 << 0u;
QTest::newRow("Mono, color1") << QImage::Format_Mono << Qt::color1 << 1u;
QTest::newRow("MonoLSB, color0") << QImage::Format_MonoLSB << Qt::color0 << 0u;
QTest::newRow("MonoLSB, color1") << QImage::Format_MonoLSB << Qt::color1 << 1u;
const char *names[] = {
"Indexed8",
"RGB32",
"ARGB32",
"ARGB32pm",
"RGB16",
"ARGB8565pm",
"RGB666",
"ARGB6666pm",
"RGB555",
"ARGB8555pm",
"RGB888",
"RGB444",
"ARGB4444pm",
"RGBx8888",
"RGBA8888pm",
0
};
QImage::Format formats[] = {
QImage::Format_Indexed8,
QImage::Format_RGB32,
QImage::Format_ARGB32,
QImage::Format_ARGB32_Premultiplied,
QImage::Format_RGB16,
QImage::Format_ARGB8565_Premultiplied,
QImage::Format_RGB666,
QImage::Format_ARGB6666_Premultiplied,
QImage::Format_RGB555,
QImage::Format_ARGB8555_Premultiplied,
QImage::Format_RGB888,
QImage::Format_RGB444,
QImage::Format_ARGB4444_Premultiplied,
QImage::Format_RGBX8888,
QImage::Format_RGBA8888_Premultiplied,
};
for (int i=0; names[i] != 0; ++i) {
QByteArray name;
name.append(names[i]).append(", ");
QTest::newRow(QByteArray(name).append("black").constData()) << formats[i] << Qt::black << 0xff000000;
QTest::newRow(QByteArray(name).append("white").constData()) << formats[i] << Qt::white << 0xffffffff;
QTest::newRow(QByteArray(name).append("red").constData()) << formats[i] << Qt::red << 0xffff0000;
QTest::newRow(QByteArray(name).append("green").constData()) << formats[i] << Qt::green << 0xff00ff00;
QTest::newRow(QByteArray(name).append("blue").constData()) << formats[i] << Qt::blue << 0xff0000ff;
}
QTest::newRow("RGB16, transparent") << QImage::Format_RGB16 << Qt::transparent << 0xff000000;
QTest::newRow("RGB32, transparent") << QImage::Format_RGB32 << Qt::transparent << 0xff000000;
QTest::newRow("ARGB32, transparent") << QImage::Format_ARGB32 << Qt::transparent << 0x00000000u;
QTest::newRow("ARGB32pm, transparent") << QImage::Format_ARGB32_Premultiplied << Qt::transparent << 0x00000000u;
QTest::newRow("RGBA8888pm, transparent") << QImage::Format_RGBA8888_Premultiplied << Qt::transparent << 0x00000000u;
}
void tst_QImage::fillColor()
{
QFETCH(QImage::Format, format);
QFETCH(Qt::GlobalColor, color);
QFETCH(uint, pixelValue);
QImage image(1, 1, format);
if (image.depth() == 8) {
QVector<QRgb> table;
table << 0xff000000;
table << 0xffffffff;
table << 0xffff0000;
table << 0xff00ff00;
table << 0xff0000ff;
image.setColorTable(table);
}
image.fill(color);
if (image.depth() == 1) {
QCOMPARE(image.pixelIndex(0, 0), (int) pixelValue);
} else {
QCOMPARE(image.pixel(0, 0), pixelValue);
}
image.fill(QColor(color));
if (image.depth() == 1) {
QCOMPARE(image.pixelIndex(0, 0), (int) pixelValue);
} else {
QCOMPARE(image.pixel(0, 0), pixelValue);
}
}
void tst_QImage::fillColorWithAlpha()
{
QImage argb32(1, 1, QImage::Format_ARGB32);
argb32.fill(QColor(255, 0, 0, 127));
QCOMPARE(argb32.pixel(0, 0), qRgba(255, 0, 0, 127));
QImage argb32pm(1, 1, QImage::Format_ARGB32_Premultiplied);
argb32pm.fill(QColor(255, 0, 0, 127));
QCOMPARE(argb32pm.pixel(0, 0), 0x7f7f0000u);
}
void tst_QImage::fillRGB888()
{
QImage expected(1, 1, QImage::Format_RGB888);
QImage actual(1, 1, QImage::Format_RGB888);
for (int c = Qt::black; c < Qt::transparent; ++c) {
QColor color = QColor(Qt::GlobalColor(c));
expected.fill(color);
actual.fill(color.rgba());
QCOMPARE(actual.pixel(0, 0), expected.pixel(0, 0));
}
}
void tst_QImage::rgbSwapped_data()
{
QTest::addColumn<QImage::Format>("format");
QTest::newRow("Format_Indexed8") << QImage::Format_Indexed8;
QTest::newRow("Format_RGB32") << QImage::Format_RGB32;
QTest::newRow("Format_ARGB32") << QImage::Format_ARGB32;
QTest::newRow("Format_ARGB32_Premultiplied") << QImage::Format_ARGB32_Premultiplied;
QTest::newRow("Format_RGB16") << QImage::Format_RGB16;
QTest::newRow("Format_ARGB8565_Premultiplied") << QImage::Format_ARGB8565_Premultiplied;
QTest::newRow("Format_ARGB6666_Premultiplied") << QImage::Format_ARGB6666_Premultiplied;
QTest::newRow("Format_ARGB4444_Premultiplied") << QImage::Format_ARGB4444_Premultiplied;
QTest::newRow("Format_RGB666") << QImage::Format_RGB666;
QTest::newRow("Format_RGB555") << QImage::Format_RGB555;
QTest::newRow("Format_ARGB8555_Premultiplied") << QImage::Format_ARGB8555_Premultiplied;
QTest::newRow("Format_RGB888") << QImage::Format_RGB888;
QTest::newRow("Format_RGB444") << QImage::Format_RGB444;
QTest::newRow("Format_RGBX8888") << QImage::Format_RGBX8888;
QTest::newRow("Format_RGBA8888_Premultiplied") << QImage::Format_RGBA8888_Premultiplied;
}
void tst_QImage::rgbSwapped()
{
QFETCH(QImage::Format, format);
QImage image(100, 1, format);
image.fill(0);
QVector<QColor> testColor(image.width());
for (int i = 0; i < image.width(); ++i)
testColor[i] = QColor(i, 10 + i, 20 + i * 2, 30 + i);
if (format != QImage::Format_Indexed8) {
QPainter p(&image);
p.setCompositionMode(QPainter::CompositionMode_Source);
for (int i = 0; i < image.width(); ++i)
p.fillRect(QRect(i, 0, 1, 1), testColor[i].rgb());
} else {
image.setColorCount(image.width());
for (int i = 0; i < image.width(); ++i) {
image.setColor(0, testColor[i].rgba());
image.setPixel(i, 0, i);
}
}
QImage imageSwapped = image.rgbSwapped();
for (int i = 0; i < image.width(); ++i) {
QColor referenceColor = QColor(image.pixel(i, 0));
QColor swappedColor = QColor(imageSwapped.pixel(i, 0));
QCOMPARE(swappedColor.alpha(), referenceColor.alpha());
QCOMPARE(swappedColor.red(), referenceColor.blue());
QCOMPARE(swappedColor.green(), referenceColor.green());
QCOMPARE(swappedColor.blue(), referenceColor.red());
}
QImage imageSwappedTwice = imageSwapped.rgbSwapped();
QCOMPARE(image, imageSwappedTwice);
QCOMPARE(memcmp(image.constBits(), imageSwappedTwice.constBits(), image.byteCount()), 0);
}
void tst_QImage::deepCopyWhenPaintingActive()
{
QImage image(64, 64, QImage::Format_ARGB32_Premultiplied);
image.fill(0);
QPainter painter(&image);
QImage copy = image;
painter.setBrush(Qt::black);
painter.drawEllipse(image.rect());
QVERIFY(copy != image);
}
void tst_QImage::scaled_QTBUG19157()
{
QImage foo(5000, 1, QImage::Format_RGB32);
foo = foo.scaled(1024, 1024, Qt::KeepAspectRatio);
QVERIFY(!foo.isNull());
}
static void cleanupFunction(void* info)
{
bool *called = static_cast<bool*>(info);
*called = true;
}
void tst_QImage::cleanupFunctions()
{
QImage bufferImage(64, 64, QImage::Format_ARGB32);
bufferImage.fill(0);
bool called;
{
called = false;
{
QImage image(bufferImage.bits(), bufferImage.width(), bufferImage.height(), bufferImage.format(), cleanupFunction, &called);
}
QVERIFY(called);
}
{
called = false;
QImage *copy = 0;
{
QImage image(bufferImage.bits(), bufferImage.width(), bufferImage.height(), bufferImage.format(), cleanupFunction, &called);
copy = new QImage(image);
}
QVERIFY(!called);
delete copy;
QVERIFY(called);
}
}
QTEST_GUILESS_MAIN(tst_QImage)
#include "tst_qimage.moc"
| lgpl-2.1 |
wctaiwan/joeq | Compil3r/Quad/BytecodeToQuad.java | 124534 | // BytecodeToQuad.java, created Fri Jan 11 16:42:38 2002 by joewhaley
// Copyright (C) 2001-3 John Whaley <[email protected]>
// Licensed under the terms of the GNU LGPL; see COPYING for details.
package Compil3r.Quad;
import java.util.HashMap;
import java.util.LinkedList;
import Bootstrap.PrimordialClassLoader;
import Clazz.jq_Array;
import Clazz.jq_Class;
import Clazz.jq_InstanceField;
import Clazz.jq_InstanceMethod;
import Clazz.jq_Method;
import Clazz.jq_Primitive;
import Clazz.jq_Reference;
import Clazz.jq_StaticField;
import Clazz.jq_StaticMethod;
import Clazz.jq_TryCatchBC;
import Clazz.jq_Type;
import Compil3r.BytecodeAnalysis.BytecodeVisitor;
import Compil3r.Quad.Operand.AConstOperand;
import Compil3r.Quad.Operand.ConditionOperand;
import Compil3r.Quad.Operand.DConstOperand;
import Compil3r.Quad.Operand.FConstOperand;
import Compil3r.Quad.Operand.FieldOperand;
import Compil3r.Quad.Operand.IConstOperand;
import Compil3r.Quad.Operand.LConstOperand;
import Compil3r.Quad.Operand.MethodOperand;
import Compil3r.Quad.Operand.PConstOperand;
import Compil3r.Quad.Operand.RegisterOperand;
import Compil3r.Quad.Operand.TargetOperand;
import Compil3r.Quad.Operand.TypeOperand;
import Compil3r.Quad.Operand.UnnecessaryGuardOperand;
import Compil3r.Quad.Operator.ALength;
import Compil3r.Quad.Operator.ALoad;
import Compil3r.Quad.Operator.AStore;
import Compil3r.Quad.Operator.Binary;
import Compil3r.Quad.Operator.BoundsCheck;
import Compil3r.Quad.Operator.CheckCast;
import Compil3r.Quad.Operator.Getfield;
import Compil3r.Quad.Operator.Getstatic;
import Compil3r.Quad.Operator.Goto;
import Compil3r.Quad.Operator.InstanceOf;
import Compil3r.Quad.Operator.IntIfCmp;
import Compil3r.Quad.Operator.Invoke;
import Compil3r.Quad.Operator.Jsr;
import Compil3r.Quad.Operator.LookupSwitch;
import Compil3r.Quad.Operator.MemLoad;
import Compil3r.Quad.Operator.MemStore;
import Compil3r.Quad.Operator.Monitor;
import Compil3r.Quad.Operator.Move;
import Compil3r.Quad.Operator.New;
import Compil3r.Quad.Operator.NewArray;
import Compil3r.Quad.Operator.NullCheck;
import Compil3r.Quad.Operator.Putfield;
import Compil3r.Quad.Operator.Putstatic;
import Compil3r.Quad.Operator.Ret;
import Compil3r.Quad.Operator.Return;
import Compil3r.Quad.Operator.Special;
import Compil3r.Quad.Operator.StoreCheck;
import Compil3r.Quad.Operator.TableSwitch;
import Compil3r.Quad.Operator.Unary;
import Compil3r.Quad.Operator.ZeroCheck;
import Compil3r.Quad.RegisterFactory.Register;
import Main.jq;
import Memory.Address;
import Memory.HeapAddress;
import Memory.StackAddress;
import Run_Time.Reflection;
import Run_Time.TypeCheck;
import UTF.Utf8;
import Util.Assert;
import Util.Strings;
/**
* Converts stack-based Java bytecode to Quad intermediate format.
* This utilizes the ControlFlowGraph in the BytecodeAnalysis package to build
* up a control flow graph, then iterates over the graph to generate the Quad
* code.
*
* @see BytecodeVisitor
* @see Compil3r.BytecodeAnalysis.ControlFlowGraph
* @author John Whaley <[email protected]>
* @version $Id: BytecodeToQuad.java,v 1.58 2003/06/18 00:00:53 mcmartin Exp $
*/
public class BytecodeToQuad extends BytecodeVisitor {
private ControlFlowGraph quad_cfg;
private BasicBlock quad_bb;
private Compil3r.BytecodeAnalysis.ControlFlowGraph bc_cfg;
private Compil3r.BytecodeAnalysis.BasicBlock bc_bb;
private BasicBlock[] quad_bbs;
private RegisterFactory rf;
private boolean[] visited;
private boolean uncond_branch;
private LinkedList regenerate;
private HashMap quad2bci = new HashMap();
public static boolean ALWAYS_TRACE = false;
/** Initializes the conversion from bytecode to quad format for the given method.
* @param method the method to convert. */
public BytecodeToQuad(jq_Method method) {
super(method);
TRACE = ALWAYS_TRACE;
}
/** Returns a string with the name of the pass and the method being converted.
* @return a string with the name of the pass and the method being converted. */
public String toString() {
return "BC2Q/"+Strings.left(method.getName().toString(), 10);
}
/** Perform conversion process from bytecode to quad.
* @return the control flow graph of the resulting quad representation. */
public ControlFlowGraph convert() {
bc_cfg = Compil3r.BytecodeAnalysis.ControlFlowGraph.computeCFG(method);
// initialize register factory
this.rf = new RegisterFactory(method);
// copy bytecode cfg to quad cfg
jq_TryCatchBC[] exs = method.getExceptionTable();
this.quad_cfg = new ControlFlowGraph(method, bc_cfg.getExit().getNumberOfPredecessors(),
exs.length, this.rf);
quad_bbs = new BasicBlock[bc_cfg.getNumberOfBasicBlocks()];
quad_bbs[0] = this.quad_cfg.entry();
quad_bbs[1] = this.quad_cfg.exit();
for (int i=2; i<quad_bbs.length; ++i) {
Compil3r.BytecodeAnalysis.BasicBlock bc_bb = bc_cfg.getBasicBlock(i);
int n_pred = bc_bb.getNumberOfPredecessors();
int n_succ = bc_bb.getNumberOfSuccessors();
int n_inst = bc_bb.getEnd() - bc_bb.getStart() + 1; // estimate
quad_bbs[i] = BasicBlock.createBasicBlock(i, n_pred, n_succ, n_inst);
}
this.quad_cfg.updateBBcounter(quad_bbs.length);
// add exception handlers.
for (int i=exs.length-1; i>=0; --i) {
jq_TryCatchBC ex = exs[i];
Compil3r.BytecodeAnalysis.BasicBlock bc_bb = bc_cfg.getBasicBlockByBytecodeIndex(ex.getStartPC());
Assert._assert(bc_bb.getStart() < ex.getEndPC());
BasicBlock ex_handler = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(ex.getHandlerPC()).id];
ex_handler.setExceptionHandlerEntry();
int numOfProtectedBlocks = (ex.getEndPC()==method.getBytecode().length?quad_bbs.length:bc_cfg.getBasicBlockByBytecodeIndex(ex.getEndPC()).id) - bc_bb.id;
ExceptionHandler eh = new ExceptionHandler(ex.getExceptionType(), numOfProtectedBlocks, ex_handler);
quad_cfg.addExceptionHandler(eh);
ExceptionHandlerList ehs = new ExceptionHandlerList(eh, null);
BasicBlock bb = quad_bbs[bc_bb.id];
bb.addExceptionHandler_first(ehs);
for (;;) {
bc_bb = bc_cfg.getBasicBlock(bc_bb.id+1);
bb = quad_bbs[bc_bb.id];
if (bc_bb.getStart() >= ex.getEndPC()) break;
ehs = bb.addExceptionHandler(ehs);
}
}
this.start_states = new AbstractState[quad_bbs.length];
for (int i=0; i<quad_bbs.length; ++i) {
Compil3r.BytecodeAnalysis.BasicBlock bc_bb = bc_cfg.getBasicBlock(i);
BasicBlock bb = quad_bbs[i];
for (int j=0; j<bc_bb.getNumberOfPredecessors(); ++j) {
bb.addPredecessor(quad_bbs[bc_bb.getPredecessor(j).id]);
}
for (int j=0; j<bc_bb.getNumberOfSuccessors(); ++j) {
bb.addSuccessor(quad_bbs[bc_bb.getSuccessor(j).id]);
}
// --> start state allocated on demand in merge
//this.start_states[i] = new AbstractState(max_stack, max_locals);
}
// initialize start state
this.start_states[2] = AbstractState.allocateInitialState(rf, method);
this.current_state = AbstractState.allocateEmptyState(method);
regenerate = new LinkedList();
visited = new boolean[quad_bbs.length];
// traverse reverse post-order over basic blocks to generate instructions
Compil3r.BytecodeAnalysis.ControlFlowGraph.RPOBasicBlockIterator rpo = bc_cfg.reversePostOrderIterator();
Compil3r.BytecodeAnalysis.BasicBlock first_bb = rpo.nextBB();
Assert._assert(first_bb == bc_cfg.getEntry());
while (rpo.hasNext()) {
Compil3r.BytecodeAnalysis.BasicBlock bc_bb = rpo.nextBB();
visited[bc_bb.id] = true;
this.traverseBB(bc_bb);
}
while (!regenerate.isEmpty()) {
Compil3r.BytecodeAnalysis.BasicBlock bc_bb =
(Compil3r.BytecodeAnalysis.BasicBlock)regenerate.removeFirst();
this.traverseBB(bc_bb);
}
return this.quad_cfg;
}
private boolean endBasicBlock;
private boolean endsWithRET;
/**
* @param bc_bb */
public void traverseBB(Compil3r.BytecodeAnalysis.BasicBlock bc_bb) {
if (start_states[bc_bb.id] == null) {
// unreachable block!
if (TRACE) out.println("Basic block "+bc_bb+" is unreachable!");
return;
}
if (bc_bb.getStart() == -1) {
return; // entry or exit
}
if (TRACE) out.println("Visiting "+bc_bb);
this.quad_bb = quad_bbs[bc_bb.id];
this.quad_bb.removeAllQuads();
this.bc_bb = bc_bb;
this.uncond_branch = false;
this.current_state.overwriteWith(start_states[bc_bb.id]);
if (this.quad_bb.isExceptionHandlerEntry()) {
// TODO: find non-exceptional branches to exception handler entries and split the basic block.
jq_Type type = ((RegisterOperand)this.current_state.peekStack(0)).getType();
RegisterOperand t = getStackRegister(type, 0);
this.quad_bb.appendQuad(Special.create(quad_cfg.getNewQuadID(), Special.GET_EXCEPTION.INSTANCE, t));
}
if (TRACE) this.current_state.dumpState();
this.endBasicBlock = false;
this.endsWithRET = false;
for (i_end=bc_bb.getStart()-1; ; ) {
i_start = i_end+1;
if (isEndOfBB()) break;
this.visitBytecode();
}
saveStackIntoRegisters();
if (!endsWithRET) {
for (int i=0; i<bc_bb.getNumberOfSuccessors(); ++i) {
this.mergeStateWith(bc_bb.getSuccessor(i));
}
}
}
private boolean isEndOfBB() {
return i_start > bc_bb.getEnd() || endBasicBlock;
}
private void mergeStateWith(Compil3r.BytecodeAnalysis.BasicBlock bc_bb) {
if (start_states[bc_bb.id] == null) {
if (TRACE) out.println("Copying current state to "+bc_bb);
start_states[bc_bb.id] = current_state.copy();
} else {
if (TRACE) out.println("Merging current state with "+bc_bb);
if (start_states[bc_bb.id].merge(current_state, rf)) {
if (TRACE) out.println("in set of "+bc_bb+" changed");
if (visited[bc_bb.id]) {
if (TRACE) out.println("must regenerate code for "+bc_bb);
if (!regenerate.contains(bc_bb)) regenerate.add(bc_bb);
}
}
}
}
private void mergeStateWith(Compil3r.BytecodeAnalysis.ExceptionHandler eh) {
Compil3r.BytecodeAnalysis.BasicBlock bc_bb = eh.getEntry();
if (start_states[bc_bb.id] == null) {
if (TRACE) out.println("Copying exception state to "+bc_bb);
start_states[bc_bb.id] = current_state.copyExceptionHandler(eh.getExceptionType(), rf);
} else {
if (TRACE) out.println("Merging exception state with "+bc_bb);
if (start_states[bc_bb.id].mergeExceptionHandler(current_state, eh.getExceptionType(), rf)) {
if (TRACE) out.println("in set of exception handler "+bc_bb+" changed");
if (visited[bc_bb.id]) {
if (TRACE) out.println("must regenerate code for "+bc_bb);
if (!regenerate.contains(bc_bb)) regenerate.add(bc_bb);
}
}
}
}
private void saveStackIntoRegisters() {
for (int i=0; i<current_state.getStackSize(); ++i) {
Operand op = current_state.peekStack(i);
if (op instanceof AbstractState.DummyOperand) continue;
if (op instanceof RegisterOperand) {
RegisterOperand rop = (RegisterOperand)op;
Register r = rf.getStack(current_state.getStackSize()-i-1, rop.getType());
if (rop.getRegister() == r)
continue;
}
jq_Type type = getTypeOf(op);
RegisterOperand t = getStackRegister(type, i);
Quad q = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type), t, op);
appendQuad(q);
current_state.pokeStack(i, t.copy());
}
}
private void replaceLocalsOnStack(int index, jq_Type type) {
for (int i=0; i<current_state.getStackSize(); ++i) {
Operand op = current_state.peekStack(i);
if (rf.isLocal(op, index, type)) {
RegisterOperand rop = (RegisterOperand)op;
RegisterOperand t = getStackRegister(type, i);
t.setFlags(rop.getFlags()); t.scratchObject = rop.scratchObject;
Quad q = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type), t, rop);
appendQuad(q);
current_state.pokeStack(i, t.copy());
}
}
}
void appendQuad(Quad q) {
if (TRACE) out.println(q.toString());
quad_bb.appendQuad(q);
quad2bci.put(q, new Integer(i_start));
}
/**
* return quad->bytecode map, may be incomplete
* @return Map<Quad, Integer>
*/
java.util.Map getQuadToBytecodeMap() {
return quad2bci;
}
RegisterOperand getStackRegister(jq_Type type, int i) {
if (current_state.getStackSize()-i-1 < 0) {
System.out.println("Error in "+method+" offset "+i_start);
current_state.dumpState();
}
return new RegisterOperand(rf.getStack(current_state.getStackSize()-i-1, type), type);
}
RegisterOperand getStackRegister(jq_Type type) {
return getStackRegister(type, -1);
}
RegisterOperand makeLocal(int i, jq_Type type) {
return new RegisterOperand(rf.getLocal(i, type), type);
}
RegisterOperand makeLocal(int i, RegisterOperand rop) {
jq_Type type = rop.getType();
return new RegisterOperand(rf.getLocal(i, type), type, rop.getFlags());
}
static boolean hasGuard(RegisterOperand rop) { return rop.scratchObject != null; }
static void setGuard(RegisterOperand rop, Operand guard) { rop.scratchObject = guard; }
static Operand getGuard(Operand op) {
if (op instanceof RegisterOperand) {
RegisterOperand rop = (RegisterOperand)op;
return (Operand)rop.scratchObject;
}
Assert._assert(op instanceof AConstOperand);
return new UnnecessaryGuardOperand();
}
Operand currentGuard;
void setCurrentGuard(Operand guard) { currentGuard = guard; }
void clearCurrentGuard() { currentGuard = null; }
Operand getCurrentGuard() { if (currentGuard == null) return null; return currentGuard.copy(); }
private AbstractState[] start_states;
private AbstractState current_state;
public void visitNOP() {
super.visitNOP();
// do nothing
}
public void visitACONST(Object s) {
super.visitACONST(s);
current_state.push_A(new AConstOperand(s));
}
public void visitICONST(int c) {
super.visitICONST(c);
current_state.push_I(new IConstOperand(c));
}
public void visitLCONST(long c) {
super.visitLCONST(c);
current_state.push_L(new LConstOperand(c));
}
public void visitFCONST(float c) {
super.visitFCONST(c);
current_state.push_F(new FConstOperand(c));
}
public void visitDCONST(double c) {
super.visitDCONST(c);
current_state.push_D(new DConstOperand(c));
}
public void visitILOAD(int i) {
super.visitILOAD(i);
current_state.push_I(current_state.getLocal_I(i));
}
public void visitLLOAD(int i) {
super.visitLLOAD(i);
current_state.push_L(current_state.getLocal_L(i));
}
public void visitFLOAD(int i) {
super.visitFLOAD(i);
current_state.push_F(current_state.getLocal_F(i));
}
public void visitDLOAD(int i) {
super.visitDLOAD(i);
current_state.push_D(current_state.getLocal_D(i));
}
public void visitALOAD(int i) {
super.visitALOAD(i);
// could be A or R
current_state.push(current_state.getLocal(i));
}
private void STOREhelper(int i, jq_Type type) {
replaceLocalsOnStack(i, type);
Operand op1 = current_state.pop(type);
Operand local_value;
RegisterOperand op0;
if (op1 instanceof RegisterOperand) {
// move from one local variable to another.
local_value = op0 = makeLocal(i, (RegisterOperand)op1); // copy attributes.
} else {
// move a constant to a local variable.
local_value = op1;
op0 = makeLocal(i, type);
}
if (type.getReferenceSize() == 8) current_state.setLocalDual(i, local_value);
else current_state.setLocal(i, local_value);
Quad q = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type), op0, op1);
appendQuad(q);
}
public void visitISTORE(int i) {
super.visitISTORE(i);
STOREhelper(i, jq_Primitive.INT);
}
public void visitLSTORE(int i) {
super.visitLSTORE(i);
STOREhelper(i, jq_Primitive.LONG);
}
public void visitFSTORE(int i) {
super.visitFSTORE(i);
STOREhelper(i, jq_Primitive.FLOAT);
}
public void visitDSTORE(int i) {
super.visitDSTORE(i);
STOREhelper(i, jq_Primitive.DOUBLE);
}
public void visitASTORE(int i) {
super.visitASTORE(i);
Operand op1 = current_state.peekStack(0);
STOREhelper(i, getTypeOf(op1));
}
private void ALOADhelper(ALoad operator, jq_Type t) {
Operand index = current_state.pop_I();
Operand ref = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(ref)) {
if (TRACE) System.out.println("Null check triggered on "+ref);
return;
}
if (performBoundsCheck(ref, index)) {
if (TRACE) System.out.println("Bounds check triggered on "+ref+" "+index);
return;
}
if (t.isReferenceType()) {
// refine type.
t = getArrayElementTypeOf(ref);
Assert._assert(!t.isAddressType());
}
RegisterOperand r = getStackRegister(t);
Quad q = ALoad.create(quad_cfg.getNewQuadID(), operator, r, ref, index, getCurrentGuard());
appendQuad(q);
current_state.push(r.copy(), t);
}
public void visitIALOAD() {
super.visitIALOAD();
ALOADhelper(ALoad.ALOAD_I.INSTANCE, jq_Primitive.INT);
}
public void visitLALOAD() {
super.visitLALOAD();
ALOADhelper(ALoad.ALOAD_L.INSTANCE, jq_Primitive.LONG);
}
public void visitFALOAD() {
super.visitFALOAD();
ALOADhelper(ALoad.ALOAD_F.INSTANCE, jq_Primitive.FLOAT);
}
public void visitDALOAD() {
super.visitDALOAD();
ALOADhelper(ALoad.ALOAD_D.INSTANCE, jq_Primitive.DOUBLE);
}
public void visitAALOAD() {
super.visitAALOAD();
Operand index = current_state.pop_I();
Operand ref = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(ref)) {
if (TRACE) System.out.println("Null check triggered on "+ref);
return;
}
if (performBoundsCheck(ref, index)) {
if (TRACE) System.out.println("Bounds check triggered on "+ref+" "+index);
return;
}
jq_Type t = getArrayElementTypeOf(ref);
ALoad operator = t.isAddressType()?(ALoad)ALoad.ALOAD_P.INSTANCE:ALoad.ALOAD_A.INSTANCE;
RegisterOperand r = getStackRegister(t);
Quad q = ALoad.create(quad_cfg.getNewQuadID(), operator, r, ref, index, getCurrentGuard());
appendQuad(q);
current_state.push(r.copy(), t);
}
public void visitBALOAD() {
super.visitBALOAD();
ALOADhelper(ALoad.ALOAD_B.INSTANCE, jq_Primitive.BYTE);
}
public void visitCALOAD() {
super.visitCALOAD();
ALOADhelper(ALoad.ALOAD_C.INSTANCE, jq_Primitive.CHAR);
}
public void visitSALOAD() {
super.visitSALOAD();
ALOADhelper(ALoad.ALOAD_S.INSTANCE, jq_Primitive.SHORT);
}
private void ASTOREhelper(AStore operator, jq_Type t) {
Operand val = current_state.pop(t);
Operand index = current_state.pop_I();
Operand ref = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(ref)) {
if (TRACE) System.out.println("Null check triggered on "+ref);
return;
}
if (performBoundsCheck(ref, index)) {
if (TRACE) System.out.println("Bounds check triggered on "+ref+" "+index);
return;
}
if (t.isReferenceType() && ref instanceof RegisterOperand) {
// perform checkstore
if (performCheckStore((RegisterOperand)ref, val)) return;
Assert._assert(!t.isAddressType());
}
Quad q = AStore.create(quad_cfg.getNewQuadID(), operator, val, ref, index, getCurrentGuard());
appendQuad(q);
}
public void visitIASTORE() {
super.visitIASTORE();
ASTOREhelper(AStore.ASTORE_I.INSTANCE, jq_Primitive.INT);
}
public void visitLASTORE() {
super.visitLASTORE();
ASTOREhelper(AStore.ASTORE_L.INSTANCE, jq_Primitive.LONG);
}
public void visitFASTORE() {
super.visitFASTORE();
ASTOREhelper(AStore.ASTORE_F.INSTANCE, jq_Primitive.FLOAT);
}
public void visitDASTORE() {
super.visitDASTORE();
ASTOREhelper(AStore.ASTORE_D.INSTANCE, jq_Primitive.DOUBLE);
}
public void visitAASTORE() {
// could be A or R
Operand val = current_state.pop();
Operand index = current_state.pop_I();
Operand ref = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(ref)) {
if (TRACE) System.out.println("Null check triggered on "+ref);
return;
}
if (performBoundsCheck(ref, index)) {
if (TRACE) System.out.println("Bounds check triggered on "+ref+" "+index);
return;
}
jq_Type arrayElemType = getArrayElementTypeOf(ref);
AStore operator = arrayElemType.isAddressType()?(AStore)AStore.ASTORE_P.INSTANCE:AStore.ASTORE_A.INSTANCE;
if (ref instanceof RegisterOperand) {
// perform checkstore
if (performCheckStore((RegisterOperand)ref, val)) return;
}
Quad q = AStore.create(quad_cfg.getNewQuadID(), operator, val, ref, index, getCurrentGuard());
appendQuad(q);
}
public void visitBASTORE() {
super.visitBASTORE();
ASTOREhelper(AStore.ASTORE_B.INSTANCE, jq_Primitive.BYTE);
}
public void visitCASTORE() {
super.visitCASTORE();
ASTOREhelper(AStore.ASTORE_C.INSTANCE, jq_Primitive.CHAR);
}
public void visitSASTORE() {
super.visitSASTORE();
ASTOREhelper(AStore.ASTORE_S.INSTANCE, jq_Primitive.SHORT);
}
public void visitPOP() {
super.visitPOP();
current_state.pop();
}
public void visitPOP2() {
super.visitPOP2();
current_state.pop(); current_state.pop();
}
public void visitDUP() {
super.visitDUP();
Operand op = current_state.pop();
int d = current_state.getStackSize();
jq_Type type = getTypeOf(op);
RegisterOperand t = new RegisterOperand(rf.getNewStack(d+1, type), type);
Quad q = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type), t, op);
appendQuad(q);
current_state.push(op.copy(), type);
current_state.push(t.copy(), type);
}
private void do_DUP_x1() {
Operand op1 = current_state.pop();
Operand op2 = current_state.pop();
int d = current_state.getStackSize();
jq_Type type1 = getTypeOf(op1);
jq_Type type2 = getTypeOf(op2);
RegisterOperand t1 = new RegisterOperand(rf.getNewStack(d+2, type1), type1);
Quad q1 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type1), t1, op1);
appendQuad(q1);
RegisterOperand t2 = new RegisterOperand(rf.getNewStack(d+1, type2), type2);
Quad q2 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type2), t2, op2);
appendQuad(q2);
RegisterOperand t3 = new RegisterOperand(rf.getNewStack(d, type1), type1);
Quad q3 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type1), t3, t1.copy());
appendQuad(q3);
current_state.push(t3.copy(), type1);
current_state.push(t2.copy(), type2);
current_state.push(t1.copy(), type1);
}
public void visitDUP_x1() {
super.visitDUP_x1();
do_DUP_x1();
}
public void visitDUP_x2() {
super.visitDUP_x2();
Operand op1 = current_state.pop();
Operand op2 = current_state.pop();
Operand op3 = current_state.pop();
int d = current_state.getStackSize();
jq_Type type1 = getTypeOf(op1);
RegisterOperand t1 = new RegisterOperand(rf.getNewStack(d+3, type1), type1);
Quad q1 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type1), t1, op1);
appendQuad(q1);
RegisterOperand t2 = null; jq_Type type2 = null;
if (op2 != AbstractState.DummyOperand.DUMMY) {
type2 = getTypeOf(op2);
t2 = new RegisterOperand(rf.getNewStack(d+2, type2), type2);
Quad q2 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type2), t2, op2);
appendQuad(q2);
}
jq_Type type3 = getTypeOf(op3);
RegisterOperand t3 = new RegisterOperand(rf.getNewStack(d+1, type3), type3);
Quad q3 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type3), t3, op3);
appendQuad(q3);
RegisterOperand t4 = new RegisterOperand(rf.getNewStack(d, type1), type1);
Quad q4 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type1), t4, t1.copy());
appendQuad(q4);
current_state.push(t4.copy(), type1);
current_state.push(t3.copy(), type3);
if (op2 != AbstractState.DummyOperand.DUMMY)
current_state.push(t2.copy(), type2);
current_state.push(t1.copy(), type1);
}
public void visitDUP2() {
super.visitDUP2();
Operand op1 = current_state.pop();
Operand op2 = current_state.pop();
int d = current_state.getStackSize();
RegisterOperand t1 = null; jq_Type type1 = null;
if (op1 != AbstractState.DummyOperand.DUMMY) {
type1 = getTypeOf(op1);
t1 = new RegisterOperand(rf.getNewStack(d+3, type1), type1);
Quad q1 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type1), t1, op1);
appendQuad(q1);
}
jq_Type type2 = getTypeOf(op2);
RegisterOperand t2 = new RegisterOperand(rf.getNewStack(d+2, type2), type2);
Quad q2 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(type2), t2, op2);
appendQuad(q2);
current_state.push(t2.copy(), type2);
if (op1 != AbstractState.DummyOperand.DUMMY)
current_state.push(t1.copy(), type1);
current_state.push(op2.copy(), type2);
if (op1 != AbstractState.DummyOperand.DUMMY)
current_state.push(op1.copy(), type1);
}
public void visitDUP2_x1() {
super.visitDUP2_x1();
// TODO: do this correctly.
Operand op1 = current_state.pop();
Operand op2 = current_state.pop();
Operand op3 = current_state.pop();
current_state.push(op2);
current_state.push(op1);
current_state.push(op3);
current_state.push(op2.copy());
current_state.push(op1.copy());
}
public void visitDUP2_x2() {
super.visitDUP2_x2();
// TODO: do this correctly.
Operand op1 = current_state.pop();
Operand op2 = current_state.pop();
Operand op3 = current_state.pop();
Operand op4 = current_state.pop();
current_state.push(op2);
current_state.push(op1);
current_state.push(op4);
current_state.push(op3);
current_state.push(op2.copy());
current_state.push(op1.copy());
}
public void visitSWAP() {
super.visitSWAP();
do_DUP_x1();
current_state.pop();
}
private void BINOPhelper(Binary operator, jq_Type tr, jq_Type t1, jq_Type t2, boolean zero_check) {
Operand op2 = current_state.pop(t2);
Operand op1 = current_state.pop(t1);
if (zero_check && performZeroCheck(op2)) {
if (TRACE) System.out.println("Zero check triggered on "+op2);
return;
}
RegisterOperand r = getStackRegister(tr);
Quad q = Binary.create(quad_cfg.getNewQuadID(), operator, r, op1, op2);
appendQuad(q);
current_state.push(r.copy(), tr);
}
public void visitIBINOP(byte op) {
super.visitIBINOP(op);
Binary operator=null; boolean zero_check = false;
switch (op) {
case BINOP_ADD: operator = Binary.ADD_I.INSTANCE; break;
case BINOP_SUB: operator = Binary.SUB_I.INSTANCE; break;
case BINOP_MUL: operator = Binary.MUL_I.INSTANCE; break;
case BINOP_DIV: operator = Binary.DIV_I.INSTANCE; zero_check = true; break;
case BINOP_REM: operator = Binary.REM_I.INSTANCE; zero_check = true; break;
case BINOP_AND: operator = Binary.AND_I.INSTANCE; break;
case BINOP_OR: operator = Binary.OR_I.INSTANCE; break;
case BINOP_XOR: operator = Binary.XOR_I.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
BINOPhelper(operator, jq_Primitive.INT, jq_Primitive.INT, jq_Primitive.INT, zero_check);
}
public void visitLBINOP(byte op) {
super.visitLBINOP(op);
Binary operator=null; boolean zero_check = false;
switch (op) {
case BINOP_ADD: operator = Binary.ADD_L.INSTANCE; break;
case BINOP_SUB: operator = Binary.SUB_L.INSTANCE; break;
case BINOP_MUL: operator = Binary.MUL_L.INSTANCE; break;
case BINOP_DIV: operator = Binary.DIV_L.INSTANCE; zero_check = true; break;
case BINOP_REM: operator = Binary.REM_L.INSTANCE; zero_check = true; break;
case BINOP_AND: operator = Binary.AND_L.INSTANCE; break;
case BINOP_OR: operator = Binary.OR_L.INSTANCE; break;
case BINOP_XOR: operator = Binary.XOR_L.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
BINOPhelper(operator, jq_Primitive.LONG, jq_Primitive.LONG, jq_Primitive.LONG, zero_check);
}
public void visitFBINOP(byte op) {
super.visitFBINOP(op);
Binary operator=null;
switch (op) {
case BINOP_ADD: operator = Binary.ADD_F.INSTANCE; break;
case BINOP_SUB: operator = Binary.SUB_F.INSTANCE; break;
case BINOP_MUL: operator = Binary.MUL_F.INSTANCE; break;
case BINOP_DIV: operator = Binary.DIV_F.INSTANCE; break;
case BINOP_REM: operator = Binary.REM_F.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
BINOPhelper(operator, jq_Primitive.FLOAT, jq_Primitive.FLOAT, jq_Primitive.FLOAT, false);
}
public void visitDBINOP(byte op) {
super.visitDBINOP(op);
Binary operator=null;
switch (op) {
case BINOP_ADD: operator = Binary.ADD_D.INSTANCE; break;
case BINOP_SUB: operator = Binary.SUB_D.INSTANCE; break;
case BINOP_MUL: operator = Binary.MUL_D.INSTANCE; break;
case BINOP_DIV: operator = Binary.DIV_D.INSTANCE; break;
case BINOP_REM: operator = Binary.REM_D.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
BINOPhelper(operator, jq_Primitive.DOUBLE, jq_Primitive.DOUBLE, jq_Primitive.DOUBLE, false);
}
public void UNOPhelper(Unary operator, jq_Type tr, jq_Type t1) {
Operand op1 = current_state.pop(t1);
RegisterOperand r = getStackRegister(tr);
Quad q = Unary.create(quad_cfg.getNewQuadID(), operator, r, op1);
appendQuad(q);
current_state.push(r.copy(), tr);
}
public void visitIUNOP(byte op) {
super.visitIUNOP(op);
Unary operator=null;
switch (op) {
case UNOP_NEG: operator = Unary.NEG_I.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
UNOPhelper(operator, jq_Primitive.INT, jq_Primitive.INT);
}
public void visitLUNOP(byte op) {
super.visitLUNOP(op);
Unary operator=null;
switch (op) {
case UNOP_NEG: operator = Unary.NEG_L.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
UNOPhelper(operator, jq_Primitive.LONG, jq_Primitive.LONG);
}
public void visitFUNOP(byte op) {
super.visitFUNOP(op);
Unary operator=null;
switch (op) {
case UNOP_NEG: operator = Unary.NEG_F.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
UNOPhelper(operator, jq_Primitive.FLOAT, jq_Primitive.FLOAT);
}
public void visitDUNOP(byte op) {
super.visitDUNOP(op);
Unary operator=null;
switch (op) {
case UNOP_NEG: operator = Unary.NEG_D.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
UNOPhelper(operator, jq_Primitive.DOUBLE, jq_Primitive.DOUBLE);
}
public void visitISHIFT(byte op) {
super.visitISHIFT(op);
Binary operator=null;
switch (op) {
case SHIFT_LEFT: operator = Binary.SHL_I.INSTANCE; break;
case SHIFT_RIGHT: operator = Binary.SHR_I.INSTANCE; break;
case SHIFT_URIGHT: operator = Binary.USHR_I.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
BINOPhelper(operator, jq_Primitive.INT, jq_Primitive.INT, jq_Primitive.INT, false);
}
public void visitLSHIFT(byte op) {
super.visitLSHIFT(op);
Binary operator=null;
switch (op) {
case SHIFT_LEFT: operator = Binary.SHL_L.INSTANCE; break;
case SHIFT_RIGHT: operator = Binary.SHR_L.INSTANCE; break;
case SHIFT_URIGHT: operator = Binary.USHR_L.INSTANCE; break;
default: Assert.UNREACHABLE(); break;
}
BINOPhelper(operator, jq_Primitive.LONG, jq_Primitive.LONG, jq_Primitive.INT, false);
}
public void visitIINC(int i, int v) {
super.visitIINC(i, v);
Operand op1 = current_state.getLocal_I(i);
replaceLocalsOnStack(i, jq_Primitive.INT);
RegisterOperand op0 = makeLocal(i, jq_Primitive.INT);
Quad q = Binary.create(quad_cfg.getNewQuadID(), Binary.ADD_I.INSTANCE, op0, op1, new IConstOperand(v));
appendQuad(q);
current_state.setLocal(i, op0);
}
public void visitI2L() {
super.visitI2L();
UNOPhelper(Unary.INT_2LONG.INSTANCE, jq_Primitive.LONG, jq_Primitive.INT);
}
public void visitI2F() {
super.visitI2F();
UNOPhelper(Unary.INT_2FLOAT.INSTANCE, jq_Primitive.FLOAT, jq_Primitive.INT);
}
public void visitI2D() {
super.visitI2D();
UNOPhelper(Unary.INT_2DOUBLE.INSTANCE, jq_Primitive.DOUBLE, jq_Primitive.INT);
}
public void visitL2I() {
super.visitL2I();
UNOPhelper(Unary.LONG_2INT.INSTANCE, jq_Primitive.INT, jq_Primitive.LONG);
}
public void visitL2F() {
super.visitL2F();
UNOPhelper(Unary.LONG_2FLOAT.INSTANCE, jq_Primitive.FLOAT, jq_Primitive.LONG);
}
public void visitL2D() {
super.visitL2D();
UNOPhelper(Unary.LONG_2DOUBLE.INSTANCE, jq_Primitive.DOUBLE, jq_Primitive.LONG);
}
public void visitF2I() {
super.visitF2I();
UNOPhelper(Unary.FLOAT_2INT.INSTANCE, jq_Primitive.INT, jq_Primitive.FLOAT);
}
public void visitF2L() {
super.visitF2L();
UNOPhelper(Unary.FLOAT_2LONG.INSTANCE, jq_Primitive.LONG, jq_Primitive.FLOAT);
}
public void visitF2D() {
super.visitF2D();
UNOPhelper(Unary.FLOAT_2DOUBLE.INSTANCE, jq_Primitive.DOUBLE, jq_Primitive.FLOAT);
}
public void visitD2I() {
super.visitD2I();
UNOPhelper(Unary.DOUBLE_2INT.INSTANCE, jq_Primitive.INT, jq_Primitive.DOUBLE);
}
public void visitD2L() {
super.visitD2L();
UNOPhelper(Unary.DOUBLE_2LONG.INSTANCE, jq_Primitive.LONG, jq_Primitive.DOUBLE);
}
public void visitD2F() {
super.visitD2F();
UNOPhelper(Unary.DOUBLE_2FLOAT.INSTANCE, jq_Primitive.FLOAT, jq_Primitive.DOUBLE);
}
public void visitI2B() {
super.visitI2B();
UNOPhelper(Unary.INT_2BYTE.INSTANCE, jq_Primitive.BYTE, jq_Primitive.INT);
}
public void visitI2C() {
super.visitI2C();
UNOPhelper(Unary.INT_2CHAR.INSTANCE, jq_Primitive.CHAR, jq_Primitive.INT);
}
public void visitI2S() {
super.visitI2S();
UNOPhelper(Unary.INT_2SHORT.INSTANCE, jq_Primitive.SHORT, jq_Primitive.INT);
}
public void visitLCMP2() {
super.visitLCMP2();
BINOPhelper(Binary.CMP_L.INSTANCE, jq_Primitive.INT, jq_Primitive.LONG, jq_Primitive.LONG, false);
}
public void visitFCMP2(byte op) {
super.visitFCMP2(op);
Binary o = op==CMP_L?(Binary)Binary.CMP_FL.INSTANCE:(Binary)Binary.CMP_FG.INSTANCE;
BINOPhelper(o, jq_Primitive.INT, jq_Primitive.FLOAT, jq_Primitive.FLOAT, false);
}
public void visitDCMP2(byte op) {
super.visitDCMP2(op);
Binary o = op==CMP_L?(Binary)Binary.CMP_DL.INSTANCE:(Binary)Binary.CMP_DG.INSTANCE;
BINOPhelper(o, jq_Primitive.INT, jq_Primitive.DOUBLE, jq_Primitive.DOUBLE, false);
}
public void visitIF(byte op, int target) {
super.visitIF(op, target);
Operand op0 = current_state.pop_I();
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(target).id];
ConditionOperand cond = new ConditionOperand(op);
Quad q = IntIfCmp.create(quad_cfg.getNewQuadID(), IntIfCmp.IFCMP_I.INSTANCE, op0, new IConstOperand(0), cond, new TargetOperand(target_bb));
appendQuad(q);
}
public void visitIFREF(byte op, int target) {
super.visitIFREF(op, target);
// could be A or R
Operand op0 = current_state.pop();
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(target).id];
ConditionOperand cond = new ConditionOperand(op);
jq_Type t = getTypeOf(op0);
IntIfCmp operator = t.isAddressType()?(IntIfCmp)IntIfCmp.IFCMP_P.INSTANCE:IntIfCmp.IFCMP_A.INSTANCE;
Operand op1 = t.isAddressType()?(Operand)new PConstOperand(null):new AConstOperand(null);
Quad q = IntIfCmp.create(quad_cfg.getNewQuadID(), operator, op0, op1, cond, new TargetOperand(target_bb));
appendQuad(q);
}
public void visitIFCMP(byte op, int target) {
super.visitIFCMP(op, target);
Operand op1 = current_state.pop_I();
Operand op0 = current_state.pop_I();
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(target).id];
ConditionOperand cond = new ConditionOperand(op);
Quad q = IntIfCmp.create(quad_cfg.getNewQuadID(), IntIfCmp.IFCMP_I.INSTANCE, op0, op1, cond, new TargetOperand(target_bb));
appendQuad(q);
}
public void visitIFREFCMP(byte op, int target) {
super.visitIFREFCMP(op, target);
// could be A or R
Operand op1 = current_state.pop();
// could be A or R
Operand op0 = current_state.pop();
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(target).id];
ConditionOperand cond = new ConditionOperand(op);
jq_Type t1 = getTypeOf(op1);
jq_Type t0 = getTypeOf(op0);
IntIfCmp operator;
if (t1.isAddressType()) {
if (!t0.isAddressType() && t0 != jq_Reference.jq_NullType.NULL_TYPE) {
Assert.UNREACHABLE("comparing address type "+op1+" with non-address type "+op0);
}
operator = IntIfCmp.IFCMP_P.INSTANCE;
} else if (t0.isAddressType()) {
if (t1 != jq_Reference.jq_NullType.NULL_TYPE) {
Assert.UNREACHABLE("comparing address type "+op0+" with non-address type "+op1);
}
operator = IntIfCmp.IFCMP_P.INSTANCE;
} else {
operator = IntIfCmp.IFCMP_A.INSTANCE;
}
Quad q = IntIfCmp.create(quad_cfg.getNewQuadID(), operator, op0, op1, cond, new TargetOperand(target_bb));
appendQuad(q);
}
public void visitGOTO(int target) {
super.visitGOTO(target);
this.uncond_branch = true;
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(target).id];
Quad q = Goto.create(quad_cfg.getNewQuadID(), Goto.GOTO.INSTANCE, new TargetOperand(target_bb));
appendQuad(q);
}
java.util.Map jsr_states = new java.util.HashMap();
void setJSRState(Compil3r.BytecodeAnalysis.BasicBlock bb, AbstractState s) {
jsr_states.put(bb, s.copyAfterJSR());
}
AbstractState getJSRState(Compil3r.BytecodeAnalysis.BasicBlock bb) {
return (AbstractState)jsr_states.get(bb);
}
public void visitJSR(int target) {
super.visitJSR(target);
this.uncond_branch = true;
Compil3r.BytecodeAnalysis.BasicBlock target_bcbb = bc_cfg.getBasicBlockByBytecodeIndex(target);
BasicBlock target_bb = quad_bbs[target_bcbb.id];
BasicBlock successor_bb = quad_bbs[bc_bb.id+1];
Compil3r.BytecodeAnalysis.JSRInfo jsrinfo = bc_cfg.getJSRInfo(target_bcbb);
if (jsrinfo == null) {
if (TRACE) out.println("jsr with no ret! converting to GOTO.");
// push a null constant in place of the return address,
// in case the return address is stored into a local variable.
current_state.push_A(new AConstOperand(null));
saveStackIntoRegisters();
Quad q = Goto.create(quad_cfg.getNewQuadID(), Goto.GOTO.INSTANCE, new TargetOperand(target_bb));
appendQuad(q);
return;
}
Assert._assert(quad_bbs[jsrinfo.entry_block.id] == target_bb);
BasicBlock last_bb = quad_bbs[jsrinfo.exit_block.id];
JSRInfo q_jsrinfo = new JSRInfo(target_bb, last_bb, jsrinfo.changedLocals);
this.quad_cfg.addJSRInfo(q_jsrinfo);
saveStackIntoRegisters();
RegisterOperand op0 = getStackRegister(jq_ReturnAddressType.INSTANCE);
Quad q = Jsr.create(quad_cfg.getNewQuadID(), Jsr.JSR.INSTANCE, op0, new TargetOperand(target_bb), new TargetOperand(successor_bb));
appendQuad(q);
Compil3r.BytecodeAnalysis.BasicBlock next_bb = bc_cfg.getBasicBlock(bc_bb.id+1);
Compil3r.BytecodeAnalysis.BasicBlock ret_bb = jsrinfo.exit_block;
setJSRState(next_bb, current_state);
// we need to visit the ret block even when it has been visited before,
// so that when we visit its ret instruction, next_bb will get updated
// with the new jsr state
if (visited[ret_bb.id]) {
if (TRACE) out.println("marking ret bb "+ret_bb+" for regeneration.");
if (!regenerate.contains(ret_bb)) regenerate.add(ret_bb);
}
current_state.push(op0.copy());
}
public void visitRET(int i) {
super.visitRET(i);
this.uncond_branch = true;
saveStackIntoRegisters();
RegisterOperand op0 = makeLocal(i, jq_ReturnAddressType.INSTANCE);
Quad q = Ret.create(quad_cfg.getNewQuadID(), Ret.RET.INSTANCE, op0);
appendQuad(q);
current_state.setLocal(i, null);
endsWithRET = true;
// get JSR info
Compil3r.BytecodeAnalysis.JSRInfo jsrinfo = bc_cfg.getJSRInfo(bc_bb);
// find all callers to this subroutine.
for (int j=0; j<bc_bb.getNumberOfSuccessors(); ++j) {
Compil3r.BytecodeAnalysis.BasicBlock caller_next = bc_bb.getSuccessor(j);
AbstractState caller_state = getJSRState(caller_next);
if (caller_state == null) {
if (TRACE) out.println("haven't seen jsr call from "+caller_next+" yet.");
if (!regenerate.contains(caller_next)) regenerate.add(caller_next);
continue;
}
caller_state.mergeAfterJSR(jsrinfo.changedLocals, current_state);
if (start_states[caller_next.id] == null) {
if (TRACE) out.println("Copying jsr state to "+caller_next);
start_states[caller_next.id] = caller_state.copy();
if (visited[caller_next.id]) {
if (TRACE) out.println("must regenerate code for "+caller_next);
if (!regenerate.contains(caller_next)) regenerate.add(caller_next);
}
} else {
if (TRACE) out.println("Merging jsr state with "+caller_next);
if (start_states[caller_next.id].merge(caller_state, rf)) {
if (TRACE) out.println("in set of "+caller_next+" changed");
if (visited[caller_next.id]) {
if (TRACE) out.println("must regenerate code for "+caller_next);
if (!regenerate.contains(caller_next)) regenerate.add(caller_next);
}
}
}
}
}
public void visitTABLESWITCH(int default_target, int low, int high, int[] targets) {
super.visitTABLESWITCH(default_target, low, high, targets);
this.uncond_branch = true;
Operand op0 = current_state.pop_I();
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(default_target).id];
Assert._assert(high-low+1 == targets.length);
Quad q = TableSwitch.create(quad_cfg.getNewQuadID(), TableSwitch.TABLESWITCH.INSTANCE, op0, new IConstOperand(low),
new TargetOperand(target_bb), targets.length);
for (int i = 0; i < targets.length; ++i) {
target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(targets[i]).id];
TableSwitch.setTarget(q, i, target_bb);
}
appendQuad(q);
}
public void visitLOOKUPSWITCH(int default_target, int[] values, int[] targets) {
super.visitLOOKUPSWITCH(default_target, values, targets);
this.uncond_branch = true;
Operand op0 = current_state.pop_I();
saveStackIntoRegisters();
BasicBlock target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(default_target).id];
Quad q = LookupSwitch.create(quad_cfg.getNewQuadID(), LookupSwitch.LOOKUPSWITCH.INSTANCE, op0, new TargetOperand(target_bb), values.length);
for (int i = 0; i < values.length; ++i) {
LookupSwitch.setMatch(q, i, values[i]);
target_bb = quad_bbs[bc_cfg.getBasicBlockByBytecodeIndex(targets[i]).id];
LookupSwitch.setTarget(q, i, target_bb);
}
appendQuad(q);
}
public void visitIRETURN() {
super.visitIRETURN();
this.uncond_branch = true;
Operand op0 = current_state.pop_I();
Quad q = Return.create(quad_cfg.getNewQuadID(), Return.RETURN_I.INSTANCE, op0);
appendQuad(q);
current_state.clearStack();
}
public void visitLRETURN() {
super.visitLRETURN();
this.uncond_branch = true;
Operand op0 = current_state.pop_L();
Quad q = Return.create(quad_cfg.getNewQuadID(), Return.RETURN_L.INSTANCE, op0);
appendQuad(q);
current_state.clearStack();
}
public void visitFRETURN() {
super.visitFRETURN();
this.uncond_branch = true;
Operand op0 = current_state.pop_F();
Quad q = Return.create(quad_cfg.getNewQuadID(), Return.RETURN_F.INSTANCE, op0);
appendQuad(q);
current_state.clearStack();
}
public void visitDRETURN() {
super.visitDRETURN();
this.uncond_branch = true;
Operand op0 = current_state.pop_D();
Quad q = Return.create(quad_cfg.getNewQuadID(), Return.RETURN_D.INSTANCE, op0);
appendQuad(q);
current_state.clearStack();
}
public void visitARETURN() {
super.visitARETURN();
this.uncond_branch = true;
// could be A or R
Operand op0 = current_state.pop();
jq_Type t = getTypeOf(op0);
Return operator;
if (method.getReturnType().isAddressType()) {
operator = Return.RETURN_P.INSTANCE;
Assert._assert(t.isAddressType() ||
t == jq_Reference.jq_NullType.NULL_TYPE ||
t.isSubtypeOf(Address._class), t.toString());
} else {
operator = t.isAddressType()?(Return)Return.RETURN_P.INSTANCE:Return.RETURN_A.INSTANCE;
}
Quad q = Return.create(quad_cfg.getNewQuadID(), operator, op0);
appendQuad(q);
current_state.clearStack();
}
public void visitVRETURN() {
super.visitVRETURN();
this.uncond_branch = true;
Quad q = Return.create(quad_cfg.getNewQuadID(), Return.RETURN_V.INSTANCE);
appendQuad(q);
current_state.clearStack();
}
private void GETSTATIChelper(jq_StaticField f, Getstatic oper1, Getstatic oper2) {
boolean dynlink = f.needsDynamicLink(method);
if (!dynlink) try { f = resolve(f); } catch (Error e) { }
Getstatic operator = dynlink?oper1:oper2;
jq_Type t = f.getType();
RegisterOperand op0 = getStackRegister(t);
Quad q = Getstatic.create(quad_cfg.getNewQuadID(), operator, op0, new FieldOperand(f));
appendQuad(q);
current_state.push(op0.copy(), t);
}
public void visitIGETSTATIC(jq_StaticField f) {
super.visitIGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_I_DYNLINK.INSTANCE, Getstatic.GETSTATIC_I.INSTANCE);
}
public void visitLGETSTATIC(jq_StaticField f) {
super.visitLGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_L_DYNLINK.INSTANCE, Getstatic.GETSTATIC_L.INSTANCE);
}
public void visitFGETSTATIC(jq_StaticField f) {
super.visitFGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_F_DYNLINK.INSTANCE, Getstatic.GETSTATIC_F.INSTANCE);
}
public void visitDGETSTATIC(jq_StaticField f) {
super.visitDGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_D_DYNLINK.INSTANCE, Getstatic.GETSTATIC_D.INSTANCE);
}
public void visitAGETSTATIC(jq_StaticField f) {
super.visitAGETSTATIC(f);
Getstatic operator1 = f.getType().isAddressType()?(Getstatic)Getstatic.GETSTATIC_P_DYNLINK.INSTANCE:Getstatic.GETSTATIC_A_DYNLINK.INSTANCE;
Getstatic operator2 = f.getType().isAddressType()?(Getstatic)Getstatic.GETSTATIC_P.INSTANCE:Getstatic.GETSTATIC_A.INSTANCE;
GETSTATIChelper(f, operator1, operator2);
}
public void visitZGETSTATIC(jq_StaticField f) {
super.visitZGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_Z_DYNLINK.INSTANCE, Getstatic.GETSTATIC_Z.INSTANCE);
}
public void visitBGETSTATIC(jq_StaticField f) {
super.visitBGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_B_DYNLINK.INSTANCE, Getstatic.GETSTATIC_B.INSTANCE);
}
public void visitCGETSTATIC(jq_StaticField f) {
super.visitCGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_C_DYNLINK.INSTANCE, Getstatic.GETSTATIC_C.INSTANCE);
}
public void visitSGETSTATIC(jq_StaticField f) {
super.visitSGETSTATIC(f);
GETSTATIChelper(f, Getstatic.GETSTATIC_S_DYNLINK.INSTANCE, Getstatic.GETSTATIC_S.INSTANCE);
}
private void PUTSTATIChelper(jq_StaticField f, Putstatic oper1, Putstatic oper2) {
boolean dynlink = f.needsDynamicLink(method);
if (!dynlink) try { f = resolve(f); } catch (Error e) { }
Putstatic operator = dynlink?oper1:oper2;
jq_Type t = f.getType();
Operand op0 = current_state.pop(t);
Quad q = Putstatic.create(quad_cfg.getNewQuadID(), operator, op0, new FieldOperand(f));
appendQuad(q);
}
public void visitIPUTSTATIC(jq_StaticField f) {
super.visitIPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_I_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_I.INSTANCE);
}
public void visitLPUTSTATIC(jq_StaticField f) {
super.visitLPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_L_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_L.INSTANCE);
}
public void visitFPUTSTATIC(jq_StaticField f) {
super.visitFPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_F_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_F.INSTANCE);
}
public void visitDPUTSTATIC(jq_StaticField f) {
super.visitDPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_D_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_D.INSTANCE);
}
public void visitAPUTSTATIC(jq_StaticField f) {
super.visitAPUTSTATIC(f);
Putstatic operator1 = f.getType().isAddressType()?(Putstatic)Putstatic.PUTSTATIC_P_DYNLINK.INSTANCE:Putstatic.PUTSTATIC_A_DYNLINK.INSTANCE;
Putstatic operator2 = f.getType().isAddressType()?(Putstatic)Putstatic.PUTSTATIC_P.INSTANCE:Putstatic.PUTSTATIC_A.INSTANCE;
PUTSTATIChelper(f, operator1, operator2);
}
public void visitZPUTSTATIC(jq_StaticField f) {
super.visitZPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_Z_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_Z.INSTANCE);
}
public void visitBPUTSTATIC(jq_StaticField f) {
super.visitBPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_B_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_B.INSTANCE);
}
public void visitCPUTSTATIC(jq_StaticField f) {
super.visitCPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_C_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_C.INSTANCE);
}
public void visitSPUTSTATIC(jq_StaticField f) {
super.visitSPUTSTATIC(f);
PUTSTATIChelper(f, Putstatic.PUTSTATIC_S_DYNLINK.INSTANCE, Putstatic.PUTSTATIC_S.INSTANCE);
}
private void GETFIELDhelper(jq_InstanceField f, Getfield oper1, Getfield oper2) {
boolean dynlink = f.needsDynamicLink(method);
if (!dynlink) try { f = resolve(f); } catch (Error e) { }
Operand op1 = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(op1)) {
if (TRACE) System.out.println("Null check triggered on "+op1);
return;
}
jq_Type t = f.getType();
RegisterOperand op0 = getStackRegister(t);
Getfield operator = dynlink?oper1:oper2;
Quad q = Getfield.create(quad_cfg.getNewQuadID(), operator, op0, op1, new FieldOperand(f), getCurrentGuard());
appendQuad(q);
current_state.push(op0.copy(), t);
}
public void visitIGETFIELD(jq_InstanceField f) {
super.visitIGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_I_DYNLINK.INSTANCE, Getfield.GETFIELD_I.INSTANCE);
}
public void visitLGETFIELD(jq_InstanceField f) {
super.visitLGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_L_DYNLINK.INSTANCE, Getfield.GETFIELD_L.INSTANCE);
}
public void visitFGETFIELD(jq_InstanceField f) {
super.visitFGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_F_DYNLINK.INSTANCE, Getfield.GETFIELD_F.INSTANCE);
}
public void visitDGETFIELD(jq_InstanceField f) {
super.visitDGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_D_DYNLINK.INSTANCE, Getfield.GETFIELD_D.INSTANCE);
}
public void visitAGETFIELD(jq_InstanceField f) {
super.visitAGETFIELD(f);
Getfield operator1 = f.getType().isAddressType()?(Getfield)Getfield.GETFIELD_P_DYNLINK.INSTANCE:Getfield.GETFIELD_A_DYNLINK.INSTANCE;
Getfield operator2 = f.getType().isAddressType()?(Getfield)Getfield.GETFIELD_P.INSTANCE:Getfield.GETFIELD_A.INSTANCE;
GETFIELDhelper(f, operator1, operator2);
}
public void visitBGETFIELD(jq_InstanceField f) {
super.visitBGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_B_DYNLINK.INSTANCE, Getfield.GETFIELD_B.INSTANCE);
}
public void visitCGETFIELD(jq_InstanceField f) {
super.visitCGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_C_DYNLINK.INSTANCE, Getfield.GETFIELD_C.INSTANCE);
}
public void visitSGETFIELD(jq_InstanceField f) {
super.visitSGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_S_DYNLINK.INSTANCE, Getfield.GETFIELD_S.INSTANCE);
}
public void visitZGETFIELD(jq_InstanceField f) {
super.visitZGETFIELD(f);
GETFIELDhelper(f, Getfield.GETFIELD_Z_DYNLINK.INSTANCE, Getfield.GETFIELD_Z.INSTANCE);
}
private void PUTFIELDhelper(jq_InstanceField f, Putfield oper1, Putfield oper2) {
boolean dynlink = f.needsDynamicLink(method);
if (!dynlink) try { f = resolve(f); } catch (Error e) { }
Operand op0 = current_state.pop(f.getType());
Operand op1 = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(op1)) {
if (TRACE) System.out.println("Null check triggered on "+op1);
return;
}
Putfield operator = dynlink?oper1:oper2;
Quad q = Putfield.create(quad_cfg.getNewQuadID(), operator, op1, new FieldOperand(f), op0, getCurrentGuard());
appendQuad(q);
}
public void visitIPUTFIELD(jq_InstanceField f) {
super.visitIPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_I_DYNLINK.INSTANCE, Putfield.PUTFIELD_I.INSTANCE);
}
public void visitLPUTFIELD(jq_InstanceField f) {
super.visitLPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_L_DYNLINK.INSTANCE, Putfield.PUTFIELD_L.INSTANCE);
}
public void visitFPUTFIELD(jq_InstanceField f) {
super.visitFPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_F_DYNLINK.INSTANCE, Putfield.PUTFIELD_F.INSTANCE);
}
public void visitDPUTFIELD(jq_InstanceField f) {
super.visitDPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_D_DYNLINK.INSTANCE, Putfield.PUTFIELD_D.INSTANCE);
}
public void visitAPUTFIELD(jq_InstanceField f) {
super.visitAPUTFIELD(f);
Putfield operator1 = f.getType().isAddressType()?(Putfield)Putfield.PUTFIELD_P_DYNLINK.INSTANCE:Putfield.PUTFIELD_A_DYNLINK.INSTANCE;
Putfield operator2 = f.getType().isAddressType()?(Putfield)Putfield.PUTFIELD_P.INSTANCE:Putfield.PUTFIELD_A.INSTANCE;
PUTFIELDhelper(f, operator1, operator2);
}
public void visitBPUTFIELD(jq_InstanceField f) {
super.visitBPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_B_DYNLINK.INSTANCE, Putfield.PUTFIELD_B.INSTANCE);
}
public void visitCPUTFIELD(jq_InstanceField f) {
super.visitCPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_C_DYNLINK.INSTANCE, Putfield.PUTFIELD_C.INSTANCE);
}
public void visitSPUTFIELD(jq_InstanceField f) {
super.visitSPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_S_DYNLINK.INSTANCE, Putfield.PUTFIELD_S.INSTANCE);
}
public void visitZPUTFIELD(jq_InstanceField f) {
super.visitZPUTFIELD(f);
PUTFIELDhelper(f, Putfield.PUTFIELD_Z_DYNLINK.INSTANCE, Putfield.PUTFIELD_Z.INSTANCE);
}
public static final Utf8 peek = Utf8.get("peek");
public static final Utf8 peek1 = Utf8.get("peek1");
public static final Utf8 peek2 = Utf8.get("peek2");
public static final Utf8 peek4 = Utf8.get("peek4");
public static final Utf8 peek8 = Utf8.get("peek8");
public static final Utf8 poke = Utf8.get("poke");
public static final Utf8 poke1 = Utf8.get("poke1");
public static final Utf8 poke2 = Utf8.get("poke2");
public static final Utf8 poke4 = Utf8.get("poke4");
public static final Utf8 poke8 = Utf8.get("poke8");
public static final Utf8 offset = Utf8.get("offset");
public static final Utf8 align = Utf8.get("align");
public static final Utf8 difference = Utf8.get("difference");
public static final Utf8 isNull = Utf8.get("isNull");
public static final Utf8 addressOf = Utf8.get("addressOf");
public static final Utf8 address32 = Utf8.get("address32");
public static final Utf8 asObject = Utf8.get("asObject");
public static final Utf8 asReferenceType = Utf8.get("asReferenceType");
public static final Utf8 to32BitValue = Utf8.get("to32BitValue");
public static final Utf8 stringRep = Utf8.get("stringRep");
public static final Utf8 getNull = Utf8.get("getNull");
public static final Utf8 size = Utf8.get("size");
public static final Utf8 getBasePointer = Utf8.get("getBasePointer");
public static final Utf8 getStackPointer = Utf8.get("getStackPointer");
public static final Utf8 alloca = Utf8.get("alloca");
public static final Utf8 atomicAdd = Utf8.get("atomicAdd");
public static final Utf8 atomicSub = Utf8.get("atomicSub");
public static final Utf8 atomicCas4 = Utf8.get("atomicCas4");
public static final Utf8 atomicAnd = Utf8.get("atomicAnd");
public static final Utf8 min = Utf8.get("min");
public static final Utf8 max = Utf8.get("max");
private void ADDRESShelper(jq_Method m, Invoke oper) {
Utf8 name = m.getName();
Quad q;
if (name == poke) {
Operand val = current_state.pop_P();
Operand loc = current_state.pop_P();
q = MemStore.create(quad_cfg.getNewQuadID(), MemStore.POKE_P.INSTANCE, loc, val);
} else if (name == poke1) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
q = MemStore.create(quad_cfg.getNewQuadID(), MemStore.POKE_1.INSTANCE, loc, val);
} else if (name == poke2) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
q = MemStore.create(quad_cfg.getNewQuadID(), MemStore.POKE_2.INSTANCE, loc, val);
} else if (name == poke4) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
q = MemStore.create(quad_cfg.getNewQuadID(), MemStore.POKE_4.INSTANCE, loc, val);
} else if (name == poke8) {
Operand val = current_state.pop_L();
Operand loc = current_state.pop_P();
q = MemStore.create(quad_cfg.getNewQuadID(), MemStore.POKE_8.INSTANCE, loc, val);
} else if (name == peek) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(Address._class);
q = MemLoad.create(quad_cfg.getNewQuadID(), MemLoad.PEEK_P.INSTANCE, res, loc);
current_state.push_P(res);
} else if (name == peek1) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.BYTE);
q = MemLoad.create(quad_cfg.getNewQuadID(), MemLoad.PEEK_1.INSTANCE, res, loc);
current_state.push_I(res);
} else if (name == peek2) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.SHORT);
q = MemLoad.create(quad_cfg.getNewQuadID(), MemLoad.PEEK_2.INSTANCE, res, loc);
current_state.push_I(res);
} else if (name == peek4) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.INT);
q = MemLoad.create(quad_cfg.getNewQuadID(), MemLoad.PEEK_4.INSTANCE, res, loc);
current_state.push_I(res);
} else if (name == peek8) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.LONG);
q = MemLoad.create(quad_cfg.getNewQuadID(), MemLoad.PEEK_8.INSTANCE, res, loc);
current_state.push_L(res);
} else if (name == offset) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(Address._class);
q = Binary.create(quad_cfg.getNewQuadID(), Binary.ADD_P.INSTANCE, res, loc, val);
current_state.push_P(res);
} else if (name == align) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(Address._class);
q = Binary.create(quad_cfg.getNewQuadID(), Binary.ALIGN_P.INSTANCE, res, loc, val);
current_state.push_P(res);
} else if (name == difference) {
Operand val = current_state.pop_P();
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.INT);
q = Binary.create(quad_cfg.getNewQuadID(), Binary.SUB_P.INSTANCE, res, loc, val);
current_state.push_I(res);
} else if (name == alloca) {
Operand amt = current_state.pop_I();
RegisterOperand res = getStackRegister(StackAddress._class);
q = Special.create(quad_cfg.getNewQuadID(), Special.ALLOCA.INSTANCE, res, amt);
current_state.push_P(res);
} else if (name == isNull) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.BOOLEAN);
q = Unary.create(quad_cfg.getNewQuadID(), Unary.ISNULL_P.INSTANCE, res, loc);
current_state.push_I(res);
} else if (name == addressOf) {
Operand loc = current_state.pop_A();
RegisterOperand res = getStackRegister(Address._class);
q = Unary.create(quad_cfg.getNewQuadID(), Unary.OBJECT_2ADDRESS.INSTANCE, res, loc);
current_state.push_P(res);
} else if (name == address32) {
Operand loc = current_state.pop_I();
RegisterOperand res = getStackRegister(Address._class);
q = Unary.create(quad_cfg.getNewQuadID(), Unary.INT_2ADDRESS.INSTANCE, res, loc);
current_state.push_P(res);
} else if (name == asObject) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(PrimordialClassLoader.getJavaLangObject());
q = Unary.create(quad_cfg.getNewQuadID(), Unary.ADDRESS_2OBJECT.INSTANCE, res, loc);
current_state.push_A(res);
} else if (name == asReferenceType) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Reference._class);
q = Unary.create(quad_cfg.getNewQuadID(), Unary.ADDRESS_2OBJECT.INSTANCE, res, loc);
current_state.push_A(res);
} else if (name == to32BitValue) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.INT);
q = Unary.create(quad_cfg.getNewQuadID(), Unary.ADDRESS_2INT.INSTANCE, res, loc);
current_state.push_I(res);
} else if (name == stringRep) {
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.INT);
q = Unary.create(quad_cfg.getNewQuadID(), Unary.ADDRESS_2INT.INSTANCE, res, loc);
current_state.push_I(res);
appendQuad(q);
jq_Class k = (jq_Class) PrimordialClassLoader.loader.getOrCreateBSType("LUtil/Strings;");
jq_StaticMethod sm = k.getOrCreateStaticMethod("hex8", "(I)Ljava/lang/String;");
INVOKEhelper(Invoke.INVOKESTATIC_A.INSTANCE, sm, sm.getReturnType(), false);
return;
} else if (name == getNull) {
PConstOperand p = new PConstOperand(null);
current_state.push_P(p);
return;
} else if (name == size) {
IConstOperand p = new IConstOperand(HeapAddress.size());
current_state.push_I(p);
return;
} else if (name == getBasePointer) {
RegisterOperand res = getStackRegister(StackAddress._class);
q = Special.create(quad_cfg.getNewQuadID(), Special.GET_BASE_POINTER.INSTANCE, res);
current_state.push_P(res);
} else if (name == getStackPointer) {
RegisterOperand res = getStackRegister(StackAddress._class);
q = Special.create(quad_cfg.getNewQuadID(), Special.GET_STACK_POINTER.INSTANCE, res);
current_state.push_P(res);
} else if (name == atomicAdd) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
q = Special.create(quad_cfg.getNewQuadID(), Special.ATOMICADD_I.INSTANCE, loc, val);
} else if (name == atomicSub) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
q = Special.create(quad_cfg.getNewQuadID(), Special.ATOMICSUB_I.INSTANCE, loc, val);
} else if (name == atomicAnd) {
Operand val = current_state.pop_I();
Operand loc = current_state.pop_P();
q = Special.create(quad_cfg.getNewQuadID(), Special.ATOMICAND_I.INSTANCE, loc, val);
} else if (name == atomicCas4) {
Operand val2 = current_state.pop_I();
Operand val1 = current_state.pop_I();
Operand loc = current_state.pop_P();
RegisterOperand res = getStackRegister(jq_Primitive.INT);
q = Special.create(quad_cfg.getNewQuadID(), Special.ATOMICCAS4.INSTANCE, res, loc, val1, val2);
current_state.push_I(res);
} else {
// TODO
INVOKEhelper(oper, m, m.getReturnType(), false);
return;
}
appendQuad(q);
mergeStateWithAllExHandlers(false);
}
private void UNSAFEhelper(jq_Method m, Invoke oper) {
if (_unsafe.handleMethod(this, quad_cfg, current_state, m, oper)) {
mergeStateWithAllExHandlers(false);
if (_unsafe.endsBB(m)) {
endBasicBlock = true;
}
} else {
// TODO
INVOKEhelper(oper, m, m.getReturnType(), false);
return;
}
}
private void INVOKEhelper(Invoke oper, jq_Method f, jq_Type returnType, boolean instance_call) {
jq_Type[] paramTypes = f.getParamTypes();
RegisterOperand result;
if (returnType == jq_Primitive.VOID) result = null;
else result = getStackRegister(returnType, f.getParamWords()-1);
Quad q = Invoke.create(quad_cfg.getNewQuadID(), oper, result, new MethodOperand(f), paramTypes.length);
Operand op = null;
for (int i = paramTypes.length; --i >= 0; ) {
jq_Type ptype = paramTypes[i];
op = current_state.pop(ptype);
RegisterOperand rop;
if (op instanceof RegisterOperand) rop = (RegisterOperand)op;
else {
rop = getStackRegister(ptype);
Quad q2 = Move.create(quad_cfg.getNewQuadID(), Move.getMoveOp(ptype), rop, op);
appendQuad(q2);
}
Invoke.setParam(q, i, rop);
}
clearCurrentGuard();
if (instance_call && performNullCheck(op)) {
if (TRACE) System.out.println("Null check triggered on "+op);
return;
}
appendQuad(q);
mergeStateWithAllExHandlers(false);
if (result != null) current_state.push(result, returnType);
}
public void visitIINVOKE(byte op, jq_Method f) {
super.visitIINVOKE(op, f);
if (_unsafe.isUnsafe(f)) {
UNSAFEhelper(f, Invoke.INVOKESTATIC_I.INSTANCE);
return;
}
if (f.getDeclaringClass().isAddressType()) {
ADDRESShelper(f, f.isStatic()?(Invoke)Invoke.INVOKESTATIC_I.INSTANCE:Invoke.INVOKEVIRTUAL_I.INSTANCE);
return;
}
Invoke oper;
boolean instance_call;
switch (op) {
case INVOKE_VIRTUAL:
instance_call = true;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKEVIRTUAL_I_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKEVIRTUAL_I.INSTANCE;
try { f = (jq_InstanceMethod)resolve(f); } catch (Error e) { }
}
//f.getDeclaringClass().load();
//jq.Assert(!f.getDeclaringClass().isInterface());
break;
case INVOKE_STATIC:
instance_call = false;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESTATIC_I_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKESTATIC_I.INSTANCE;
try { f = (jq_StaticMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_SPECIAL:
instance_call = true;
Assert._assert(f instanceof jq_InstanceMethod);
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESPECIAL_I_DYNLINK.INSTANCE;
else {
f = jq_Class.getInvokespecialTarget(clazz, (jq_InstanceMethod)f);
oper = Invoke.INVOKESTATIC_I.INSTANCE;
}
break;
case INVOKE_INTERFACE:
instance_call = true;
oper = Invoke.INVOKEINTERFACE_I.INSTANCE;
break;
default:
throw new InternalError();
}
INVOKEhelper(oper, f, jq_Primitive.INT, instance_call);
}
public void visitLINVOKE(byte op, jq_Method f) {
super.visitLINVOKE(op, f);
if (_unsafe.isUnsafe(f)) {
UNSAFEhelper(f, Invoke.INVOKESTATIC_L.INSTANCE);
return;
}
if (f.getDeclaringClass().isAddressType()) {
ADDRESShelper(f, f.isStatic()?(Invoke)Invoke.INVOKESTATIC_L.INSTANCE:Invoke.INVOKEVIRTUAL_L.INSTANCE);
return;
}
Invoke oper;
boolean instance_call;
switch (op) {
case INVOKE_VIRTUAL:
instance_call = true;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKEVIRTUAL_L_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKEVIRTUAL_L.INSTANCE;
try { f = (jq_InstanceMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_STATIC:
instance_call = false;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESTATIC_L_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKESTATIC_L.INSTANCE;
try { f = (jq_StaticMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_SPECIAL:
instance_call = true;
Assert._assert(f instanceof jq_InstanceMethod);
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESPECIAL_L_DYNLINK.INSTANCE;
else {
f = jq_Class.getInvokespecialTarget(clazz, (jq_InstanceMethod)f);
oper = Invoke.INVOKESTATIC_L.INSTANCE;
}
break;
case INVOKE_INTERFACE:
instance_call = true;
oper = Invoke.INVOKEINTERFACE_L.INSTANCE;
break;
default:
throw new InternalError();
}
INVOKEhelper(oper, f, jq_Primitive.LONG, instance_call);
}
public void visitFINVOKE(byte op, jq_Method f) {
super.visitFINVOKE(op, f);
if (_unsafe.isUnsafe(f)) {
UNSAFEhelper(f, Invoke.INVOKESTATIC_F.INSTANCE);
return;
}
if (f.getDeclaringClass().isAddressType()) {
ADDRESShelper(f, f.isStatic()?(Invoke)Invoke.INVOKESTATIC_F.INSTANCE:Invoke.INVOKEVIRTUAL_F.INSTANCE);
return;
}
Invoke oper;
boolean instance_call;
switch (op) {
case INVOKE_VIRTUAL:
instance_call = true;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKEVIRTUAL_F_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKEVIRTUAL_F.INSTANCE;
try { f = (jq_InstanceMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_STATIC:
instance_call = false;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESTATIC_F_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKESTATIC_F.INSTANCE;
try { f = (jq_StaticMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_SPECIAL:
instance_call = true;
Assert._assert(f instanceof jq_InstanceMethod);
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESPECIAL_F_DYNLINK.INSTANCE;
else {
f = jq_Class.getInvokespecialTarget(clazz, (jq_InstanceMethod)f);
oper = Invoke.INVOKESTATIC_F.INSTANCE;
}
break;
case INVOKE_INTERFACE:
instance_call = true;
oper = Invoke.INVOKEINTERFACE_F.INSTANCE;
break;
default:
throw new InternalError();
}
INVOKEhelper(oper, f, jq_Primitive.FLOAT, instance_call);
}
public void visitDINVOKE(byte op, jq_Method f) {
super.visitDINVOKE(op, f);
if (_unsafe.isUnsafe(f)) {
UNSAFEhelper(f, Invoke.INVOKESTATIC_D.INSTANCE);
return;
}
if (f.getDeclaringClass().isAddressType()) {
ADDRESShelper(f, f.isStatic()?(Invoke)Invoke.INVOKESTATIC_D.INSTANCE:Invoke.INVOKEVIRTUAL_D.INSTANCE);
return;
}
Invoke oper;
boolean instance_call;
switch (op) {
case INVOKE_VIRTUAL:
instance_call = true;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKEVIRTUAL_D_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKEVIRTUAL_D.INSTANCE;
try { f = (jq_InstanceMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_STATIC:
instance_call = false;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESTATIC_D_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKESTATIC_D.INSTANCE;
try { f = (jq_StaticMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_SPECIAL:
instance_call = true;
Assert._assert(f instanceof jq_InstanceMethod);
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESPECIAL_D_DYNLINK.INSTANCE;
else {
f = jq_Class.getInvokespecialTarget(clazz, (jq_InstanceMethod)f);
oper = Invoke.INVOKESTATIC_D.INSTANCE;
}
break;
case INVOKE_INTERFACE:
instance_call = true;
oper = Invoke.INVOKEINTERFACE_D.INSTANCE;
break;
default:
throw new InternalError();
}
INVOKEhelper(oper, f, jq_Primitive.DOUBLE, instance_call);
}
public void visitAINVOKE(byte op, jq_Method f) {
super.visitAINVOKE(op, f);
if (_unsafe.isUnsafe(f)) {
UNSAFEhelper(f, f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKESTATIC_P.INSTANCE:Invoke.INVOKESTATIC_A.INSTANCE);
return;
}
if (f.getDeclaringClass().isAddressType()) {
Invoke oper;
if (f.isStatic()) {
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKESTATIC_P.INSTANCE:Invoke.INVOKESTATIC_A.INSTANCE;
} else {
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKEVIRTUAL_P.INSTANCE:Invoke.INVOKEVIRTUAL_A.INSTANCE;
}
ADDRESShelper(f, oper);
return;
}
Invoke oper;
boolean instance_call;
switch (op) {
case INVOKE_VIRTUAL:
instance_call = true;
if (f.needsDynamicLink(method))
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKEVIRTUAL_P_DYNLINK.INSTANCE:Invoke.INVOKEVIRTUAL_A_DYNLINK.INSTANCE;
else {
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKEVIRTUAL_P.INSTANCE:Invoke.INVOKEVIRTUAL_A.INSTANCE;
try { f = (jq_InstanceMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_STATIC:
instance_call = false;
if (f.needsDynamicLink(method))
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKESTATIC_P_DYNLINK.INSTANCE:Invoke.INVOKESTATIC_A_DYNLINK.INSTANCE;
else {
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKESTATIC_P.INSTANCE:Invoke.INVOKESTATIC_A.INSTANCE;
try { f = (jq_StaticMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_SPECIAL:
instance_call = true;
Assert._assert(f instanceof jq_InstanceMethod);
if (f.needsDynamicLink(method))
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKESPECIAL_P_DYNLINK.INSTANCE:Invoke.INVOKESPECIAL_A_DYNLINK.INSTANCE;
else {
f = jq_Class.getInvokespecialTarget(clazz, (jq_InstanceMethod)f);
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKESTATIC_P.INSTANCE:Invoke.INVOKESTATIC_A.INSTANCE;
}
break;
case INVOKE_INTERFACE:
instance_call = true;
oper = f.getReturnType().isAddressType()?(Invoke)Invoke.INVOKEINTERFACE_P.INSTANCE:Invoke.INVOKEINTERFACE_A.INSTANCE;
break;
default:
throw new InternalError();
}
INVOKEhelper(oper, f, f.getReturnType(), instance_call);
}
public void visitVINVOKE(byte op, jq_Method f) {
super.visitVINVOKE(op, f);
if (_unsafe.isUnsafe(f)) {
UNSAFEhelper(f, Invoke.INVOKESTATIC_V.INSTANCE);
return;
}
if (f.getDeclaringClass().isAddressType()) {
ADDRESShelper(f, f.isStatic()?(Invoke)Invoke.INVOKESTATIC_V.INSTANCE:Invoke.INVOKEVIRTUAL_V.INSTANCE);
return;
}
Invoke oper;
boolean instance_call;
switch (op) {
case INVOKE_VIRTUAL:
instance_call = true;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKEVIRTUAL_V_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKEVIRTUAL_V.INSTANCE;
try { f = (jq_InstanceMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_STATIC:
instance_call = false;
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESTATIC_V_DYNLINK.INSTANCE;
else {
oper = Invoke.INVOKESTATIC_V.INSTANCE;
try { f = (jq_StaticMethod)resolve(f); } catch (Error e) { }
}
break;
case INVOKE_SPECIAL:
instance_call = true;
Assert._assert(f instanceof jq_InstanceMethod);
if (f.needsDynamicLink(method))
oper = Invoke.INVOKESPECIAL_V_DYNLINK.INSTANCE;
else {
f = jq_Class.getInvokespecialTarget(clazz, (jq_InstanceMethod)f);
oper = Invoke.INVOKESTATIC_V.INSTANCE;
}
break;
case INVOKE_INTERFACE:
instance_call = true;
oper = Invoke.INVOKEINTERFACE_V.INSTANCE;
break;
default:
throw new InternalError();
}
INVOKEhelper(oper, f, f.getReturnType(), instance_call);
}
public void visitNEW(jq_Type f) {
super.visitNEW(f);
RegisterOperand res = getStackRegister(f);
Quad q = New.create(quad_cfg.getNewQuadID(), New.NEW.INSTANCE, res, new TypeOperand(f));
appendQuad(q);
current_state.push_A(res);
}
public void visitNEWARRAY(jq_Array f) {
super.visitNEWARRAY(f);
Operand size = current_state.pop_I();
RegisterOperand res = getStackRegister(f);
Quad q = NewArray.create(quad_cfg.getNewQuadID(), NewArray.NEWARRAY.INSTANCE, res, size, new TypeOperand(f));
appendQuad(q);
mergeStateWithAllExHandlers(false);
current_state.push_A(res);
}
public void visitCHECKCAST(jq_Type f) {
super.visitCHECKCAST(f);
Operand op = current_state.pop(); // could be P or A
RegisterOperand res = getStackRegister(f);
if (!f.isAddressType()) {
Quad q = CheckCast.create(quad_cfg.getNewQuadID(), CheckCast.CHECKCAST.INSTANCE, res, op, new TypeOperand(f));
appendQuad(q);
mergeStateWithAllExHandlers(false);
current_state.push_A(res);
} else {
current_state.push_P(res);
}
}
public void visitINSTANCEOF(jq_Type f) {
super.visitINSTANCEOF(f);
Assert._assert(!f.isAddressType(), method.toString());
Operand op = current_state.pop_A();
RegisterOperand res = getStackRegister(jq_Primitive.BOOLEAN);
Quad q = InstanceOf.create(quad_cfg.getNewQuadID(), InstanceOf.INSTANCEOF.INSTANCE, res, op, new TypeOperand(f));
appendQuad(q);
current_state.push_I(res);
}
public void visitARRAYLENGTH() {
super.visitARRAYLENGTH();
Operand op = current_state.pop_A();
clearCurrentGuard();
if (performNullCheck(op)) {
if (TRACE) System.out.println("Null check triggered on "+op);
return;
}
RegisterOperand res = getStackRegister(jq_Primitive.INT);
Quad q = ALength.create(quad_cfg.getNewQuadID(), ALength.ARRAYLENGTH.INSTANCE, res, op);
appendQuad(q);
current_state.push_I(res);
}
public void visitATHROW() {
super.visitATHROW();
this.uncond_branch = true;
Operand op0 = current_state.pop_A();
Quad q = Return.create(quad_cfg.getNewQuadID(), Return.THROW_A.INSTANCE, op0);
appendQuad(q);
current_state.clearStack();
}
public void visitMONITOR(byte op) {
super.visitMONITOR(op);
Operand op0 = current_state.pop_A();
Monitor oper = op==MONITOR_ENTER ? (Monitor)Monitor.MONITORENTER.INSTANCE : (Monitor)Monitor.MONITOREXIT.INSTANCE;
Quad q = Monitor.create(quad_cfg.getNewQuadID(), oper, op0);
appendQuad(q);
mergeStateWithAllExHandlers(false);
}
public void visitMULTINEWARRAY(jq_Type f, char dim) {
super.visitMULTINEWARRAY(f, dim);
RegisterOperand result = getStackRegister(f, dim-1);
Quad q = Invoke.create(quad_cfg.getNewQuadID(), Invoke.INVOKESTATIC_A.INSTANCE, result, new MethodOperand(Run_Time.Arrays._multinewarray), dim+2);
RegisterOperand rop = new RegisterOperand(rf.getNewStack(current_state.getStackSize(), jq_Primitive.INT), jq_Primitive.INT);
Quad q2 = Move.create(quad_cfg.getNewQuadID(), Move.MOVE_I.INSTANCE, rop, new IConstOperand(dim));
appendQuad(q2);
Invoke.setParam(q, 0, rop);
rop = new RegisterOperand(rf.getNewStack(current_state.getStackSize()+1, jq_Type._class), jq_Type._class);
q2 = Move.create(quad_cfg.getNewQuadID(), Move.MOVE_A.INSTANCE, rop, new AConstOperand(f));
appendQuad(q2);
Invoke.setParam(q, 1, rop);
for (int i=0; i<dim; ++i) {
Operand op = current_state.pop_I();
if (op instanceof RegisterOperand) rop = (RegisterOperand)op;
else {
rop = getStackRegister(jq_Primitive.INT);
q2 = Move.create(quad_cfg.getNewQuadID(), Move.MOVE_I.INSTANCE, rop, op);
appendQuad(q2);
}
Invoke.setParam(q, i+2, rop);
}
appendQuad(q);
mergeStateWithAllExHandlers(false);
current_state.push(result, f);
}
public static final boolean ELIM_NULL_CHECKS = true;
boolean performNullCheck(Operand op) {
if (op instanceof AConstOperand) {
Object val = ((AConstOperand)op).getValue();
if (val != null) {
setCurrentGuard(new UnnecessaryGuardOperand());
return false;
} else {
Quad q = NullCheck.create(quad_cfg.getNewQuadID(), NullCheck.NULL_CHECK.INSTANCE, null, op);
appendQuad(q);
if (false) {
endBasicBlock = true;
mergeStateWithNullPtrExHandler(true);
return true;
} else {
mergeStateWithNullPtrExHandler(false);
return false;
}
}
}
RegisterOperand rop = (RegisterOperand)op;
if (ELIM_NULL_CHECKS) {
if (hasGuard(rop)) {
Operand guard = getGuard(rop);
setCurrentGuard(guard);
return false;
}
}
RegisterOperand guard = makeGuardReg();
Quad q = NullCheck.create(quad_cfg.getNewQuadID(), NullCheck.NULL_CHECK.INSTANCE, guard, rop.copy());
appendQuad(q);
mergeStateWithNullPtrExHandler(false);
setCurrentGuard(guard);
setGuard(rop, guard);
jq_Type type = rop.getType();
if (type.isAddressType()) {
// occurs when we compile Address.<init>, etc.
return false;
}
int number = getLocalNumber(rop.getRegister(), type);
if (rf.isLocal(rop, number, type)) {
Operand op2 = current_state.getLocal_A(number);
if (op2 instanceof RegisterOperand) {
setGuard((RegisterOperand)op2, guard);
}
current_state.setLocal(number, op2);
replaceLocalsOnStack(number, type);
}
return false;
}
boolean performBoundsCheck(Operand ref, Operand index) {
Quad q = BoundsCheck.create(quad_cfg.getNewQuadID(), BoundsCheck.BOUNDS_CHECK.INSTANCE, ref.copy(), index.copy(), getCurrentGuard());
appendQuad(q);
mergeStateWithArrayBoundsExHandler(false);
return false;
}
boolean performCheckStore(RegisterOperand ref, Operand elem) {
jq_Type type = getTypeOf(elem);
if (type == jq_Reference.jq_NullType.NULL_TYPE) return false;
jq_Type arrayElemType = getArrayElementTypeOf(ref);
if (arrayElemType.isAddressType()) {
if (type.isAddressType() || type == jq_Reference.jq_NullType.NULL_TYPE)
return false;
Assert.UNREACHABLE("Storing non-address value into address array! Array: "+ref+" Type: "+type);
}
if (type.isAddressType()) {
Assert.UNREACHABLE("Storing address value into non-address array! Array: "+ref+" Type: "+type);
}
if (ref.isExactType()) {
if (TypeCheck.isAssignable_noload(type, arrayElemType) == TypeCheck.YES)
return false;
}
jq_Type arrayElemType2 = arrayElemType;
if (arrayElemType.isArrayType()) {
arrayElemType2 = ((jq_Array)arrayElemType).getInnermostElementType();
}
if (arrayElemType2.isLoaded() && arrayElemType2.isFinal()) {
if (arrayElemType == type)
return false;
}
Quad q = StoreCheck.create(quad_cfg.getNewQuadID(), StoreCheck.ASTORE_CHECK.INSTANCE, ref.copy(), elem.copy(), getCurrentGuard());
appendQuad(q);
mergeStateWithObjArrayStoreExHandler(false);
return false;
}
boolean performZeroCheck(Operand op) {
if (op instanceof IConstOperand) {
int val = ((IConstOperand)op).getValue();
if (val != 0) {
setCurrentGuard(new UnnecessaryGuardOperand());
return false;
} else {
Quad q = ZeroCheck.create(quad_cfg.getNewQuadID(), ZeroCheck.ZERO_CHECK_I.INSTANCE, null, op);
appendQuad(q);
if (false) {
endBasicBlock = true;
mergeStateWithArithExHandler(true);
return true;
} else {
mergeStateWithArithExHandler(false);
return false;
}
}
}
if (op instanceof LConstOperand) {
long val = ((LConstOperand)op).getValue();
if (val != 0) {
setCurrentGuard(new UnnecessaryGuardOperand());
return false;
} else {
Quad q = ZeroCheck.create(quad_cfg.getNewQuadID(), ZeroCheck.ZERO_CHECK_L.INSTANCE, null, op);
appendQuad(q);
if (false) {
endBasicBlock = true;
mergeStateWithArithExHandler(true);
return true;
} else {
mergeStateWithArithExHandler(false);
return false;
}
}
}
RegisterOperand rop = (RegisterOperand)op;
if (hasGuard(rop)) {
Operand guard = getGuard(rop);
setCurrentGuard(guard);
return false;
}
RegisterOperand guard = makeGuardReg();
ZeroCheck oper = null;
if (rop.getType() == jq_Primitive.LONG) oper = ZeroCheck.ZERO_CHECK_L.INSTANCE;
else if (rop.getType().isIntLike()) oper = ZeroCheck.ZERO_CHECK_I.INSTANCE;
else Assert.UNREACHABLE("Zero check on "+rop+" type "+rop.getType());
Quad q = ZeroCheck.create(quad_cfg.getNewQuadID(), oper, guard, rop.copy());
appendQuad(q);
mergeStateWithArithExHandler(false);
setCurrentGuard(guard);
setGuard(rop, guard);
jq_Type type = rop.getType();
int number = getLocalNumber(rop.getRegister(), type);
if (rf.isLocal(rop, number, type)) {
Operand op2 = null;
if (type == jq_Primitive.LONG)
op2 = current_state.getLocal_L(number);
else if (type.isIntLike())
op2 = current_state.getLocal_I(number);
else
Assert.UNREACHABLE("Unknown type for local "+number+" "+rop+": "+type);
if (TRACE) System.out.println(rop+" is a local variable of type "+type+": currently "+op2);
if (op2 instanceof RegisterOperand) {
setGuard((RegisterOperand)op2, guard);
}
current_state.setLocal(number, op2);
replaceLocalsOnStack(number, type);
}
return false;
}
static jq_Type getTypeOf(Operand op) {
if (op instanceof IConstOperand) return jq_Primitive.INT;
if (op instanceof FConstOperand) return jq_Primitive.FLOAT;
if (op instanceof LConstOperand) return jq_Primitive.LONG;
if (op instanceof DConstOperand) return jq_Primitive.DOUBLE;
if (op instanceof PConstOperand) return Address._class;
if (op instanceof AConstOperand) {
Object val = ((AConstOperand)op).getValue();
if (val == null) return jq_Reference.jq_NullType.NULL_TYPE;
return Reflection.getTypeOf(val);
}
Assert._assert(op instanceof RegisterOperand, op.toString() + " is not a RegisterOperand");
return ((RegisterOperand)op).getType();
}
static jq_Type getArrayElementTypeOf(Operand op) {
if (op instanceof RegisterOperand) {
return ((jq_Array)((RegisterOperand)op).getType()).getElementType();
} else if (op instanceof AConstOperand && ((AConstOperand)op).getValue() == null) {
// what is the element type of an array constant 'null'?
return PrimordialClassLoader.getJavaLangObject();
} else {
Assert.UNREACHABLE(op.toString());
return null;
}
}
void mergeStateWithAllExHandlers(boolean cfgEdgeToExit) {
Compil3r.BytecodeAnalysis.ExceptionHandlerIterator i =
bc_bb.getExceptionHandlers();
while (i.hasNext()) {
Compil3r.BytecodeAnalysis.ExceptionHandler eh = i.nextEH();
mergeStateWith(eh);
}
}
void mergeStateWithNullPtrExHandler(boolean cfgEdgeToExit) {
Compil3r.BytecodeAnalysis.ExceptionHandlerIterator i =
bc_bb.getExceptionHandlers();
while (i.hasNext()) {
Compil3r.BytecodeAnalysis.ExceptionHandler eh = i.nextEH();
jq_Class k = eh.getExceptionType();
if (k == PrimordialClassLoader.getJavaLangNullPointerException() ||
k == PrimordialClassLoader.getJavaLangRuntimeException() ||
k == PrimordialClassLoader.getJavaLangException() ||
k == PrimordialClassLoader.getJavaLangThrowable() ||
k == null) {
mergeStateWith(eh);
break;
}
}
}
void mergeStateWithArithExHandler(boolean cfgEdgeToExit) {
Compil3r.BytecodeAnalysis.ExceptionHandlerIterator i =
bc_bb.getExceptionHandlers();
while (i.hasNext()) {
Compil3r.BytecodeAnalysis.ExceptionHandler eh = i.nextEH();
jq_Class k = eh.getExceptionType();
if (k == PrimordialClassLoader.getJavaLangArithmeticException() ||
k == PrimordialClassLoader.getJavaLangRuntimeException() ||
k == PrimordialClassLoader.getJavaLangException() ||
k == PrimordialClassLoader.getJavaLangThrowable() ||
k == null) {
mergeStateWith(eh);
break;
}
}
}
void mergeStateWithArrayBoundsExHandler(boolean cfgEdgeToExit) {
Compil3r.BytecodeAnalysis.ExceptionHandlerIterator i =
bc_bb.getExceptionHandlers();
while (i.hasNext()) {
Compil3r.BytecodeAnalysis.ExceptionHandler eh = i.nextEH();
jq_Class k = eh.getExceptionType();
if (k == PrimordialClassLoader.getJavaLangArrayIndexOutOfBoundsException() ||
k == PrimordialClassLoader.getJavaLangIndexOutOfBoundsException() ||
k == PrimordialClassLoader.getJavaLangRuntimeException() ||
k == PrimordialClassLoader.getJavaLangException() ||
k == PrimordialClassLoader.getJavaLangThrowable() ||
k == null) {
mergeStateWith(eh);
break;
}
}
}
void mergeStateWithObjArrayStoreExHandler(boolean cfgEdgeToExit) {
Compil3r.BytecodeAnalysis.ExceptionHandlerIterator i =
bc_bb.getExceptionHandlers();
while (i.hasNext()) {
Compil3r.BytecodeAnalysis.ExceptionHandler eh = i.nextEH();
jq_Class k = eh.getExceptionType();
if (k == PrimordialClassLoader.getJavaLangArrayStoreException() ||
k == PrimordialClassLoader.getJavaLangRuntimeException() ||
k == PrimordialClassLoader.getJavaLangException() ||
k == PrimordialClassLoader.getJavaLangThrowable() ||
k == null) {
mergeStateWith(eh);
break;
}
}
}
RegisterOperand makeGuardReg() {
return RegisterFactory.makeGuardReg();
}
int getLocalNumber(Register r, jq_Type t) {
return r.getNumber();
}
/** Class used to store the abstract state of the bytecode-to-quad converter. */
public static class AbstractState {
public static boolean TRACE = false;
private int stackptr;
private Operand[] stack;
private Operand[] locals;
static class DummyOperand implements Operand {
private DummyOperand() {}
static final DummyOperand DUMMY = new DummyOperand();
public Quad getQuad() { Assert.UNREACHABLE(); return null; }
public void attachToQuad(Quad q) { Assert.UNREACHABLE(); }
public Operand copy() { return DUMMY; }
public boolean isSimilar(Operand that) { return that == DUMMY; }
public String toString() { return "<dummy>"; }
}
static AbstractState allocateEmptyState(jq_Method m) {
// +1 because SWAP requires a temporary location.
AbstractState s = new AbstractState(m.getMaxStack()+1, m.getMaxLocals());
return s;
}
static AbstractState allocateInitialState(RegisterFactory rf, jq_Method m) {
// +1 because SWAP requires a temporary location.
AbstractState s = new AbstractState(m.getMaxStack()+1, m.getMaxLocals());
jq_Type[] paramTypes = m.getParamTypes();
for (int i=0, j=-1; i<paramTypes.length; ++i) {
jq_Type paramType = paramTypes[i];
++j;
s.locals[j] = new RegisterOperand(rf.getLocal(j, paramType), paramType);
if (paramType.getReferenceSize() == 8) {
s.locals[++j] = DummyOperand.DUMMY;
}
}
return s;
}
private AbstractState(int nstack, int nlocals) {
this.stack = new Operand[nstack]; this.locals = new Operand[nlocals];
}
AbstractState copy() {
AbstractState that = new AbstractState(this.stack.length, this.locals.length);
System.arraycopy(this.stack, 0, that.stack, 0, this.stackptr);
System.arraycopy(this.locals, 0, that.locals, 0, this.locals.length);
that.stackptr = this.stackptr;
return that;
}
AbstractState copyFull() {
AbstractState that = new AbstractState(this.stack.length, this.locals.length);
for (int i=0; i<stackptr; ++i) {
that.stack[i] = this.stack[i].copy();
}
for (int i=0; i<this.locals.length; ++i) {
if (this.locals[i] != null)
that.locals[i] = this.locals[i].copy();
}
that.stackptr = this.stackptr;
return that;
}
AbstractState copyAfterJSR() {
AbstractState that = new AbstractState(this.stack.length, this.locals.length);
for (int i=0; i<this.locals.length; ++i) {
if (this.locals[i] != null)
that.locals[i] = this.locals[i].copy();
}
return that;
}
AbstractState copyExceptionHandler(jq_Class exType, RegisterFactory rf) {
if (exType == null) exType = PrimordialClassLoader.getJavaLangThrowable();
AbstractState that = new AbstractState(this.stack.length, this.locals.length);
that.stackptr = 1;
RegisterOperand ex = new RegisterOperand(rf.getStack(0, exType), exType);
that.stack[0] = ex;
for (int i=0; i<this.locals.length; ++i) {
if (this.locals[i] != null)
that.locals[i] = this.locals[i].copy();
}
return that;
}
void overwriteWith(AbstractState that) {
Assert._assert(this.stack.length == that.stack.length);
Assert._assert(this.locals.length == that.locals.length);
System.arraycopy(that.stack, 0, this.stack, 0, that.stackptr);
System.arraycopy(that.locals, 0, this.locals, 0, that.locals.length);
this.stackptr = that.stackptr;
}
void mergeAfterJSR(boolean[] changedLocals, AbstractState that) {
for (int j=0; j<this.locals.length; ++j) {
if (!changedLocals[j]) continue;
if (TRACE) System.out.println("local "+j+" changed in jsr to "+that.locals[j]);
if (that.locals[j] == null) this.locals[j] = null;
else this.locals[j] = that.locals[j].copy();
}
this.stackptr = that.stackptr;
for (int i=0; i<stackptr; ++i) {
this.stack[i] = that.stack[i].copy();
}
}
boolean merge(AbstractState that, RegisterFactory rf) {
if (this.stackptr != that.stackptr) throw new VerifyError(this.stackptr+" != "+that.stackptr);
Assert._assert(this.locals.length == that.locals.length);
boolean change = false;
for (int i=0; i<this.stackptr; ++i) {
Operand o = meet(this.stack[i], that.stack[i], true, i, rf);
if (o != this.stack[i] && (o == null || !o.isSimilar(this.stack[i]))) change = true;
this.stack[i] = o;
}
for (int i=0; i<this.locals.length; ++i) {
Operand o = meet(this.locals[i], that.locals[i], false, i, rf);
if (o != this.locals[i] && (o == null || !o.isSimilar(this.locals[i]))) change = true;
this.locals[i] = o;
}
return change;
}
boolean mergeExceptionHandler(AbstractState that, jq_Class exType, RegisterFactory rf) {
if (exType == null) exType = PrimordialClassLoader.getJavaLangThrowable();
Assert._assert(this.locals.length == that.locals.length);
Assert._assert(this.stackptr == 1);
boolean change = false;
RegisterOperand ex = new RegisterOperand(rf.getStack(0, exType), exType);
Operand o = meet(this.stack[0], ex, true, 0, rf);
if (o != this.stack[0] && (o == null || !o.isSimilar(this.stack[0]))) change = true;
this.stack[0] = o;
for (int i=0; i<this.locals.length; ++i) {
o = meet(this.locals[i], that.locals[i], false, i, rf);
if (o != this.locals[i] && (o == null || !o.isSimilar(this.locals[i]))) change = true;
this.locals[i] = o;
}
return change;
}
static Operand meet(Operand op1, Operand op2, boolean stack, int index, RegisterFactory rf) {
if (TRACE) System.out.println("Meeting "+op1+" with "+op2+", "+(stack?"S":"L")+index);
if (op1 == op2) {
// same operand, or both null.
return op1;
}
if ((op1 == null) || (op2 == null)) {
// no information about one of the operands.
return null;
}
if (Operand.Util.isConstant(op1)) {
if (op1.isSimilar(op2)) {
// same constant value.
return op1;
}
if (op2 instanceof DummyOperand) {
return null;
}
jq_Type type = TypeCheck.findCommonSuperclass(getTypeOf(op1), getTypeOf(op2));
if (type != null) {
// different constants of the same type
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, type):rf.getLocal(index, type), type);
return res;
} else {
// constants of incompatible types.
return null;
}
}
if (op1 instanceof RegisterOperand) {
if (op2 instanceof DummyOperand) {
// op1 is a register, op2 is a dummy
return null;
}
RegisterOperand rop1 = (RegisterOperand)op1;
jq_Type t1 = rop1.getType();
if (op2 instanceof RegisterOperand) {
// both are registers.
RegisterOperand rop2 = (RegisterOperand)op2;
jq_Type t2 = rop2.getType();
if (t1 == t2) {
// registers have same type.
if (rop1.hasMoreConservativeFlags(rop2)) {
// registers have compatible flags.
if ((rop1.scratchObject == null) ||
((Operand)rop1.scratchObject).isSimilar((Operand)rop2.scratchObject)) {
// null guards match.
return rop1;
}
// null guards don't match.
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
res.setFlags(rop1.getFlags());
return res;
}
// incompatible flags.
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
if ((rop1.scratchObject == null) ||
((Operand)rop1.scratchObject).isSimilar((Operand)rop2.scratchObject)) {
// null guards match.
res.scratchObject = rop1.scratchObject;
}
res.setFlags(rop1.getFlags());
res.meetFlags(rop2.getFlags());
return res;
}
if (TypeCheck.isAssignable_noload(t2, t1) == TypeCheck.YES) {
// t2 is a subtype of t1.
if (!rop1.isExactType() && rop1.hasMoreConservativeFlags(rop2)) {
// flags and exact type matches.
if ((rop1.scratchObject == null) ||
((Operand)rop1.scratchObject).isSimilar((Operand)rop2.scratchObject)) {
// null guards match.
return rop1;
}
// null guards don't match.
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
res.setFlags(rop1.getFlags());
return res;
}
// doesn't match.
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
if ((rop1.scratchObject == null) ||
((Operand)rop1.scratchObject).isSimilar((Operand)rop2.scratchObject)) {
// null guards match.
res.scratchObject = rop1.scratchObject;
}
res.setFlags(rop1.getFlags());
res.meetFlags(rop2.getFlags());
res.clearExactType();
return res;
}
if ((t2 = TypeCheck.findCommonSuperclass(t1, t2)) != null) {
// common superclass
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t2):rf.getLocal(index, t2), t2);
if (rop1.scratchObject != null) {
if (((Operand)rop1.scratchObject).isSimilar((Operand)rop2.scratchObject)) {
// null guards match.
res.scratchObject = rop1.scratchObject;
}
}
res.setFlags(rop1.getFlags());
res.meetFlags(rop2.getFlags());
res.clearExactType();
return res;
}
// no common superclass
return null;
}
// op2 is not a register.
jq_Type t2 = getTypeOf(op2);
if (t1 == t2) {
// same type.
if ((rop1.scratchObject == null) || (t2 != jq_Reference.jq_NullType.NULL_TYPE)) {
// null guard matches.
return rop1;
}
// null guards doesn't match.
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
res.setFlags(rop1.getFlags());
return res;
}
if (TypeCheck.isAssignable_noload(t2, t1) == TypeCheck.YES) {
// compatible type.
if (!rop1.isExactType()) {
if ((rop1.scratchObject == null) || (t2 != jq_Reference.jq_NullType.NULL_TYPE)) {
// null guard matches.
return rop1;
}
// null guard doesn't match.
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
res.setFlags(rop1.getFlags());
return res;
}
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t1):rf.getLocal(index, t1), t1);
if (t2 != jq_Reference.jq_NullType.NULL_TYPE) {
// null guard matches.
res.scratchObject = rop1.scratchObject;
}
res.setFlags(rop1.getFlags());
res.clearExactType();
return res;
}
if ((t2 = TypeCheck.findCommonSuperclass(t1, t2)) != null) {
// common superclass
RegisterOperand res = new RegisterOperand(stack?rf.getStack(index, t2):rf.getLocal(index, t2), t2);
if (t2 != jq_Reference.jq_NullType.NULL_TYPE) {
// null guard matches.
res.scratchObject = rop1.scratchObject;
}
res.setFlags(rop1.getFlags());
res.clearExactType();
return res;
}
// no common superclass
return null;
}
// op1 is not a register.
if (op1.isSimilar(op2)) {
return op1;
} else {
return null;
}
}
int getStackSize() { return this.stackptr; }
void push_I(Operand op) { Assert._assert(getTypeOf(op).isIntLike()); push(op); }
void push_F(Operand op) { Assert._assert(getTypeOf(op) == jq_Primitive.FLOAT); push(op); }
void push_L(Operand op) { Assert._assert(getTypeOf(op) == jq_Primitive.LONG); push(op); pushDummy(); }
void push_D(Operand op) { Assert._assert(getTypeOf(op) == jq_Primitive.DOUBLE); push(op); pushDummy(); }
void push_A(Operand op) { Assert._assert(getTypeOf(op).isReferenceType() && !getTypeOf(op).isAddressType()); push(op); }
void push_P(Operand op) { Assert._assert(getTypeOf(op).isAddressType()); push(op); }
void push(Operand op, jq_Type t) {
Assert._assert(TypeCheck.isAssignable_noload(getTypeOf(op), t) == TypeCheck.YES);
push(op); if (t.getReferenceSize() == 8) pushDummy();
}
void pushDummy() { push(DummyOperand.DUMMY); }
void push(Operand op) {
if (TRACE) System.out.println("Pushing "+op+" on stack "+(this.stackptr));
this.stack[this.stackptr++] = op;
}
Operand pop_I() { Operand op = pop(); Assert._assert(getTypeOf(op).isIntLike()); return op; }
Operand pop_F() { Operand op = pop(); Assert._assert(getTypeOf(op) == jq_Primitive.FLOAT); return op; }
Operand pop_L() { popDummy(); Operand op = pop(); Assert._assert(getTypeOf(op) == jq_Primitive.LONG); return op; }
Operand pop_D() { popDummy(); Operand op = pop(); Assert._assert(getTypeOf(op) == jq_Primitive.DOUBLE); return op; }
Operand pop_A() { Operand op = pop(); Assert._assert(getTypeOf(op).isReferenceType() && !getTypeOf(op).isAddressType()); return op; }
Operand pop_P() {
Operand op = pop();
if (op instanceof AConstOperand) {
op = new PConstOperand(null);
}
Assert._assert(getTypeOf(op).isAddressType() ||
getTypeOf(op).isSubtypeOf(Address._class));
return op;
}
void popDummy() { Operand op = pop(); Assert._assert(op == DummyOperand.DUMMY); }
Operand pop(jq_Type t) {
if (t.getReferenceSize() == 8) popDummy();
Operand op = pop();
if (t.isAddressType()) {
if (op instanceof AConstOperand) {
op = new PConstOperand(null);
}
jq_Type t2 = getTypeOf(op);
Assert._assert(t2 == jq_Reference.jq_NullType.NULL_TYPE ||
t2.isAddressType() ||
t2.isSubtypeOf(Address._class));
}
//jq.Assert(TypeCheck.isAssignable_noload(getTypeOf(op), t) != TypeCheck.NO);
return op;
}
Operand pop() {
if (TRACE) System.out.println("Popping "+this.stack[this.stackptr-1]+" from stack "+(this.stackptr-1));
return this.stack[--this.stackptr];
}
Operand peekStack(int i) { return this.stack[this.stackptr-i-1]; }
void pokeStack(int i, Operand op) { this.stack[this.stackptr-i-1] = op; }
void clearStack() { this.stackptr = 0; }
Operand getLocal_I(int i) { Operand op = getLocal(i); Assert._assert(getTypeOf(op).isIntLike()); return op; }
Operand getLocal_F(int i) { Operand op = getLocal(i); Assert._assert(getTypeOf(op) == jq_Primitive.FLOAT); return op; }
Operand getLocal_L(int i) {
Operand op = getLocal(i);
Assert._assert(getTypeOf(op) == jq_Primitive.LONG);
Assert._assert(getLocal(i+1) == DummyOperand.DUMMY);
return op;
}
Operand getLocal_D(int i) {
Operand op = getLocal(i);
Assert._assert(getTypeOf(op) == jq_Primitive.DOUBLE);
Assert._assert(getLocal(i+1) == DummyOperand.DUMMY);
return op;
}
Operand getLocal_A(int i) {
Operand op = getLocal(i);
Assert._assert(getTypeOf(op).isReferenceType());
Assert._assert(!getTypeOf(op).isAddressType());
return op;
}
Operand getLocal(int i) {
return this.locals[i].copy();
}
void setLocal(int i, Operand op) {
this.locals[i] = op;
}
void setLocalDual(int i, Operand op) {
this.locals[i] = op; this.locals[i+1] = DummyOperand.DUMMY;
}
void dumpState() {
System.out.print("Locals:");
for (int i=0; i<this.locals.length; ++i) {
if (this.locals[i] != null)
System.out.print(" L"+i+":"+this.locals[i]);
}
System.out.print("\nStack: ");
for (int i=0; i<this.stackptr; ++i) {
System.out.print(" S"+i+":"+this.stack[i]);
}
System.out.println();
}
}
public static class jq_ReturnAddressType extends jq_Reference {
public static final jq_ReturnAddressType INSTANCE = new jq_ReturnAddressType();
private BasicBlock returnTarget;
private jq_ReturnAddressType() { super(Utf8.get("L&ReturnAddress;"), Bootstrap.PrimordialClassLoader.loader); }
private jq_ReturnAddressType(BasicBlock returnTarget) {
super(Utf8.get("L&ReturnAddress;"), Bootstrap.PrimordialClassLoader.loader);
this.returnTarget = returnTarget;
}
public boolean isAddressType() { return false; }
public String getJDKName() { return desc.toString(); }
public String getJDKDesc() { return getJDKName(); }
public Clazz.jq_Class[] getInterfaces() { Assert.UNREACHABLE(); return null; }
public Clazz.jq_Class getInterface(Utf8 desc) { Assert.UNREACHABLE(); return null; }
public boolean implementsInterface(Clazz.jq_Class k) { Assert.UNREACHABLE(); return false; }
public Clazz.jq_InstanceMethod getVirtualMethod(Clazz.jq_NameAndDesc nd) { Assert.UNREACHABLE(); return null; }
public String getName() { return "<retaddr>"; }
public String shortName() { return "<retaddr>"; }
public boolean isClassType() { Assert.UNREACHABLE(); return false; }
public boolean isArrayType() { Assert.UNREACHABLE(); return false; }
public boolean isFinal() { Assert.UNREACHABLE(); return false; }
public jq_Reference getDirectPrimarySupertype() { Assert.UNREACHABLE(); return null; }
public int getDepth() { Assert.UNREACHABLE(); return 0; }
public void load() { Assert.UNREACHABLE(); }
public void verify() { Assert.UNREACHABLE(); }
public void prepare() { Assert.UNREACHABLE(); }
public void sf_initialize() { Assert.UNREACHABLE(); }
public void compile() { Assert.UNREACHABLE(); }
public void cls_initialize() { Assert.UNREACHABLE(); }
public String toString() { return "<retaddr> (target="+returnTarget+")"; }
public boolean equals(Object rat) {
if (!(rat instanceof jq_ReturnAddressType)) return false;
return ((jq_ReturnAddressType)rat).returnTarget.equals(this.returnTarget);
}
public int hashCode() {
return returnTarget.hashCode();
}
}
static interface UnsafeHelper {
public boolean isUnsafe(jq_Method m);
public boolean endsBB(jq_Method m);
public boolean handleMethod(BytecodeToQuad b2q, ControlFlowGraph quad_cfg, BytecodeToQuad.AbstractState current_state, jq_Method m, Operator.Invoke oper);
}
private static UnsafeHelper _unsafe;
static {
/* Set up delegates. */
_unsafe = null;
boolean nullVM = jq.nullVM || System.getProperty("joeq.nullvm") != null;
if (!nullVM) {
_unsafe = attemptDelegate("Compil3r.Quad.B2QUnsafeHandler");
}
if (_unsafe == null) {
_unsafe = new Compil3r.Quad.B2QUnsafeIgnorer();
}
}
private static UnsafeHelper attemptDelegate(String s) {
String type = "BC2Q delegate";
try {
Class c = Class.forName(s);
return (UnsafeHelper)c.newInstance();
} catch (java.lang.ClassNotFoundException x) {
System.err.println("Cannot find "+type+" "+s+": "+x);
} catch (java.lang.InstantiationException x) {
System.err.println("Cannot instantiate "+type+" "+s+": "+x);
} catch (java.lang.IllegalAccessException x) {
System.err.println("Cannot access "+type+" "+s+": "+x);
}
return null;
}
}
| lgpl-2.1 |
IDgis/geo-publisher | publisher-domain/src/main/java/nl/idgis/publisher/domain/job/NotificationType.java | 308 | package nl.idgis.publisher.domain.job;
import nl.idgis.publisher.domain.MessageProperties;
import nl.idgis.publisher.domain.MessageType;
public interface NotificationType<T extends MessageProperties> extends MessageType<T> {
String name();
NotificationResult getResult(String resultName);
}
| lgpl-2.1 |
kajona/kajonacms | module_system/admin/formentries/FormentryTageditor.php | 2557 | <?php
/*"******************************************************************************************************
* (c) 2007-2016 by Kajona, www.kajona.de *
* Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt *
********************************************************************************************************/
namespace Kajona\System\Admin\Formentries;
use Kajona\System\System\Carrier;
use Kajona\System\System\Exception;
use Kajona\System\System\Reflection;
/**
* An list of tags which can be added or removed.
*
* @author [email protected]
* @since 4.7
* @package module_formgenerator
*/
class FormentryTageditor extends FormentryMultiselect {
protected $strOnChangeCallback;
public function setOnChangeCallback($strOnChangeCallback) {
$this->strOnChangeCallback = $strOnChangeCallback;
return $this;
}
/**
* Renders the field itself.
* In most cases, based on the current toolkit.
*
* @return string
*/
public function renderField()
{
$objToolkit = Carrier::getInstance()->getObjToolkit("admin");
$strReturn = "";
if($this->getStrHint() != null) {
$strReturn .= $objToolkit->formTextRow($this->getStrHint());
}
$strReturn.= $objToolkit->formInputTagEditor($this->getStrEntryName(), $this->getStrLabel(), $this->arrKeyValues, $this->strOnChangeCallback);
return $strReturn;
}
public function setValueToObject()
{
$objSourceObject = $this->getObjSourceObject();
if($objSourceObject == null)
return "";
$objReflection = new Reflection($objSourceObject);
$strSetter = $objReflection->getSetter($this->getStrSourceProperty());
if($strSetter === null)
throw new Exception("unable to find setter for value-property ".$this->getStrSourceProperty()."@".get_class($objSourceObject), Exception::$level_ERROR);
return $objSourceObject->{$strSetter}(json_encode(explode(",", $this->getStrValue())));
}
public function validateValue()
{
$arrValues = explode(",", $this->getStrValue());
foreach($arrValues as $strValue) {
$strValue = trim($strValue);
if(empty($strValue)) {
return false;
}
}
return true;
}
public function getValueAsText() {
return implode(", ", $this->arrKeyValues);
}
}
| lgpl-2.1 |
herculeshssj/unirio-ppgi-goalservice | GoalService/discovery/src/main/org/deri/wsmx/discovery/rule/complete/HWRuleServiceDescription.java | 2417 | /*
* Copyright (c) 2006, University of Innsbruck, Austria.
*
* 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.deri.wsmx.discovery.rule.complete;
import java.util.*;
import org.omwg.logicalexpression.LogicalExpression;
import org.omwg.ontology.*;
import org.wsmo.common.*;
import org.wsmo.factory.Factory;
import com.ontotext.wsmo4j.common.TopEntityImpl;
/**
* <pre>
* Committed by $Author: $
* $Source: $,
* </pre>
*
* @author Nathalie Steinmetz, STI Innsbruck
*
* @version $Revision: $ $Date: $
*/
public class HWRuleServiceDescription {
private Set<Variable> variables;
private LogicalExpression le;
private Set<Ontology> imports;
private TopEntity defaultNS =null;
public HWRuleServiceDescription(
Set<Ontology> imports,
Set<Variable> variables,
LogicalExpression le ){
this.variables=variables;
this.le=le;
this.imports=imports;
}
/*
* just for pretty printing...
*/
public void setDefaultNS(String ns){
defaultNS = new TopEntityImpl(
Factory.createWsmoFactory(null).createIRI("http://foo#topEntity"));
defaultNS.setDefaultNamespace(Factory.createWsmoFactory(null).createIRI(ns));
}
public Set<Variable> getVariables(){
return variables;
}
public LogicalExpression getExpressions(){
return le;
}
public void replaceExpressions(LogicalExpression le) {
this.le = le;
}
public Set<Ontology> listOntologies(){
return imports;
}
public String toString(){
return le.toString(defaultNS);
}
}
| lgpl-2.1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.