repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
PepperPD/edx-pepper-platform
static/xmodule_js/common_static/xmodule/descriptors/js/001-a540140df081888388f2d1b0d37daaeb.a540140df081.js
14096
// Generated by CoffeeScript 1.6.3 (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.MarkdownEditingDescriptor = (function(_super) { __extends(MarkdownEditingDescriptor, _super); MarkdownEditingDescriptor.multipleChoiceTemplate = "( ) incorrect\n( ) incorrect\n(x) correct\n"; MarkdownEditingDescriptor.checkboxChoiceTemplate = "[x] correct\n[ ] incorrect\n[x] correct\n"; MarkdownEditingDescriptor.stringInputTemplate = "= answer\n"; MarkdownEditingDescriptor.numberInputTemplate = "= answer +- x%\n"; MarkdownEditingDescriptor.selectTemplate = "[[incorrect, (correct), incorrect]]\n"; MarkdownEditingDescriptor.headerTemplate = "Header\n=====\n"; MarkdownEditingDescriptor.explanationTemplate = "[explanation]\nShort explanation\n[explanation]\n"; function MarkdownEditingDescriptor(element) { this.toggleCheatsheet = __bind(this.toggleCheatsheet, this); this.onToolbarButton = __bind(this.onToolbarButton, this); this.onShowXMLButton = __bind(this.onShowXMLButton, this); this.element = element; if ($(".markdown-box", this.element).length !== 0) { this.markdown_editor = CodeMirror.fromTextArea($(".markdown-box", element)[0], { lineWrapping: true, mode: null }); this.setCurrentEditor(this.markdown_editor); this.element.on('click', '.xml-tab', this.onShowXMLButton); this.element.on('click', '.format-buttons a', this.onToolbarButton); this.element.on('click', '.cheatsheet-toggle', this.toggleCheatsheet); $(this.element.find('.xml-box')).hide(); } else { this.createXMLEditor(); } } /* Creates the XML Editor and sets it as the current editor. If text is passed in, it will replace the text present in the HTML template. text: optional argument to override the text passed in via the HTML template */ MarkdownEditingDescriptor.prototype.createXMLEditor = function(text) { this.xml_editor = CodeMirror.fromTextArea($(".xml-box", this.element)[0], { mode: "xml", lineNumbers: true, lineWrapping: true }); if (text) { this.xml_editor.setValue(text); } return this.setCurrentEditor(this.xml_editor); }; /* User has clicked to show the XML editor. Before XML editor is swapped in, the user will need to confirm the one-way conversion. */ MarkdownEditingDescriptor.prototype.onShowXMLButton = function(e) { e.preventDefault(); if (this.confirmConversionToXml()) { this.createXMLEditor(MarkdownEditingDescriptor.markdownToXml(this.markdown_editor.getValue())); this.xml_editor.setCursor(0); this.xml_editor.refresh(); return $(this.element.find('.editor-bar')).hide(); } }; /* Have the user confirm the one-way conversion to XML. Returns true if the user clicked OK, else false. */ MarkdownEditingDescriptor.prototype.confirmConversionToXml = function() { return confirm("If you use the Advanced Editor, this problem will be converted to XML and you will not be able to return to the Simple Editor Interface.\n\nProceed to the Advanced Editor and convert this problem to XML?"); }; /* Event listener for toolbar buttons (only possible when markdown editor is visible). */ MarkdownEditingDescriptor.prototype.onToolbarButton = function(e) { var revisedSelection, selection; e.preventDefault(); selection = this.markdown_editor.getSelection(); revisedSelection = null; switch ($(e.currentTarget).attr('class')) { case "multiple-choice-button": revisedSelection = MarkdownEditingDescriptor.insertMultipleChoice(selection); break; case "string-button": revisedSelection = MarkdownEditingDescriptor.insertStringInput(selection); break; case "number-button": revisedSelection = MarkdownEditingDescriptor.insertNumberInput(selection); break; case "checks-button": revisedSelection = MarkdownEditingDescriptor.insertCheckboxChoice(selection); break; case "dropdown-button": revisedSelection = MarkdownEditingDescriptor.insertSelect(selection); break; case "header-button": revisedSelection = MarkdownEditingDescriptor.insertHeader(selection); break; case "explanation-button": revisedSelection = MarkdownEditingDescriptor.insertExplanation(selection); break; } if (revisedSelection !== null) { this.markdown_editor.replaceSelection(revisedSelection); return this.markdown_editor.focus(); } }; /* Event listener for toggling cheatsheet (only possible when markdown editor is visible). */ MarkdownEditingDescriptor.prototype.toggleCheatsheet = function(e) { var _this = this; e.preventDefault(); if (!$(this.markdown_editor.getWrapperElement()).find('.simple-editor-cheatsheet')[0]) { this.cheatsheet = $($('#simple-editor-cheatsheet').html()); $(this.markdown_editor.getWrapperElement()).append(this.cheatsheet); } return setTimeout((function() { return _this.cheatsheet.toggleClass('shown'); }), 10); }; /* Stores the current editor and hides the one that is not displayed. */ MarkdownEditingDescriptor.prototype.setCurrentEditor = function(editor) { if (this.current_editor) { $(this.current_editor.getWrapperElement()).hide(); } this.current_editor = editor; $(this.current_editor.getWrapperElement()).show(); return $(this.current_editor).focus(); }; /* Called when save is called. Listeners are unregistered because editing the block again will result in a new instance of the descriptor. Note that this is NOT the case for cancel-- when cancel is called the instance of the descriptor is reused if edit is selected again. */ MarkdownEditingDescriptor.prototype.save = function() { this.element.off('click', '.xml-tab', this.changeEditor); this.element.off('click', '.format-buttons a', this.onToolbarButton); this.element.off('click', '.cheatsheet-toggle', this.toggleCheatsheet); if (this.current_editor === this.markdown_editor) { return { data: MarkdownEditingDescriptor.markdownToXml(this.markdown_editor.getValue()), metadata: { markdown: this.markdown_editor.getValue() } }; } else { return { data: this.xml_editor.getValue(), nullout: ['markdown'] }; } }; MarkdownEditingDescriptor.insertMultipleChoice = function(selectedText) { return MarkdownEditingDescriptor.insertGenericChoice(selectedText, '(', ')', MarkdownEditingDescriptor.multipleChoiceTemplate); }; MarkdownEditingDescriptor.insertCheckboxChoice = function(selectedText) { return MarkdownEditingDescriptor.insertGenericChoice(selectedText, '[', ']', MarkdownEditingDescriptor.checkboxChoiceTemplate); }; MarkdownEditingDescriptor.insertGenericChoice = function(selectedText, choiceStart, choiceEnd, template) { var cleanSelectedText, line, lines, revisedLines, _i, _len; if (selectedText.length > 0) { cleanSelectedText = selectedText.replace(/\n+/g, '\n').replace(/\n$/, ''); lines = cleanSelectedText.split('\n'); revisedLines = ''; for (_i = 0, _len = lines.length; _i < _len; _i++) { line = lines[_i]; revisedLines += choiceStart; if (/^\s*x\s+(\S)/i.test(line)) { line = line.replace(/^\s*x\s+(\S)/i, '$1'); revisedLines += 'x'; } else { revisedLines += ' '; } revisedLines += choiceEnd + ' ' + line + '\n'; } return revisedLines; } else { return template; } }; MarkdownEditingDescriptor.insertStringInput = function(selectedText) { return MarkdownEditingDescriptor.insertGenericInput(selectedText, '= ', '', MarkdownEditingDescriptor.stringInputTemplate); }; MarkdownEditingDescriptor.insertNumberInput = function(selectedText) { return MarkdownEditingDescriptor.insertGenericInput(selectedText, '= ', '', MarkdownEditingDescriptor.numberInputTemplate); }; MarkdownEditingDescriptor.insertSelect = function(selectedText) { return MarkdownEditingDescriptor.insertGenericInput(selectedText, '[[', ']]', MarkdownEditingDescriptor.selectTemplate); }; MarkdownEditingDescriptor.insertHeader = function(selectedText) { return MarkdownEditingDescriptor.insertGenericInput(selectedText, '', '\n====\n', MarkdownEditingDescriptor.headerTemplate); }; MarkdownEditingDescriptor.insertExplanation = function(selectedText) { return MarkdownEditingDescriptor.insertGenericInput(selectedText, '[explanation]\n', '\n[explanation]', MarkdownEditingDescriptor.explanationTemplate); }; MarkdownEditingDescriptor.insertGenericInput = function(selectedText, lineStart, lineEnd, template) { if (selectedText.length > 0) { return lineStart + selectedText + lineEnd; } else { return template; } }; MarkdownEditingDescriptor.markdownToXml = function(markdown) { var toXml; toXml = function(markdown) { var xml = markdown; // replace headers xml = xml.replace(/(^.*?$)(?=\n\=\=+$)/gm, '<h1>$1</h1>'); xml = xml.replace(/\n^\=\=+$/gm, ''); // group multiple choice answers xml = xml.replace(/(^\s*\(.?\).*?$\n*)+/gm, function(match, p) { var groupString = '<multiplechoiceresponse>\n'; groupString += ' <choicegroup type="MultipleChoice">\n'; var options = match.split('\n'); for(var i = 0; i < options.length; i++) { if(options[i].length > 0) { var value = options[i].split(/^\s*\(.?\)\s*/)[1]; var correct = /^\s*\(x\)/i.test(options[i]); groupString += ' <choice correct="' + correct + '">' + value + '</choice>\n'; } } groupString += ' </choicegroup>\n'; groupString += '</multiplechoiceresponse>\n\n'; return groupString; }); // group check answers xml = xml.replace(/(^\s*\[.?\].*?$\n*)+/gm, function(match, p) { var groupString = '<choiceresponse>\n'; groupString += ' <checkboxgroup direction="vertical">\n'; var options = match.split('\n'); for(var i = 0; i < options.length; i++) { if(options[i].length > 0) { var value = options[i].split(/^\s*\[.?\]\s*/)[1]; var correct = /^\s*\[x\]/i.test(options[i]); groupString += ' <choice correct="' + correct + '">' + value + '</choice>\n'; } } groupString += ' </checkboxgroup>\n'; groupString += '</choiceresponse>\n\n'; return groupString; }); // replace string and numerical xml = xml.replace(/^\=\s*(.*?$)/gm, function(match, p) { var string; var floatValue = parseFloat(p); if(!isNaN(floatValue)) { var params = /(.*?)\+\-\s*(.*?$)/.exec(p); if(params) { string = '<numericalresponse answer="' + floatValue + '">\n'; string += ' <responseparam type="tolerance" default="' + params[2] + '" />\n'; } else { string = '<numericalresponse answer="' + floatValue + '">\n'; } string += ' <formulaequationinput />\n'; string += '</numericalresponse>\n\n'; } else { string = '<stringresponse answer="' + p + '" type="ci">\n <textline size="20"/>\n</stringresponse>\n\n'; } return string; }); // replace selects xml = xml.replace(/\[\[(.+?)\]\]/g, function(match, p) { var selectString = '\n<optionresponse>\n'; selectString += ' <optioninput options="('; var options = p.split(/\,\s*/g); for(var i = 0; i < options.length; i++) { selectString += "'" + options[i].replace(/(?:^|,)\s*\((.*?)\)\s*(?:$|,)/g, '$1') + "'" + (i < options.length -1 ? ',' : ''); } selectString += ')" correct="'; var correct = /(?:^|,)\s*\((.*?)\)\s*(?:$|,)/g.exec(p); if (correct) selectString += correct[1]; selectString += '"></optioninput>\n'; selectString += '</optionresponse>\n\n'; return selectString; }); // replace explanations xml = xml.replace(/\[explanation\]\n?([^\]]*)\[\/?explanation\]/gmi, function(match, p1) { var selectString = '<solution>\n<div class="detailed-solution">\nExplanation\n\n' + p1 + '\n</div>\n</solution>'; return selectString; }); // split scripts and wrap paragraphs var splits = xml.split(/(\<\/?script.*?\>)/g); var scriptFlag = false; for(var i = 0; i < splits.length; i++) { if(/\<script/.test(splits[i])) { scriptFlag = true; } if(!scriptFlag) { splits[i] = splits[i].replace(/(^(?!\s*\<|$).*$)/gm, '<p>$1</p>'); } if(/\<\/script/.test(splits[i])) { scriptFlag = false; } } xml = splits.join(''); // rid white space xml = xml.replace(/\n\n\n/g, '\n'); // surround w/ problem tag xml = '<problem>\n' + xml + '\n</problem>'; return xml; } ; return toXml(markdown); }; return MarkdownEditingDescriptor; })(XModule.Descriptor); }).call(this);
agpl-3.0
dongjoon-hyun/spark
core/src/main/scala/org/apache/spark/deploy/master/Master.scala
52280
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.deploy.master import java.text.SimpleDateFormat import java.util.{Date, Locale} import java.util.concurrent.{ScheduledFuture, TimeUnit} import scala.collection.mutable.{ArrayBuffer, HashMap, HashSet} import scala.util.Random import org.apache.spark.{SecurityManager, SparkConf, SparkException} import org.apache.spark.deploy.{ApplicationDescription, DriverDescription, ExecutorState, SparkHadoopUtil} import org.apache.spark.deploy.DeployMessages._ import org.apache.spark.deploy.master.DriverState.DriverState import org.apache.spark.deploy.master.MasterMessages._ import org.apache.spark.deploy.master.ui.MasterWebUI import org.apache.spark.deploy.rest.StandaloneRestServer import org.apache.spark.internal.Logging import org.apache.spark.internal.config._ import org.apache.spark.internal.config.Deploy._ import org.apache.spark.internal.config.UI._ import org.apache.spark.internal.config.Worker._ import org.apache.spark.metrics.{MetricsSystem, MetricsSystemInstances} import org.apache.spark.resource.{ResourceRequirement, ResourceUtils} import org.apache.spark.rpc._ import org.apache.spark.serializer.{JavaSerializer, Serializer} import org.apache.spark.util.{SparkUncaughtExceptionHandler, ThreadUtils, Utils} private[deploy] class Master( override val rpcEnv: RpcEnv, address: RpcAddress, webUiPort: Int, val securityMgr: SecurityManager, val conf: SparkConf) extends ThreadSafeRpcEndpoint with Logging with LeaderElectable { private val forwardMessageThread = ThreadUtils.newDaemonSingleThreadScheduledExecutor("master-forward-message-thread") private val hadoopConf = SparkHadoopUtil.get.newConfiguration(conf) // For application IDs private def createDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US) private val workerTimeoutMs = conf.get(WORKER_TIMEOUT) * 1000 private val retainedApplications = conf.get(RETAINED_APPLICATIONS) private val retainedDrivers = conf.get(RETAINED_DRIVERS) private val reaperIterations = conf.get(REAPER_ITERATIONS) private val recoveryMode = conf.get(RECOVERY_MODE) private val maxExecutorRetries = conf.get(MAX_EXECUTOR_RETRIES) val workers = new HashSet[WorkerInfo] val idToApp = new HashMap[String, ApplicationInfo] private val waitingApps = new ArrayBuffer[ApplicationInfo] val apps = new HashSet[ApplicationInfo] private val idToWorker = new HashMap[String, WorkerInfo] private val addressToWorker = new HashMap[RpcAddress, WorkerInfo] private val endpointToApp = new HashMap[RpcEndpointRef, ApplicationInfo] private val addressToApp = new HashMap[RpcAddress, ApplicationInfo] private val completedApps = new ArrayBuffer[ApplicationInfo] private var nextAppNumber = 0 private val drivers = new HashSet[DriverInfo] private val completedDrivers = new ArrayBuffer[DriverInfo] // Drivers currently spooled for scheduling private val waitingDrivers = new ArrayBuffer[DriverInfo] private var nextDriverNumber = 0 Utils.checkHost(address.host) private val masterMetricsSystem = MetricsSystem.createMetricsSystem(MetricsSystemInstances.MASTER, conf) private val applicationMetricsSystem = MetricsSystem.createMetricsSystem(MetricsSystemInstances.APPLICATIONS, conf) private val masterSource = new MasterSource(this) // After onStart, webUi will be set private var webUi: MasterWebUI = null private val masterPublicAddress = { val envVar = conf.getenv("SPARK_PUBLIC_DNS") if (envVar != null) envVar else address.host } private val masterUrl = address.toSparkURL private var masterWebUiUrl: String = _ private var state = RecoveryState.STANDBY private var persistenceEngine: PersistenceEngine = _ private var leaderElectionAgent: LeaderElectionAgent = _ private var recoveryCompletionTask: ScheduledFuture[_] = _ private var checkForWorkerTimeOutTask: ScheduledFuture[_] = _ // As a temporary workaround before better ways of configuring memory, we allow users to set // a flag that will perform round-robin scheduling across the nodes (spreading out each app // among all the nodes) instead of trying to consolidate each app onto a small # of nodes. private val spreadOutApps = conf.get(SPREAD_OUT_APPS) // Default maxCores for applications that don't specify it (i.e. pass Int.MaxValue) private val defaultCores = conf.get(DEFAULT_CORES) val reverseProxy = conf.get(UI_REVERSE_PROXY) if (defaultCores < 1) { throw new SparkException(s"${DEFAULT_CORES.key} must be positive") } // Alternative application submission gateway that is stable across Spark versions private val restServerEnabled = conf.get(MASTER_REST_SERVER_ENABLED) private var restServer: Option[StandaloneRestServer] = None private var restServerBoundPort: Option[Int] = None { val authKey = SecurityManager.SPARK_AUTH_SECRET_CONF require(conf.getOption(authKey).isEmpty || !restServerEnabled, s"The RestSubmissionServer does not support authentication via ${authKey}. Either turn " + "off the RestSubmissionServer with spark.master.rest.enabled=false, or do not use " + "authentication.") } override def onStart(): Unit = { logInfo("Starting Spark master at " + masterUrl) logInfo(s"Running Spark version ${org.apache.spark.SPARK_VERSION}") webUi = new MasterWebUI(this, webUiPort) webUi.bind() masterWebUiUrl = webUi.webUrl if (reverseProxy) { val uiReverseProxyUrl = conf.get(UI_REVERSE_PROXY_URL).map(_.stripSuffix("/")) if (uiReverseProxyUrl.nonEmpty) { System.setProperty("spark.ui.proxyBase", uiReverseProxyUrl.get) // If the master URL has a path component, it must end with a slash. // Otherwise the browser generates incorrect relative links masterWebUiUrl = uiReverseProxyUrl.get + "/" } webUi.addProxy() logInfo(s"Spark Master is acting as a reverse proxy. Master, Workers and " + s"Applications UIs are available at $masterWebUiUrl") } checkForWorkerTimeOutTask = forwardMessageThread.scheduleAtFixedRate( () => Utils.tryLogNonFatalError { self.send(CheckForWorkerTimeOut) }, 0, workerTimeoutMs, TimeUnit.MILLISECONDS) if (restServerEnabled) { val port = conf.get(MASTER_REST_SERVER_PORT) restServer = Some(new StandaloneRestServer(address.host, port, conf, self, masterUrl)) } restServerBoundPort = restServer.map(_.start()) masterMetricsSystem.registerSource(masterSource) masterMetricsSystem.start() applicationMetricsSystem.start() // Attach the master and app metrics servlet handler to the web ui after the metrics systems are // started. masterMetricsSystem.getServletHandlers.foreach(webUi.attachHandler) applicationMetricsSystem.getServletHandlers.foreach(webUi.attachHandler) val serializer = new JavaSerializer(conf) val (persistenceEngine_, leaderElectionAgent_) = recoveryMode match { case "ZOOKEEPER" => logInfo("Persisting recovery state to ZooKeeper") val zkFactory = new ZooKeeperRecoveryModeFactory(conf, serializer) (zkFactory.createPersistenceEngine(), zkFactory.createLeaderElectionAgent(this)) case "FILESYSTEM" => val fsFactory = new FileSystemRecoveryModeFactory(conf, serializer) (fsFactory.createPersistenceEngine(), fsFactory.createLeaderElectionAgent(this)) case "CUSTOM" => val clazz = Utils.classForName(conf.get(RECOVERY_MODE_FACTORY)) val factory = clazz.getConstructor(classOf[SparkConf], classOf[Serializer]) .newInstance(conf, serializer) .asInstanceOf[StandaloneRecoveryModeFactory] (factory.createPersistenceEngine(), factory.createLeaderElectionAgent(this)) case _ => (new BlackHolePersistenceEngine(), new MonarchyLeaderAgent(this)) } persistenceEngine = persistenceEngine_ leaderElectionAgent = leaderElectionAgent_ } override def onStop(): Unit = { masterMetricsSystem.report() applicationMetricsSystem.report() // prevent the CompleteRecovery message sending to restarted master if (recoveryCompletionTask != null) { recoveryCompletionTask.cancel(true) } if (checkForWorkerTimeOutTask != null) { checkForWorkerTimeOutTask.cancel(true) } forwardMessageThread.shutdownNow() webUi.stop() restServer.foreach(_.stop()) masterMetricsSystem.stop() applicationMetricsSystem.stop() persistenceEngine.close() leaderElectionAgent.stop() } override def electedLeader(): Unit = { self.send(ElectedLeader) } override def revokedLeadership(): Unit = { self.send(RevokedLeadership) } override def receive: PartialFunction[Any, Unit] = { case ElectedLeader => val (storedApps, storedDrivers, storedWorkers) = persistenceEngine.readPersistedData(rpcEnv) state = if (storedApps.isEmpty && storedDrivers.isEmpty && storedWorkers.isEmpty) { RecoveryState.ALIVE } else { RecoveryState.RECOVERING } logInfo("I have been elected leader! New state: " + state) if (state == RecoveryState.RECOVERING) { beginRecovery(storedApps, storedDrivers, storedWorkers) recoveryCompletionTask = forwardMessageThread.schedule(new Runnable { override def run(): Unit = Utils.tryLogNonFatalError { self.send(CompleteRecovery) } }, workerTimeoutMs, TimeUnit.MILLISECONDS) } case CompleteRecovery => completeRecovery() case RevokedLeadership => logError("Leadership has been revoked -- master shutting down.") System.exit(0) case WorkerDecommissioning(id, workerRef) => if (state == RecoveryState.STANDBY) { workerRef.send(MasterInStandby) } else { // We use foreach since get gives us an option and we can skip the failures. idToWorker.get(id).foreach(decommissionWorker) } case DecommissionWorkers(ids) => // The caller has already checked the state when handling DecommissionWorkersOnHosts, // so it should not be the STANDBY assert(state != RecoveryState.STANDBY) ids.foreach ( id => // We use foreach since get gives us an option and we can skip the failures. idToWorker.get(id).foreach { w => decommissionWorker(w) // Also send a message to the worker node to notify. w.endpoint.send(DecommissionWorker) } ) case RegisterWorker( id, workerHost, workerPort, workerRef, cores, memory, workerWebUiUrl, masterAddress, resources) => logInfo("Registering worker %s:%d with %d cores, %s RAM".format( workerHost, workerPort, cores, Utils.megabytesToString(memory))) if (state == RecoveryState.STANDBY) { workerRef.send(MasterInStandby) } else if (idToWorker.contains(id)) { workerRef.send(RegisteredWorker(self, masterWebUiUrl, masterAddress, true)) } else { val workerResources = resources.map(r => r._1 -> WorkerResourceInfo(r._1, r._2.addresses)) val worker = new WorkerInfo(id, workerHost, workerPort, cores, memory, workerRef, workerWebUiUrl, workerResources) if (registerWorker(worker)) { persistenceEngine.addWorker(worker) workerRef.send(RegisteredWorker(self, masterWebUiUrl, masterAddress, false)) schedule() } else { val workerAddress = worker.endpoint.address logWarning("Worker registration failed. Attempted to re-register worker at same " + "address: " + workerAddress) workerRef.send(RegisterWorkerFailed("Attempted to re-register worker at same address: " + workerAddress)) } } case RegisterApplication(description, driver) => // TODO Prevent repeated registrations from some driver if (state == RecoveryState.STANDBY) { // ignore, don't send response } else { logInfo("Registering app " + description.name) val app = createApplication(description, driver) registerApplication(app) logInfo("Registered app " + description.name + " with ID " + app.id) persistenceEngine.addApplication(app) driver.send(RegisteredApplication(app.id, self)) schedule() } case DriverStateChanged(driverId, state, exception) => state match { case DriverState.ERROR | DriverState.FINISHED | DriverState.KILLED | DriverState.FAILED => removeDriver(driverId, state, exception) case _ => throw new Exception(s"Received unexpected state update for driver $driverId: $state") } case Heartbeat(workerId, worker) => idToWorker.get(workerId) match { case Some(workerInfo) => workerInfo.lastHeartbeat = System.currentTimeMillis() case None => if (workers.map(_.id).contains(workerId)) { logWarning(s"Got heartbeat from unregistered worker $workerId." + " Asking it to re-register.") worker.send(ReconnectWorker(masterUrl)) } else { logWarning(s"Got heartbeat from unregistered worker $workerId." + " This worker was never registered, so ignoring the heartbeat.") } } case MasterChangeAcknowledged(appId) => idToApp.get(appId) match { case Some(app) => logInfo("Application has been re-registered: " + appId) app.state = ApplicationState.WAITING case None => logWarning("Master change ack from unknown app: " + appId) } if (canCompleteRecovery) { completeRecovery() } case WorkerSchedulerStateResponse(workerId, execResponses, driverResponses) => idToWorker.get(workerId) match { case Some(worker) => logInfo("Worker has been re-registered: " + workerId) worker.state = WorkerState.ALIVE val validExecutors = execResponses.filter( exec => idToApp.get(exec.desc.appId).isDefined) for (exec <- validExecutors) { val (execDesc, execResources) = (exec.desc, exec.resources) val app = idToApp(execDesc.appId) val execInfo = app.addExecutor( worker, execDesc.cores, execResources, Some(execDesc.execId)) worker.addExecutor(execInfo) worker.recoverResources(execResources) execInfo.copyState(execDesc) } for (driver <- driverResponses) { val (driverId, driverResource) = (driver.driverId, driver.resources) drivers.find(_.id == driverId).foreach { driver => driver.worker = Some(worker) driver.state = DriverState.RUNNING driver.withResources(driverResource) worker.recoverResources(driverResource) worker.addDriver(driver) } } case None => logWarning("Scheduler state from unknown worker: " + workerId) } if (canCompleteRecovery) { completeRecovery() } case WorkerLatestState(workerId, executors, driverIds) => idToWorker.get(workerId) match { case Some(worker) => for (exec <- executors) { val executorMatches = worker.executors.exists { case (_, e) => e.application.id == exec.appId && e.id == exec.execId } if (!executorMatches) { // master doesn't recognize this executor. So just tell worker to kill it. worker.endpoint.send(KillExecutor(masterUrl, exec.appId, exec.execId)) } } for (driverId <- driverIds) { val driverMatches = worker.drivers.exists { case (id, _) => id == driverId } if (!driverMatches) { // master doesn't recognize this driver. So just tell worker to kill it. worker.endpoint.send(KillDriver(driverId)) } } case None => logWarning("Worker state from unknown worker: " + workerId) } case UnregisterApplication(applicationId) => logInfo(s"Received unregister request from application $applicationId") idToApp.get(applicationId).foreach(finishApplication) case CheckForWorkerTimeOut => timeOutDeadWorkers() } override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = { case RequestSubmitDriver(description) => if (state != RecoveryState.ALIVE) { val msg = s"${Utils.BACKUP_STANDALONE_MASTER_PREFIX}: $state. " + "Can only accept driver submissions in ALIVE state." context.reply(SubmitDriverResponse(self, false, None, msg)) } else { logInfo("Driver submitted " + description.command.mainClass) val driver = createDriver(description) persistenceEngine.addDriver(driver) waitingDrivers += driver drivers.add(driver) schedule() // TODO: It might be good to instead have the submission client poll the master to determine // the current status of the driver. For now it's simply "fire and forget". context.reply(SubmitDriverResponse(self, true, Some(driver.id), s"Driver successfully submitted as ${driver.id}")) } case RequestKillDriver(driverId) => if (state != RecoveryState.ALIVE) { val msg = s"${Utils.BACKUP_STANDALONE_MASTER_PREFIX}: $state. " + s"Can only kill drivers in ALIVE state." context.reply(KillDriverResponse(self, driverId, success = false, msg)) } else { logInfo("Asked to kill driver " + driverId) val driver = drivers.find(_.id == driverId) driver match { case Some(d) => if (waitingDrivers.contains(d)) { waitingDrivers -= d self.send(DriverStateChanged(driverId, DriverState.KILLED, None)) } else { // We just notify the worker to kill the driver here. The final bookkeeping occurs // on the return path when the worker submits a state change back to the master // to notify it that the driver was successfully killed. d.worker.foreach { w => w.endpoint.send(KillDriver(driverId)) } } // TODO: It would be nice for this to be a synchronous response val msg = s"Kill request for $driverId submitted" logInfo(msg) context.reply(KillDriverResponse(self, driverId, success = true, msg)) case None => val msg = s"Driver $driverId has already finished or does not exist" logWarning(msg) context.reply(KillDriverResponse(self, driverId, success = false, msg)) } } case RequestDriverStatus(driverId) => if (state != RecoveryState.ALIVE) { val msg = s"${Utils.BACKUP_STANDALONE_MASTER_PREFIX}: $state. " + "Can only request driver status in ALIVE state." context.reply( DriverStatusResponse(found = false, None, None, None, Some(new Exception(msg)))) } else { (drivers ++ completedDrivers).find(_.id == driverId) match { case Some(driver) => context.reply(DriverStatusResponse(found = true, Some(driver.state), driver.worker.map(_.id), driver.worker.map(_.hostPort), driver.exception)) case None => context.reply(DriverStatusResponse(found = false, None, None, None, None)) } } case RequestMasterState => context.reply(MasterStateResponse( address.host, address.port, restServerBoundPort, workers.toArray, apps.toArray, completedApps.toArray, drivers.toArray, completedDrivers.toArray, state)) case BoundPortsRequest => context.reply(BoundPortsResponse(address.port, webUi.boundPort, restServerBoundPort)) case RequestExecutors(appId, requestedTotal) => context.reply(handleRequestExecutors(appId, requestedTotal)) case KillExecutors(appId, executorIds) => val formattedExecutorIds = formatExecutorIds(executorIds) context.reply(handleKillExecutors(appId, formattedExecutorIds)) case DecommissionWorkersOnHosts(hostnames) => if (state != RecoveryState.STANDBY) { context.reply(decommissionWorkersOnHosts(hostnames)) } else { context.reply(0) } case ExecutorStateChanged(appId, execId, state, message, exitStatus) => val execOption = idToApp.get(appId).flatMap(app => app.executors.get(execId)) execOption match { case Some(exec) => val appInfo = idToApp(appId) val oldState = exec.state exec.state = state if (state == ExecutorState.RUNNING) { assert(oldState == ExecutorState.LAUNCHING, s"executor $execId state transfer from $oldState to RUNNING is illegal") appInfo.resetRetryCount() } exec.application.driver.send(ExecutorUpdated(execId, state, message, exitStatus, None)) if (ExecutorState.isFinished(state)) { // Remove this executor from the worker and app logInfo(s"Removing executor ${exec.fullId} because it is $state") // If an application has already finished, preserve its // state to display its information properly on the UI if (!appInfo.isFinished) { appInfo.removeExecutor(exec) } exec.worker.removeExecutor(exec) val normalExit = exitStatus == Some(0) // Only retry certain number of times so we don't go into an infinite loop. // Important note: this code path is not exercised by tests, so be very careful when // changing this `if` condition. // We also don't count failures from decommissioned workers since they are "expected." if (!normalExit && oldState != ExecutorState.DECOMMISSIONED && appInfo.incrementRetryCount() >= maxExecutorRetries && maxExecutorRetries >= 0) { // < 0 disables this application-killing path val execs = appInfo.executors.values if (!execs.exists(_.state == ExecutorState.RUNNING)) { logError(s"Application ${appInfo.desc.name} with ID ${appInfo.id} failed " + s"${appInfo.retryCount} times; removing it") removeApplication(appInfo, ApplicationState.FAILED) } } } schedule() case None => logWarning(s"Got status update for unknown executor $appId/$execId") } context.reply(true) } override def onDisconnected(address: RpcAddress): Unit = { // The disconnected client could've been either a worker or an app; remove whichever it was logInfo(s"$address got disassociated, removing it.") addressToWorker.get(address).foreach(removeWorker(_, s"${address} got disassociated")) addressToApp.get(address).foreach(finishApplication) if (state == RecoveryState.RECOVERING && canCompleteRecovery) { completeRecovery() } } private def canCompleteRecovery = workers.count(_.state == WorkerState.UNKNOWN) == 0 && apps.count(_.state == ApplicationState.UNKNOWN) == 0 private def beginRecovery(storedApps: Seq[ApplicationInfo], storedDrivers: Seq[DriverInfo], storedWorkers: Seq[WorkerInfo]): Unit = { for (app <- storedApps) { logInfo("Trying to recover app: " + app.id) try { registerApplication(app) app.state = ApplicationState.UNKNOWN app.driver.send(MasterChanged(self, masterWebUiUrl)) } catch { case e: Exception => logInfo("App " + app.id + " had exception on reconnect") } } for (driver <- storedDrivers) { // Here we just read in the list of drivers. Any drivers associated with now-lost workers // will be re-launched when we detect that the worker is missing. drivers += driver } for (worker <- storedWorkers) { logInfo("Trying to recover worker: " + worker.id) try { registerWorker(worker) worker.state = WorkerState.UNKNOWN worker.endpoint.send(MasterChanged(self, masterWebUiUrl)) } catch { case e: Exception => logInfo("Worker " + worker.id + " had exception on reconnect") } } } private def completeRecovery(): Unit = { // Ensure "only-once" recovery semantics using a short synchronization period. if (state != RecoveryState.RECOVERING) { return } state = RecoveryState.COMPLETING_RECOVERY // Kill off any workers and apps that didn't respond to us. workers.filter(_.state == WorkerState.UNKNOWN).foreach( removeWorker(_, "Not responding for recovery")) apps.filter(_.state == ApplicationState.UNKNOWN).foreach(finishApplication) // Update the state of recovered apps to RUNNING apps.filter(_.state == ApplicationState.WAITING).foreach(_.state = ApplicationState.RUNNING) // Reschedule drivers which were not claimed by any workers drivers.filter(_.worker.isEmpty).foreach { d => logWarning(s"Driver ${d.id} was not found after master recovery") if (d.desc.supervise) { logWarning(s"Re-launching ${d.id}") relaunchDriver(d) } else { removeDriver(d.id, DriverState.ERROR, None) logWarning(s"Did not re-launch ${d.id} because it was not supervised") } } state = RecoveryState.ALIVE schedule() logInfo("Recovery complete - resuming operations!") } /** * Schedule executors to be launched on the workers. * Returns an array containing number of cores assigned to each worker. * * There are two modes of launching executors. The first attempts to spread out an application's * executors on as many workers as possible, while the second does the opposite (i.e. launch them * on as few workers as possible). The former is usually better for data locality purposes and is * the default. * * The number of cores assigned to each executor is configurable. When this is explicitly set, * multiple executors from the same application may be launched on the same worker if the worker * has enough cores and memory. Otherwise, each executor grabs all the cores available on the * worker by default, in which case only one executor per application may be launched on each * worker during one single schedule iteration. * Note that when `spark.executor.cores` is not set, we may still launch multiple executors from * the same application on the same worker. Consider appA and appB both have one executor running * on worker1, and appA.coresLeft > 0, then appB is finished and release all its cores on worker1, * thus for the next schedule iteration, appA launches a new executor that grabs all the free * cores on worker1, therefore we get multiple executors from appA running on worker1. * * It is important to allocate coresPerExecutor on each worker at a time (instead of 1 core * at a time). Consider the following example: cluster has 4 workers with 16 cores each. * User requests 3 executors (spark.cores.max = 48, spark.executor.cores = 16). If 1 core is * allocated at a time, 12 cores from each worker would be assigned to each executor. * Since 12 < 16, no executors would launch [SPARK-8881]. */ private def scheduleExecutorsOnWorkers( app: ApplicationInfo, usableWorkers: Array[WorkerInfo], spreadOutApps: Boolean): Array[Int] = { val coresPerExecutor = app.desc.coresPerExecutor val minCoresPerExecutor = coresPerExecutor.getOrElse(1) val oneExecutorPerWorker = coresPerExecutor.isEmpty val memoryPerExecutor = app.desc.memoryPerExecutorMB val resourceReqsPerExecutor = app.desc.resourceReqsPerExecutor val numUsable = usableWorkers.length val assignedCores = new Array[Int](numUsable) // Number of cores to give to each worker val assignedExecutors = new Array[Int](numUsable) // Number of new executors on each worker var coresToAssign = math.min(app.coresLeft, usableWorkers.map(_.coresFree).sum) /** Return whether the specified worker can launch an executor for this app. */ def canLaunchExecutorForApp(pos: Int): Boolean = { val keepScheduling = coresToAssign >= minCoresPerExecutor val enoughCores = usableWorkers(pos).coresFree - assignedCores(pos) >= minCoresPerExecutor val assignedExecutorNum = assignedExecutors(pos) // If we allow multiple executors per worker, then we can always launch new executors. // Otherwise, if there is already an executor on this worker, just give it more cores. val launchingNewExecutor = !oneExecutorPerWorker || assignedExecutorNum == 0 if (launchingNewExecutor) { val assignedMemory = assignedExecutorNum * memoryPerExecutor val enoughMemory = usableWorkers(pos).memoryFree - assignedMemory >= memoryPerExecutor val assignedResources = resourceReqsPerExecutor.map { req => req.resourceName -> req.amount * assignedExecutorNum }.toMap val resourcesFree = usableWorkers(pos).resourcesAmountFree.map { case (rName, free) => rName -> (free - assignedResources.getOrElse(rName, 0)) } val enoughResources = ResourceUtils.resourcesMeetRequirements( resourcesFree, resourceReqsPerExecutor) val underLimit = assignedExecutors.sum + app.executors.size < app.executorLimit keepScheduling && enoughCores && enoughMemory && enoughResources && underLimit } else { // We're adding cores to an existing executor, so no need // to check memory and executor limits keepScheduling && enoughCores } } // Keep launching executors until no more workers can accommodate any // more executors, or if we have reached this application's limits var freeWorkers = (0 until numUsable).filter(canLaunchExecutorForApp) while (freeWorkers.nonEmpty) { freeWorkers.foreach { pos => var keepScheduling = true while (keepScheduling && canLaunchExecutorForApp(pos)) { coresToAssign -= minCoresPerExecutor assignedCores(pos) += minCoresPerExecutor // If we are launching one executor per worker, then every iteration assigns 1 core // to the executor. Otherwise, every iteration assigns cores to a new executor. if (oneExecutorPerWorker) { assignedExecutors(pos) = 1 } else { assignedExecutors(pos) += 1 } // Spreading out an application means spreading out its executors across as // many workers as possible. If we are not spreading out, then we should keep // scheduling executors on this worker until we use all of its resources. // Otherwise, just move on to the next worker. if (spreadOutApps) { keepScheduling = false } } } freeWorkers = freeWorkers.filter(canLaunchExecutorForApp) } assignedCores } /** * Schedule and launch executors on workers */ private def startExecutorsOnWorkers(): Unit = { // Right now this is a very simple FIFO scheduler. We keep trying to fit in the first app // in the queue, then the second app, etc. for (app <- waitingApps) { val coresPerExecutor = app.desc.coresPerExecutor.getOrElse(1) // If the cores left is less than the coresPerExecutor,the cores left will not be allocated if (app.coresLeft >= coresPerExecutor) { // Filter out workers that don't have enough resources to launch an executor val usableWorkers = workers.toArray.filter(_.state == WorkerState.ALIVE) .filter(canLaunchExecutor(_, app.desc)) .sortBy(_.coresFree).reverse val appMayHang = waitingApps.length == 1 && waitingApps.head.executors.isEmpty && usableWorkers.isEmpty if (appMayHang) { logWarning(s"App ${app.id} requires more resource than any of Workers could have.") } val assignedCores = scheduleExecutorsOnWorkers(app, usableWorkers, spreadOutApps) // Now that we've decided how many cores to allocate on each worker, let's allocate them for (pos <- 0 until usableWorkers.length if assignedCores(pos) > 0) { allocateWorkerResourceToExecutors( app, assignedCores(pos), app.desc.coresPerExecutor, usableWorkers(pos)) } } } } /** * Allocate a worker's resources to one or more executors. * @param app the info of the application which the executors belong to * @param assignedCores number of cores on this worker for this application * @param coresPerExecutor number of cores per executor * @param worker the worker info */ private def allocateWorkerResourceToExecutors( app: ApplicationInfo, assignedCores: Int, coresPerExecutor: Option[Int], worker: WorkerInfo): Unit = { // If the number of cores per executor is specified, we divide the cores assigned // to this worker evenly among the executors with no remainder. // Otherwise, we launch a single executor that grabs all the assignedCores on this worker. val numExecutors = coresPerExecutor.map { assignedCores / _ }.getOrElse(1) val coresToAssign = coresPerExecutor.getOrElse(assignedCores) for (i <- 1 to numExecutors) { val allocated = worker.acquireResources(app.desc.resourceReqsPerExecutor) val exec = app.addExecutor(worker, coresToAssign, allocated) launchExecutor(worker, exec) app.state = ApplicationState.RUNNING } } private def canLaunch( worker: WorkerInfo, memoryReq: Int, coresReq: Int, resourceRequirements: Seq[ResourceRequirement]) : Boolean = { val enoughMem = worker.memoryFree >= memoryReq val enoughCores = worker.coresFree >= coresReq val enoughResources = ResourceUtils.resourcesMeetRequirements( worker.resourcesAmountFree, resourceRequirements) enoughMem && enoughCores && enoughResources } /** * @return whether the worker could launch the driver represented by DriverDescription */ private def canLaunchDriver(worker: WorkerInfo, desc: DriverDescription): Boolean = { canLaunch(worker, desc.mem, desc.cores, desc.resourceReqs) } /** * @return whether the worker could launch the executor according to application's requirement */ private def canLaunchExecutor(worker: WorkerInfo, desc: ApplicationDescription): Boolean = { canLaunch( worker, desc.memoryPerExecutorMB, desc.coresPerExecutor.getOrElse(1), desc.resourceReqsPerExecutor) } /** * Schedule the currently available resources among waiting apps. This method will be called * every time a new app joins or resource availability changes. */ private def schedule(): Unit = { if (state != RecoveryState.ALIVE) { return } // Drivers take strict precedence over executors val shuffledAliveWorkers = Random.shuffle(workers.toSeq.filter(_.state == WorkerState.ALIVE)) val numWorkersAlive = shuffledAliveWorkers.size var curPos = 0 for (driver <- waitingDrivers.toList) { // iterate over a copy of waitingDrivers // We assign workers to each waiting driver in a round-robin fashion. For each driver, we // start from the last worker that was assigned a driver, and continue onwards until we have // explored all alive workers. var launched = false var isClusterIdle = true var numWorkersVisited = 0 while (numWorkersVisited < numWorkersAlive && !launched) { val worker = shuffledAliveWorkers(curPos) isClusterIdle = worker.drivers.isEmpty && worker.executors.isEmpty numWorkersVisited += 1 if (canLaunchDriver(worker, driver.desc)) { val allocated = worker.acquireResources(driver.desc.resourceReqs) driver.withResources(allocated) launchDriver(worker, driver) waitingDrivers -= driver launched = true } curPos = (curPos + 1) % numWorkersAlive } if (!launched && isClusterIdle) { logWarning(s"Driver ${driver.id} requires more resource than any of Workers could have.") } } startExecutorsOnWorkers() } private def launchExecutor(worker: WorkerInfo, exec: ExecutorDesc): Unit = { logInfo("Launching executor " + exec.fullId + " on worker " + worker.id) worker.addExecutor(exec) worker.endpoint.send(LaunchExecutor(masterUrl, exec.application.id, exec.id, exec.application.desc, exec.cores, exec.memory, exec.resources)) exec.application.driver.send( ExecutorAdded(exec.id, worker.id, worker.hostPort, exec.cores, exec.memory)) } private def registerWorker(worker: WorkerInfo): Boolean = { // There may be one or more refs to dead workers on this same node (w/ different ID's), // remove them. workers.filter { w => (w.host == worker.host && w.port == worker.port) && (w.state == WorkerState.DEAD) }.foreach { w => workers -= w } val workerAddress = worker.endpoint.address if (addressToWorker.contains(workerAddress)) { val oldWorker = addressToWorker(workerAddress) if (oldWorker.state == WorkerState.UNKNOWN) { // A worker registering from UNKNOWN implies that the worker was restarted during recovery. // The old worker must thus be dead, so we will remove it and accept the new worker. removeWorker(oldWorker, "Worker replaced by a new worker with same address") } else { logInfo("Attempted to re-register worker at same address: " + workerAddress) return false } } workers += worker idToWorker(worker.id) = worker addressToWorker(workerAddress) = worker true } /** * Decommission all workers that are active on any of the given hostnames. The decommissioning is * asynchronously done by enqueueing WorkerDecommission messages to self. No checks are done about * the prior state of the worker. So an already decommissioned worker will match as well. * * @param hostnames: A list of hostnames without the ports. Like "localhost", "foo.bar.com" etc * * Returns the number of workers that matched the hostnames. */ private def decommissionWorkersOnHosts(hostnames: Seq[String]): Integer = { val hostnamesSet = hostnames.map(_.toLowerCase(Locale.ROOT)).toSet val workersToRemove = addressToWorker .filterKeys(addr => hostnamesSet.contains(addr.host.toLowerCase(Locale.ROOT))) .values val workersToRemoveHostPorts = workersToRemove.map(_.hostPort) logInfo(s"Decommissioning the workers with host:ports ${workersToRemoveHostPorts}") // The workers are removed async to avoid blocking the receive loop for the entire batch self.send(DecommissionWorkers(workersToRemove.map(_.id).toSeq)) // Return the count of workers actually removed workersToRemove.size } private def decommissionWorker(worker: WorkerInfo): Unit = { if (worker.state != WorkerState.DECOMMISSIONED) { logInfo("Decommissioning worker %s on %s:%d".format(worker.id, worker.host, worker.port)) worker.setState(WorkerState.DECOMMISSIONED) for (exec <- worker.executors.values) { logInfo("Telling app of decommission executors") exec.application.driver.send(ExecutorUpdated( exec.id, ExecutorState.DECOMMISSIONED, Some("worker decommissioned"), None, // worker host is being set here to let the driver know that the host (aka. worker) // is also being decommissioned. So the driver can unregister all the shuffle map // statues located at this host when it receives the executor lost event. Some(worker.host))) exec.state = ExecutorState.DECOMMISSIONED exec.application.removeExecutor(exec) } // On recovery do not add a decommissioned executor persistenceEngine.removeWorker(worker) } else { logWarning("Skipping decommissioning worker %s on %s:%d as worker is already decommissioned". format(worker.id, worker.host, worker.port)) } } private def removeWorker(worker: WorkerInfo, msg: String): Unit = { logInfo("Removing worker " + worker.id + " on " + worker.host + ":" + worker.port) worker.setState(WorkerState.DEAD) idToWorker -= worker.id addressToWorker -= worker.endpoint.address for (exec <- worker.executors.values) { logInfo("Telling app of lost executor: " + exec.id) exec.application.driver.send(ExecutorUpdated( exec.id, ExecutorState.LOST, Some("worker lost"), None, Some(worker.host))) exec.state = ExecutorState.LOST exec.application.removeExecutor(exec) } for (driver <- worker.drivers.values) { if (driver.desc.supervise) { logInfo(s"Re-launching ${driver.id}") relaunchDriver(driver) } else { logInfo(s"Not re-launching ${driver.id} because it was not supervised") removeDriver(driver.id, DriverState.ERROR, None) } } logInfo(s"Telling app of lost worker: " + worker.id) apps.filterNot(completedApps.contains(_)).foreach { app => app.driver.send(WorkerRemoved(worker.id, worker.host, msg)) } persistenceEngine.removeWorker(worker) schedule() } private def relaunchDriver(driver: DriverInfo): Unit = { // We must setup a new driver with a new driver id here, because the original driver may // be still running. Consider this scenario: a worker is network partitioned with master, // the master then relaunches driver driverID1 with a driver id driverID2, then the worker // reconnects to master. From this point on, if driverID2 is equal to driverID1, then master // can not distinguish the statusUpdate of the original driver and the newly relaunched one, // for example, when DriverStateChanged(driverID1, KILLED) arrives at master, master will // remove driverID1, so the newly relaunched driver disappears too. See SPARK-19900 for details. removeDriver(driver.id, DriverState.RELAUNCHING, None) val newDriver = createDriver(driver.desc) persistenceEngine.addDriver(newDriver) drivers.add(newDriver) waitingDrivers += newDriver schedule() } private def createApplication(desc: ApplicationDescription, driver: RpcEndpointRef): ApplicationInfo = { val now = System.currentTimeMillis() val date = new Date(now) val appId = newApplicationId(date) new ApplicationInfo(now, appId, desc, date, driver, defaultCores) } private def registerApplication(app: ApplicationInfo): Unit = { val appAddress = app.driver.address if (addressToApp.contains(appAddress)) { logInfo("Attempted to re-register application at same address: " + appAddress) return } applicationMetricsSystem.registerSource(app.appSource) apps += app idToApp(app.id) = app endpointToApp(app.driver) = app addressToApp(appAddress) = app waitingApps += app } private def finishApplication(app: ApplicationInfo): Unit = { removeApplication(app, ApplicationState.FINISHED) } def removeApplication(app: ApplicationInfo, state: ApplicationState.Value): Unit = { if (apps.contains(app)) { logInfo("Removing app " + app.id) apps -= app idToApp -= app.id endpointToApp -= app.driver addressToApp -= app.driver.address if (completedApps.size >= retainedApplications) { val toRemove = math.max(retainedApplications / 10, 1) completedApps.take(toRemove).foreach { a => applicationMetricsSystem.removeSource(a.appSource) } completedApps.trimStart(toRemove) } completedApps += app // Remember it in our history waitingApps -= app for (exec <- app.executors.values) { killExecutor(exec) } app.markFinished(state) if (state != ApplicationState.FINISHED) { app.driver.send(ApplicationRemoved(state.toString)) } persistenceEngine.removeApplication(app) schedule() // Tell all workers that the application has finished, so they can clean up any app state. workers.foreach { w => w.endpoint.send(ApplicationFinished(app.id)) } } } /** * Handle a request to set the target number of executors for this application. * * If the executor limit is adjusted upwards, new executors will be launched provided * that there are workers with sufficient resources. If it is adjusted downwards, however, * we do not kill existing executors until we explicitly receive a kill request. * * @return whether the application has previously registered with this Master. */ private def handleRequestExecutors(appId: String, requestedTotal: Int): Boolean = { idToApp.get(appId) match { case Some(appInfo) => logInfo(s"Application $appId requested to set total executors to $requestedTotal.") appInfo.executorLimit = requestedTotal schedule() true case None => logWarning(s"Unknown application $appId requested $requestedTotal total executors.") false } } /** * Handle a kill request from the given application. * * This method assumes the executor limit has already been adjusted downwards through * a separate [[RequestExecutors]] message, such that we do not launch new executors * immediately after the old ones are removed. * * @return whether the application has previously registered with this Master. */ private def handleKillExecutors(appId: String, executorIds: Seq[Int]): Boolean = { idToApp.get(appId) match { case Some(appInfo) => logInfo(s"Application $appId requests to kill executors: " + executorIds.mkString(", ")) val (known, unknown) = executorIds.partition(appInfo.executors.contains) known.foreach { executorId => val desc = appInfo.executors(executorId) appInfo.removeExecutor(desc) killExecutor(desc) } if (unknown.nonEmpty) { logWarning(s"Application $appId attempted to kill non-existent executors: " + unknown.mkString(", ")) } schedule() true case None => logWarning(s"Unregistered application $appId requested us to kill executors!") false } } /** * Cast the given executor IDs to integers and filter out the ones that fail. * * All executors IDs should be integers since we launched these executors. However, * the kill interface on the driver side accepts arbitrary strings, so we need to * handle non-integer executor IDs just to be safe. */ private def formatExecutorIds(executorIds: Seq[String]): Seq[Int] = { executorIds.flatMap { executorId => try { Some(executorId.toInt) } catch { case e: NumberFormatException => logError(s"Encountered executor with a non-integer ID: $executorId. Ignoring") None } } } /** * Ask the worker on which the specified executor is launched to kill the executor. */ private def killExecutor(exec: ExecutorDesc): Unit = { exec.worker.removeExecutor(exec) exec.worker.endpoint.send(KillExecutor(masterUrl, exec.application.id, exec.id)) exec.state = ExecutorState.KILLED } /** Generate a new app ID given an app's submission date */ private def newApplicationId(submitDate: Date): String = { val appId = "app-%s-%04d".format(createDateFormat.format(submitDate), nextAppNumber) nextAppNumber += 1 appId } /** Check for, and remove, any timed-out workers */ private def timeOutDeadWorkers(): Unit = { // Copy the workers into an array so we don't modify the hashset while iterating through it val currentTime = System.currentTimeMillis() val toRemove = workers.filter(_.lastHeartbeat < currentTime - workerTimeoutMs).toArray for (worker <- toRemove) { if (worker.state != WorkerState.DEAD) { val workerTimeoutSecs = TimeUnit.MILLISECONDS.toSeconds(workerTimeoutMs) logWarning("Removing %s because we got no heartbeat in %d seconds".format( worker.id, workerTimeoutSecs)) removeWorker(worker, s"Not receiving heartbeat for $workerTimeoutSecs seconds") } else { if (worker.lastHeartbeat < currentTime - ((reaperIterations + 1) * workerTimeoutMs)) { workers -= worker // we've seen this DEAD worker in the UI, etc. for long enough; cull it } } } } private def newDriverId(submitDate: Date): String = { val appId = "driver-%s-%04d".format(createDateFormat.format(submitDate), nextDriverNumber) nextDriverNumber += 1 appId } private def createDriver(desc: DriverDescription): DriverInfo = { val now = System.currentTimeMillis() val date = new Date(now) new DriverInfo(now, newDriverId(date), desc, date) } private def launchDriver(worker: WorkerInfo, driver: DriverInfo): Unit = { logInfo("Launching driver " + driver.id + " on worker " + worker.id) worker.addDriver(driver) driver.worker = Some(worker) worker.endpoint.send(LaunchDriver(driver.id, driver.desc, driver.resources)) driver.state = DriverState.RUNNING } private def removeDriver( driverId: String, finalState: DriverState, exception: Option[Exception]): Unit = { drivers.find(d => d.id == driverId) match { case Some(driver) => logInfo(s"Removing driver: $driverId") drivers -= driver if (completedDrivers.size >= retainedDrivers) { val toRemove = math.max(retainedDrivers / 10, 1) completedDrivers.trimStart(toRemove) } completedDrivers += driver persistenceEngine.removeDriver(driver) driver.state = finalState driver.exception = exception driver.worker.foreach(w => w.removeDriver(driver)) schedule() case None => logWarning(s"Asked to remove unknown driver: $driverId") } } } private[deploy] object Master extends Logging { val SYSTEM_NAME = "sparkMaster" val ENDPOINT_NAME = "Master" def main(argStrings: Array[String]): Unit = { Thread.setDefaultUncaughtExceptionHandler(new SparkUncaughtExceptionHandler( exitOnUncaughtException = false)) Utils.initDaemon(log) val conf = new SparkConf val args = new MasterArguments(argStrings, conf) val (rpcEnv, _, _) = startRpcEnvAndEndpoint(args.host, args.port, args.webUiPort, conf) rpcEnv.awaitTermination() } /** * Start the Master and return a three tuple of: * (1) The Master RpcEnv * (2) The web UI bound port * (3) The REST server bound port, if any */ def startRpcEnvAndEndpoint( host: String, port: Int, webUiPort: Int, conf: SparkConf): (RpcEnv, Int, Option[Int]) = { val securityMgr = new SecurityManager(conf) val rpcEnv = RpcEnv.create(SYSTEM_NAME, host, port, conf, securityMgr) val masterEndpoint = rpcEnv.setupEndpoint(ENDPOINT_NAME, new Master(rpcEnv, rpcEnv.address, webUiPort, securityMgr, conf)) val portsResponse = masterEndpoint.askSync[BoundPortsResponse](BoundPortsRequest) (rpcEnv, portsResponse.webUIPort, portsResponse.restPort) } }
apache-2.0
sebastiankirsch/spring-boot
spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java
7114
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.json; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Field; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.core.ResolvableType; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.util.FileCopyUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AbstractJsonMarshalTester}. * * @author Phillip Webb */ public abstract class AbstractJsonMarshalTesterTests { private static final String JSON = "{\"name\":\"Spring\",\"age\":123}"; private static final String MAP_JSON = "{\"a\":" + JSON + "}"; private static final String ARRAY_JSON = "[" + JSON + "]"; private static final ExampleObject OBJECT = createExampleObject("Spring", 123); private static final ResolvableType TYPE = ResolvableType .forClass(ExampleObject.class); @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void writeShouldReturnJsonContent() throws Exception { JsonContent<Object> content = createTester(TYPE).write(OBJECT); assertThat(content).isEqualToJson(JSON); } @Test public void writeListShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("listOfExampleObject"); List<ExampleObject> value = Collections.singletonList(OBJECT); JsonContent<Object> content = createTester(type).write(value); assertThat(content).isEqualToJson(ARRAY_JSON); } @Test public void writeArrayShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("arrayOfExampleObject"); ExampleObject[] value = new ExampleObject[] { OBJECT }; JsonContent<Object> content = createTester(type).write(value); assertThat(content).isEqualToJson(ARRAY_JSON); } @Test public void writeMapShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("mapOfExampleObject"); Map<String, Object> value = new LinkedHashMap<>(); value.put("a", OBJECT); JsonContent<Object> content = createTester(type).write(value); assertThat(content).isEqualToJson(MAP_JSON); } @Test public void createWhenResourceLoadClassIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ResourceLoadClass must not be null"); createTester(null, ResolvableType.forClass(ExampleObject.class)); } @Test public void createWhenTypeIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Type must not be null"); createTester(getClass(), null); } @Test public void parseBytesShouldReturnObject() throws Exception { AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.parse(JSON.getBytes())).isEqualTo(OBJECT); } @Test public void parseStringShouldReturnObject() throws Exception { AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.parse(JSON)).isEqualTo(OBJECT); } @Test public void readResourcePathShouldReturnObject() throws Exception { AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read("example.json")).isEqualTo(OBJECT); } @Test public void readFileShouldReturnObject() throws Exception { File file = this.temp.newFile("example.json"); FileCopyUtils.copy(JSON.getBytes(), file); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(file)).isEqualTo(OBJECT); } @Test public void readInputStreamShouldReturnObject() throws Exception { InputStream stream = new ByteArrayInputStream(JSON.getBytes()); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(stream)).isEqualTo(OBJECT); } @Test public void readResourceShouldReturnObject() throws Exception { Resource resource = new ByteArrayResource(JSON.getBytes()); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(resource)).isEqualTo(OBJECT); } @Test public void readReaderShouldReturnObject() throws Exception { Reader reader = new StringReader(JSON); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(reader)).isEqualTo(OBJECT); } @Test public void parseListShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("listOfExampleObject"); AbstractJsonMarshalTester<Object> tester = createTester(type); assertThat(tester.parse(ARRAY_JSON)).asList().containsOnly(OBJECT); } @Test public void parseArrayShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("arrayOfExampleObject"); AbstractJsonMarshalTester<Object> tester = createTester(type); assertThat(tester.parse(ARRAY_JSON)).asArray().containsOnly(OBJECT); } @Test public void parseMapShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("mapOfExampleObject"); AbstractJsonMarshalTester<Object> tester = createTester(type); assertThat(tester.parse(MAP_JSON)).asMap().containsEntry("a", OBJECT); } protected static final ExampleObject createExampleObject(String name, int age) { ExampleObject exampleObject = new ExampleObject(); exampleObject.setName(name); exampleObject.setAge(age); return exampleObject; } protected final AbstractJsonMarshalTester<Object> createTester(ResolvableType type) { return createTester(AbstractJsonMarshalTesterTests.class, type); } protected abstract AbstractJsonMarshalTester<Object> createTester( Class<?> resourceLoadClass, ResolvableType type); /** * Access to field backed by {@link ResolvableType}. */ public static class ResolvableTypes { public List<ExampleObject> listOfExampleObject; public ExampleObject[] arrayOfExampleObject; public Map<String, ExampleObject> mapOfExampleObject; public static ResolvableType get(String name) { Field field = ReflectionUtils.findField(ResolvableTypes.class, name); return ResolvableType.forField(field); } } }
apache-2.0
bryanchou/cat
cat-home/src/main/java/com/dianping/cat/report/page/dependency/graph/TopologyGraphManager.java
9259
package com.dianping.cat.report.page.dependency.graph; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.unidal.dal.jdbc.DalException; import org.unidal.helper.Threads; import org.unidal.helper.Threads.Task; import org.unidal.lookup.annotation.Inject; import com.dianping.cat.Cat; import com.dianping.cat.Constants; import com.dianping.cat.config.server.ServerConfigManager; import com.dianping.cat.config.server.ServerFilterConfigManager; import com.dianping.cat.consumer.company.model.entity.Domain; import com.dianping.cat.consumer.company.model.entity.ProductLine; import com.dianping.cat.consumer.config.ProductLineConfigManager; import com.dianping.cat.consumer.dependency.DependencyAnalyzer; import com.dianping.cat.consumer.dependency.model.entity.DependencyReport; import com.dianping.cat.helper.TimeHelper; import com.dianping.cat.home.dal.report.TopologyGraphDao; import com.dianping.cat.home.dal.report.TopologyGraphEntity; import com.dianping.cat.home.dependency.graph.entity.TopologyEdge; import com.dianping.cat.home.dependency.graph.entity.TopologyGraph; import com.dianping.cat.home.dependency.graph.entity.TopologyNode; import com.dianping.cat.home.dependency.graph.transform.DefaultNativeParser; import com.dianping.cat.message.Transaction; import com.dianping.cat.report.service.ModelPeriod; import com.dianping.cat.report.service.ModelRequest; import com.dianping.cat.report.service.ModelResponse; import com.dianping.cat.report.service.ModelService; public class TopologyGraphManager implements Initializable, LogEnabled { @Inject(type = ModelService.class, value = DependencyAnalyzer.ID) private ModelService<DependencyReport> m_service; @Inject private DependencyItemBuilder m_itemBuilder; @Inject private ProductLineConfigManager m_productLineConfigManger; @Inject private ServerConfigManager m_manager; @Inject private ServerFilterConfigManager m_serverFilterConfigManager; @Inject private TopologyGraphDao m_topologyGraphDao; private TopologyGraphBuilder m_currentBuilder; private Map<Long, TopologyGraph> m_topologyGraphs = new ConcurrentHashMap<Long, TopologyGraph>(); private Logger m_logger; public ProductLinesDashboard buildDependencyDashboard(long time) { TopologyGraph topologyGraph = queryTopologyGraph(time); ProductLinesDashboard dashboardGraph = new ProductLinesDashboard(); Set<String> allDomains = new HashSet<String>(); if (topologyGraph != null) { Map<String, ProductLine> groups = m_productLineConfigManger.queryApplicationProductLines(); for (Entry<String, ProductLine> entry : groups.entrySet()) { String realName = entry.getValue().getTitle(); Map<String, Domain> domains = entry.getValue().getDomains(); for (Domain domain : domains.values()) { String nodeName = domain.getId(); TopologyNode node = topologyGraph.findTopologyNode(nodeName); allDomains.add(nodeName); if (node != null) { dashboardGraph.addNode(realName, m_currentBuilder.cloneNode(node)); } } } Map<String, TopologyEdge> edges = topologyGraph.getEdges(); for (TopologyEdge edge : edges.values()) { String self = edge.getSelf(); String to = edge.getTarget(); if (allDomains.contains(self) && allDomains.contains(to)) { dashboardGraph.addEdge(m_currentBuilder.cloneEdge(edge)); } } } return dashboardGraph.sortByNodeNumber(); } public TopologyGraph buildTopologyGraph(String domain, long time) { TopologyGraph all = queryTopologyGraph(time); TopologyGraph topylogyGraph = new TopologyGraph(); topylogyGraph.setId(domain); topylogyGraph.setType(GraphConstrant.PROJECT); topylogyGraph.setStatus(GraphConstrant.OK); if (all != null && m_currentBuilder != null) { TopologyNode node = all.findTopologyNode(domain); if (node != null) { topylogyGraph.setDes(node.getDes()); topylogyGraph.setStatus(node.getStatus()); topylogyGraph.setType(node.getType()); } Collection<TopologyEdge> edges = all.getEdges().values(); for (TopologyEdge edge : edges) { String self = edge.getSelf(); String target = edge.getTarget(); TopologyEdge cloneEdge = m_currentBuilder.cloneEdge(edge); if (self.equals(domain)) { TopologyNode other = all.findTopologyNode(target); if (other != null) { topylogyGraph.addTopologyNode(m_currentBuilder.cloneNode(other)); } else { topylogyGraph.addTopologyNode(m_currentBuilder.createNode(target)); } edge.setOpposite(false); topylogyGraph.addTopologyEdge(cloneEdge); } else if (target.equals(domain)) { TopologyNode other = all.findTopologyNode(self); if (other != null) { topylogyGraph.addTopologyNode(m_currentBuilder.cloneNode(other)); } else { topylogyGraph.addTopologyNode(m_currentBuilder.createNode(target)); } cloneEdge.setTarget(edge.getSelf()); cloneEdge.setSelf(edge.getTarget()); cloneEdge.setOpposite(true); topylogyGraph.addTopologyEdge(cloneEdge); } } } return topylogyGraph; } @Override public void enableLogging(Logger logger) { m_logger = logger; } @Override public void initialize() throws InitializationException { if (m_manager.isJobMachine()) { Threads.forGroup("cat").start(new DependencyReloadTask()); } } public TopologyGraph queryGraphFromDB(long time) { try { com.dianping.cat.home.dal.report.TopologyGraph topologyGraph = m_topologyGraphDao.findByPeriod(new Date(time), TopologyGraphEntity.READSET_FULL); if (topologyGraph != null) { byte[] content = topologyGraph.getContent(); return DefaultNativeParser.parse(content); } } catch (DalException e) { Cat.logError(e); } return null; } private TopologyGraph queryGraphFromMemory(long time) { TopologyGraph graph = m_topologyGraphs.get(time); long current = System.currentTimeMillis(); long minute = current - current % TimeHelper.ONE_MINUTE; if ((minute - time) <= 3 * TimeHelper.ONE_MINUTE && graph == null) { graph = m_topologyGraphs.get(time - TimeHelper.ONE_MINUTE); if (graph == null) { graph = m_topologyGraphs.get(time - TimeHelper.ONE_MINUTE * 2); } } return graph; } private TopologyGraph queryTopologyGraph(long time) { ModelPeriod period = ModelPeriod.getByTime(time); if (period.isHistorical()) { return queryGraphFromDB(time); } else { return queryGraphFromMemory(time); } } private class DependencyReloadTask implements Task { private void buildDependencyInfo(TopologyGraphBuilder builder, String domain) { if (m_serverFilterConfigManager.validateDomain(domain)) { ModelRequest request = new ModelRequest(domain, ModelPeriod.CURRENT.getStartTime()); if (m_service.isEligable(request)) { ModelResponse<DependencyReport> response = m_service.invoke(request); DependencyReport report = response.getModel(); if (report != null) { builder.visitDependencyReport(report); } } else { m_logger.warn(String.format("Can't get dependency report of %s", domain)); } } } @Override public String getName() { return "TopologyGraphReload"; } private Collection<String> queryAllDomains() { ModelRequest request = new ModelRequest(Constants.CAT, ModelPeriod.CURRENT.getStartTime()); if (m_service.isEligable(request)) { ModelResponse<DependencyReport> response = m_service.invoke(request); DependencyReport report = response.getModel(); return report.getDomainNames(); } return new HashSet<String>(); } @Override public void run() { boolean active = TimeHelper.sleepToNextMinute(); while (active) { Transaction t = Cat.newTransaction("ReloadTask", "Dependency"); long current = System.currentTimeMillis(); try { TopologyGraphBuilder builder = new TopologyGraphBuilder().setItemBuilder(m_itemBuilder); Collection<String> domains = queryAllDomains(); for (String domain : domains) { try { buildDependencyInfo(builder, domain); } catch (Exception e) { Cat.logError(e); } } Map<Long, TopologyGraph> graphs = builder.getGraphs(); for (Entry<Long, TopologyGraph> entry : graphs.entrySet()) { m_topologyGraphs.put(entry.getKey(), entry.getValue()); m_topologyGraphs.remove(entry.getKey() - TimeHelper.ONE_HOUR * 2); } m_currentBuilder = builder; t.setStatus(Transaction.SUCCESS); } catch (Exception e) { m_logger.error(e.getMessage(), e); t.setStatus(e); } finally { t.complete(); } long duration = System.currentTimeMillis() - current; try { int maxDuration = 60 * 1000; if (duration < maxDuration) { Thread.sleep(maxDuration - duration); } } catch (InterruptedException e) { active = false; } } } @Override public void shutdown() { } } }
apache-2.0
michaelgallacher/intellij-community
platform/lang-impl/src/com/intellij/refactoring/memberPushDown/AbstractPushDownDialog.java
4609
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.memberPushDown; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.classMembers.MemberInfoBase; import com.intellij.refactoring.classMembers.MemberInfoChange; import com.intellij.refactoring.classMembers.MemberInfoModel; import com.intellij.refactoring.ui.AbstractMemberSelectionPanel; import com.intellij.refactoring.ui.DocCommentPanel; import com.intellij.refactoring.ui.RefactoringDialog; import com.intellij.refactoring.util.DocCommentPolicy; import com.intellij.usageView.UsageViewUtil; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public abstract class AbstractPushDownDialog<MemberInfo extends MemberInfoBase<Member>, Member extends PsiElement, Klass extends PsiElement> extends RefactoringDialog { private final List<MemberInfo> myMemberInfos; private final Klass myClass; private DocCommentPanel myJavaDocPanel; private MemberInfoModel<Member, MemberInfo> myMemberInfoModel; public AbstractPushDownDialog(Project project, MemberInfo[] memberInfos, Klass aClass) { super(project, true); myMemberInfos = Arrays.asList(memberInfos); myClass = aClass; setTitle(RefactoringBundle.message("push.members.down.title")); init(); } public List<MemberInfo> getMemberInfos() { return myMemberInfos; } public Klass getSourceClass() { return myClass; } public ArrayList<MemberInfo> getSelectedMemberInfos() { return myMemberInfos.stream() .filter(info -> info.isChecked() && myMemberInfoModel.isMemberEnabled(info)) .collect(Collectors.toCollection(ArrayList::new)); } protected String getDimensionServiceKey() { return "#com.intellij.refactoring.memberPushDown.PushDownDialog"; } protected JComponent createNorthPanel() { GridBagConstraints gbConstraints = new GridBagConstraints(); JPanel panel = new JPanel(new GridBagLayout()); gbConstraints.insets = new Insets(4, 0, 10, 8); gbConstraints.weighty = 1; gbConstraints.weightx = 1; gbConstraints.gridy = 0; gbConstraints.gridwidth = GridBagConstraints.REMAINDER; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.anchor = GridBagConstraints.WEST; panel.add(new JLabel(RefactoringBundle.message("push.members.from.0.down.label", UsageViewUtil.getLongName(myClass))), gbConstraints); return panel; } protected JComponent createCenterPanel() { JPanel panel = new JPanel(new BorderLayout()); final AbstractMemberSelectionPanel<Member, MemberInfo> memberSelectionPanel = createMemberInfoPanel(); panel.add(memberSelectionPanel, BorderLayout.CENTER); myMemberInfoModel = createMemberInfoModel(); myMemberInfoModel.memberInfoChanged(new MemberInfoChange<>(myMemberInfos)); memberSelectionPanel.getTable().setMemberInfoModel(myMemberInfoModel); memberSelectionPanel.getTable().addMemberInfoChangeListener(myMemberInfoModel); myJavaDocPanel = new DocCommentPanel(RefactoringBundle.message("push.down.javadoc.panel.title")); myJavaDocPanel.setPolicy(getDocCommentPolicy()); panel.add(myJavaDocPanel, BorderLayout.EAST); return panel; } protected abstract MemberInfoModel<Member, MemberInfo> createMemberInfoModel(); protected abstract AbstractMemberSelectionPanel<Member, MemberInfo> createMemberInfoPanel(); protected abstract int getDocCommentPolicy(); protected void doAction() { if(!isOKActionEnabled()) return; savePreviewOption(isPreviewUsages()); invokeRefactoring(new PushDownProcessor<>(myClass, getSelectedMemberInfos(), new DocCommentPolicy(myJavaDocPanel.getPolicy()))); } protected abstract void savePreviewOption(boolean usages); }
apache-2.0
afilimonov/jackrabbit-oak
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/AbstractTypeDefinition.java
4181
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.nodetype; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.namepath.NamePathMapper; /** * Abstract base class for the various kinds of type definition classes * in this package. */ abstract class AbstractTypeDefinition { private static final String[] NO_STRINGS = new String[0]; protected final Tree definition; protected final NamePathMapper mapper; protected AbstractTypeDefinition(Tree definition, NamePathMapper mapper) { this.definition = checkNotNull(definition); this.mapper = checkNotNull(mapper); } /** * Returns the boolean value of the named property. * * @param name property name * @return property value, or {@code false} if the property does not exist */ protected boolean getBoolean(@Nonnull String name) { PropertyState property = definition.getProperty(checkNotNull(name)); return property != null && property.getValue(Type.BOOLEAN); } /** * Returns the string value of the named property. * * @param oakName property name * @return property value, or {@code null} if the property does not exist */ @CheckForNull protected String getString(@Nonnull String oakName) { return getValue(oakName, Type.STRING); } /** * Returns the string values of the named property. * * @param oakName property name * @return property values, or {@code null} if the property does not exist */ @CheckForNull protected String[] getStrings(@Nonnull String oakName) { return getValues(oakName, Type.STRING); } /** * Returns the name value of the named property. * * @param oakName property name * @return property value, or {@code null} if the property does not exist */ @CheckForNull protected String getName(@Nonnull String oakName) { return getValue(oakName, Type.NAME); } /** * Returns the name values of the named property. * * @param oakName property name * @return property values, or {@code null} if the property does not exist */ @CheckForNull protected String[] getNames(@Nonnull String oakName) { return getValues(oakName, Type.NAME); } private String getValue(String oakName, Type<String> type) { PropertyState property = definition.getProperty(checkNotNull(oakName)); if (property != null) { return property.getValue(type); } else { return null; } } private String[] getValues(String oakName, Type<String> type) { String[] values = null; PropertyState property = definition.getProperty(checkNotNull(oakName)); if (property != null) { int n = property.count(); if (n > 0) { values = new String[n]; for (int i = 0; i < n; i++) { values[i] = property.getValue(type, i); } } else { values = NO_STRINGS; } } return values; } }
apache-2.0
spiffxp/kubernetes
test/images/webhook/addlabel.go
1676
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "github.com/golang/glog" "k8s.io/api/admission/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const ( addFirstLabelPatch string = `[ { "op": "add", "path": "/metadata/labels", "value": {"added-label": "yes"}} ]` addAdditionalLabelPatch string = `[ { "op": "add", "path": "/metadata/labels/added-label", "value": "yes" } ]` ) // Add a label {"added-label": "yes"} to the object func addLabel(ar v1beta1.AdmissionReview) *v1beta1.AdmissionResponse { glog.V(2).Info("calling add-label") obj := struct { metav1.ObjectMeta Data map[string]string }{} raw := ar.Request.Object.Raw err := json.Unmarshal(raw, &obj) if err != nil { glog.Error(err) return toAdmissionResponse(err) } reviewResponse := v1beta1.AdmissionResponse{} reviewResponse.Allowed = true if len(obj.ObjectMeta.Labels) == 0 { reviewResponse.Patch = []byte(addFirstLabelPatch) } else { reviewResponse.Patch = []byte(addAdditionalLabelPatch) } pt := v1beta1.PatchTypeJSONPatch reviewResponse.PatchType = &pt return &reviewResponse }
apache-2.0
SeanKilleen/elasticsearch-net
src/Tests/Nest.Tests.Unit/QueryParsers/Queries/FilteredQueryTests.cs
439
using NUnit.Framework; namespace Nest.Tests.Unit.QueryParsers.Queries { [TestFixture] public class FilteredQueryTests : ParseQueryTestsBase { [Test] public void Filtered_Deserializes() { var q = this.SerializeThenDeserialize( f=>f.Filtered, f=>f.Filtered(fq=>fq .Filter(ff=>Filter1) .Query(qq=>Query1) ) ); AssertIsTermFilter(q.Filter, Filter1); AssertIsTermQuery(q.Query, Query1); } } }
apache-2.0
baifendian/sqoop
src/java/com/cloudera/sqoop/io/NamedFifo.java
1177
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.sqoop.io; import java.io.File; /** * A named FIFO channel. * * @deprecated use org.apache.sqoop.io.NamedFifo instead. * @see org.apache.sqoop.io.NamedFifo */ public class NamedFifo extends org.apache.sqoop.io.NamedFifo { public NamedFifo(String pathname) { super(pathname); } public NamedFifo(File fifo) { super(fifo); } }
apache-2.0
rabipanda/tensorflow
tensorflow/compiler/xla/packed_literal_reader.cc
3376
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/packed_literal_reader.h" #include <limits> #include <string> #include <utility> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/casts.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" namespace xla { PackedLiteralReader::PackedLiteralReader(tensorflow::RandomAccessFile* file) : file_(file), offset_(0) {} PackedLiteralReader::~PackedLiteralReader() { delete file_; } StatusOr<std::unique_ptr<Literal>> PackedLiteralReader::Read( const Shape& shape, const Layout* layout) { VLOG(3) << "reading shape from file: " << ShapeUtil::HumanString(shape) << " layout: " << (layout == nullptr ? "<none>" : layout->ShortDebugString()); Shape literal_shape = shape; if (layout != nullptr) { TF_RETURN_IF_ERROR( LayoutUtil::ValidateLayoutForShape(*layout, literal_shape)); *literal_shape.mutable_layout() = *layout; } if (shape.element_type() != F32) { return Unimplemented( "not yet implemented element type for packed literal reading: %s", PrimitiveType_Name(shape.element_type()).c_str()); } auto result = MakeUnique<Literal>(literal_shape); result->PopulateWithValue(std::numeric_limits<float>::quiet_NaN()); int64 elements = ShapeUtil::ElementsIn(shape); tensorflow::gtl::ArraySlice<float> field = result->data<float>(); char* data = tensorflow::bit_cast<char*>(field.data()); uint64 bytes = elements * sizeof(float); tensorflow::StringPiece sp; auto s = file_->Read(offset_, bytes, &sp, data); offset_ += sp.size(); if (!s.ok()) { return s; } else { // Success: make sure we move the data into the right place if the Read // call decided to return data in somewhere other than "data". CHECK_EQ(sp.size(), bytes); if (sp.data() != data) { memcpy(data, sp.data(), sp.size()); } } VLOG(3) << "read shape from file: " << ShapeUtil::HumanString(shape); return std::move(result); } bool PackedLiteralReader::IsExhausted() const { // Try to read a single byte from offset_. If we can't, we've // exhausted the data. char single_byte[1]; tensorflow::StringPiece sp; auto s = file_->Read(offset_, sizeof(single_byte), &sp, single_byte); return !s.ok(); } } // namespace xla
apache-2.0
TheTypoMaster/chromium-crosswalk
chrome/browser/chromeos/platform_keys/platform_keys.cc
531
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/platform_keys/platform_keys.h" namespace chromeos { namespace platform_keys { const char kTokenIdUser[] = "user"; const char kTokenIdSystem[] = "system"; ClientCertificateRequest::ClientCertificateRequest() { } ClientCertificateRequest::~ClientCertificateRequest() { } } // namespace platform_keys } // namespace chromeos
bsd-3-clause
sebbrudzinski/modules
commcare/src/main/java/org/motechproject/commcare/domain/CommcareModuleJson.java
1341
package org.motechproject.commcare.domain; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; /** * Represents a single CommCare module. A CommCare module is a set of forms related to one topic area. A single CommCare * application can contain multiple modules. It's part of the MOTECH model. */ public class CommcareModuleJson implements Serializable { private static final long serialVersionUID = 4408034863223848508L; @Expose @SerializedName("case_properties") private List<String> caseProperties; @Expose @SerializedName("case_type") private String caseType; @Expose @SerializedName("forms") private List<FormSchemaJson> formSchemas; public List<String> getCaseProperties() { return caseProperties; } public void setCaseProperties(List<String> caseProperties) { this.caseProperties = caseProperties; } public String getCaseType() { return caseType; } public void setCaseType(String caseType) { this.caseType = caseType; } public List<FormSchemaJson> getFormSchemas() { return formSchemas; } public void setFormSchemas(List<FormSchemaJson> formSchemas) { this.formSchemas = formSchemas; } }
bsd-3-clause
coppedis/AliRoot
PYTHIA8/pythia8210dev/src/BoseEinstein.cc
10440
// BoseEinstein.cc is a part of the PYTHIA event generator. // Copyright (C) 2015 Torbjorn Sjostrand. // PYTHIA is licenced under the GNU GPL version 2, see COPYING for details. // Please respect the MCnet Guidelines, see GUIDELINES for details. // Function definitions (not found in the header) for the BoseEinsten class. #include "Pythia8/BoseEinstein.h" namespace Pythia8 { //========================================================================== // The BoseEinstein class. //-------------------------------------------------------------------------- // Constants: could be changed here if desired, but normally should not. // These are of technical nature, as described for each. // Enumeration of id codes and table for particle species considered. const int BoseEinstein::IDHADRON[9] = { 211, -211, 111, 321, -321, 130, 310, 221, 331 }; const int BoseEinstein::ITABLE[9] = { 0, 0, 0, 1, 1, 1, 1, 2, 3 }; // Distance between table entries, normalized to min( 2*mass, QRef). const double BoseEinstein::STEPSIZE = 0.05; // Skip shift for two extremely close particles, to avoid instabilities. const double BoseEinstein::Q2MIN = 1e-8; // Parameters of energy compensation procedure: maximally allowed // relative energy error, iterative stepsize, and number of iterations. const double BoseEinstein::COMPRELERR = 1e-10; const double BoseEinstein::COMPFACMAX = 1000.; const int BoseEinstein::NCOMPSTEP = 10; //-------------------------------------------------------------------------- // Find settings. Precalculate table used to find momentum shifts. bool BoseEinstein::init(Info* infoPtrIn, Settings& settings, ParticleData& particleData) { // Save pointer. infoPtr = infoPtrIn; // Main flags. doPion = settings.flag("BoseEinstein:Pion"); doKaon = settings.flag("BoseEinstein:Kaon"); doEta = settings.flag("BoseEinstein:Eta"); // Shape of Bose-Einstein enhancement/suppression. lambda = settings.parm("BoseEinstein:lambda"); QRef = settings.parm("BoseEinstein:QRef"); // Multiples and inverses (= "radii") of distance parameters in Q-space. QRef2 = 2. * QRef; QRef3 = 3. * QRef; R2Ref = 1. / (QRef * QRef); R2Ref2 = 1. / (QRef2 * QRef2); R2Ref3 = 1. / (QRef3 * QRef3); // Masses of particles with Bose-Einstein implemented. for (int iSpecies = 0; iSpecies < 9; ++iSpecies) mHadron[iSpecies] = particleData.m0( IDHADRON[iSpecies] ); // Pair pi, K, eta and eta' masses for use in tables. mPair[0] = 2. * mHadron[0]; mPair[1] = 2. * mHadron[3]; mPair[2] = 2. * mHadron[7]; mPair[3] = 2. * mHadron[8]; // Loop over the four required tables. Local variables. double Qnow, Q2now, centerCorr; for (int iTab = 0; iTab < 4; ++iTab) { m2Pair[iTab] = mPair[iTab] * mPair[iTab]; // Step size and number of steps in normal table. deltaQ[iTab] = STEPSIZE * min(mPair[iTab], QRef); nStep[iTab] = min( 199, 1 + int(3. * QRef / deltaQ[iTab]) ); maxQ[iTab] = (nStep[iTab] - 0.1) * deltaQ[iTab]; centerCorr = deltaQ[iTab] * deltaQ[iTab] / 12.; // Construct normal table recursively in Q space. shift[iTab][0] = 0.; for (int i = 1; i <= nStep[iTab]; ++i) { Qnow = deltaQ[iTab] * (i - 0.5); Q2now = Qnow * Qnow; shift[iTab][i] = shift[iTab][i - 1] + exp(-Q2now * R2Ref) * deltaQ[iTab] * (Q2now + centerCorr) / sqrt(Q2now + m2Pair[iTab]); } // Step size and number of steps in compensation table. deltaQ3[iTab] = STEPSIZE * min(mPair[iTab], QRef3); nStep3[iTab] = min( 199, 1 + int(9. * QRef / deltaQ3[iTab]) ); maxQ3[iTab] = (nStep3[iTab] - 0.1) * deltaQ3[iTab]; centerCorr = deltaQ3[iTab] * deltaQ3[iTab] / 12.; // Construct compensation table recursively in Q space. shift3[iTab][0] = 0.; for (int i = 1; i <= nStep3[iTab]; ++i) { Qnow = deltaQ3[iTab] * (i - 0.5); Q2now = Qnow * Qnow; shift3[iTab][i] = shift3[iTab][i - 1] + exp(-Q2now * R2Ref3) * deltaQ3[iTab] * (Q2now + centerCorr) / sqrt(Q2now + m2Pair[iTab]); } } // Done. return true; } //-------------------------------------------------------------------------- // Perform Bose-Einstein corrections on an event. bool BoseEinstein::shiftEvent( Event& event) { // Reset list of identical particles. hadronBE.resize(0); // Loop over all hadron species with BE effects. nStored[0] = 0; for (int iSpecies = 0; iSpecies < 9; ++iSpecies) { nStored[iSpecies + 1] = nStored[iSpecies]; if (!doPion && iSpecies <= 2) continue; if (!doKaon && iSpecies >= 3 && iSpecies <= 6) continue; if (!doEta && iSpecies >= 7) continue; // Properties of current hadron species. int idNow = IDHADRON[ iSpecies ]; int iTab = ITABLE[ iSpecies ]; // Loop through event record to store copies of current species. for (int i = 0; i < event.size(); ++i) if ( event[i].id() == idNow && event[i].isFinal() ) hadronBE.push_back( BoseEinsteinHadron( idNow, i, event[i].p(), event[i].m() ) ); nStored[iSpecies + 1] = hadronBE.size(); // Loop through pairs of identical particles and find shifts. for (int i1 = nStored[iSpecies]; i1 < nStored[iSpecies+1] - 1; ++i1) for (int i2 = i1 + 1; i2 < nStored[iSpecies+1]; ++i2) shiftPair( i1, i2, iTab); } // Must have at least two pairs to carry out compensation. if (nStored[9] < 2) return true; // Shift momenta and recalculate energies. double eSumOriginal = 0.; double eSumShifted = 0.; double eDiffByComp = 0.; for (int i = 0; i < nStored[9]; ++i) { eSumOriginal += hadronBE[i].p.e(); hadronBE[i].p += hadronBE[i].pShift; hadronBE[i].p.e( sqrt( hadronBE[i].p.pAbs2() + hadronBE[i].m2 ) ); eSumShifted += hadronBE[i].p.e(); eDiffByComp += dot3( hadronBE[i].pComp, hadronBE[i].p) / hadronBE[i].p.e(); } // Iterate compensation shift until convergence. int iStep = 0; while ( abs(eSumShifted - eSumOriginal) > COMPRELERR * eSumOriginal && abs(eSumShifted - eSumOriginal) < COMPFACMAX * abs(eDiffByComp) && iStep < NCOMPSTEP ) { ++iStep; double compFac = (eSumOriginal - eSumShifted) / eDiffByComp; eSumShifted = 0.; eDiffByComp = 0.; for (int i = 0; i < nStored[9]; ++i) { hadronBE[i].p += compFac * hadronBE[i].pComp; hadronBE[i].p.e( sqrt( hadronBE[i].p.pAbs2() + hadronBE[i].m2 ) ); eSumShifted += hadronBE[i].p.e(); eDiffByComp += dot3( hadronBE[i].pComp, hadronBE[i].p) / hadronBE[i].p.e(); } } // Error if no convergence, and then return without doing BE shift. // However, not grave enough to kill event, so return true. if ( abs(eSumShifted - eSumOriginal) > COMPRELERR * eSumOriginal ) { infoPtr->errorMsg("Warning in BoseEinstein::shiftEvent: " "no consistent BE shift topology found, so skip BE"); return true; } // Store new particle copies with shifted momenta. for (int i = 0; i < nStored[9]; ++i) { int iNew = event.copy( hadronBE[i].iPos, 99); event[ iNew ].p( hadronBE[i].p ); } // Done. return true; } //-------------------------------------------------------------------------- // Calculate shift and (unnormalized) compensation for pair. void BoseEinstein::shiftPair( int i1, int i2, int iTab) { // Calculate old relative momentum. double Q2old = m2(hadronBE[i1].p, hadronBE[i2].p) - m2Pair[iTab]; if (Q2old < Q2MIN) return; double Qold = sqrt(Q2old); double psFac = sqrt(Q2old + m2Pair[iTab]) / Q2old; // Calculate new relative momentum for normal shift. double Qmove = 0.; if (Qold < deltaQ[iTab]) Qmove = Qold / 3.; else if (Qold < maxQ[iTab]) { double realQbin = Qold / deltaQ[iTab]; int intQbin = int( realQbin ); double inter = (pow3(realQbin) - pow3(intQbin)) / (3 * intQbin * (intQbin + 1) + 1); Qmove = ( shift[iTab][intQbin] + inter * (shift[iTab][intQbin + 1] - shift[iTab][intQbin]) ) * psFac; } else Qmove = shift[iTab][nStep[iTab]] * psFac; double Q2new = Q2old * pow( Qold / (Qold + 3. * lambda * Qmove), 2. / 3.); // Calculate corresponding three-momentum shift. double Q2Diff = Q2new - Q2old; double p2DiffAbs = (hadronBE[i1].p - hadronBE[i2].p).pAbs2(); double p2AbsDiff = hadronBE[i1].p.pAbs2() - hadronBE[i2].p.pAbs2(); double eSum = hadronBE[i1].p.e() + hadronBE[i2].p.e(); double eDiff = hadronBE[i1].p.e() - hadronBE[i2].p.e(); double sumQ2E = Q2Diff + eSum * eSum; double rootA = eSum * eDiff * p2AbsDiff - p2DiffAbs * sumQ2E; double rootB = p2DiffAbs * sumQ2E - p2AbsDiff * p2AbsDiff; double factor = 0.5 * ( rootA + sqrtpos(rootA * rootA + Q2Diff * (sumQ2E - eDiff * eDiff) * rootB) ) / rootB; // Add shifts to sum. (Energy component dummy.) Vec4 pDiff = factor * (hadronBE[i1].p - hadronBE[i2].p); hadronBE[i1].pShift += pDiff; hadronBE[i2].pShift -= pDiff; // Calculate new relative momentum for compensation shift. double Qmove3 = 0.; if (Qold < deltaQ3[iTab]) Qmove3 = Qold / 3.; else if (Qold < maxQ3[iTab]) { double realQbin = Qold / deltaQ3[iTab]; int intQbin = int( realQbin ); double inter = (pow3(realQbin) - pow3(intQbin)) / (3 * intQbin * (intQbin + 1) + 1); Qmove3 = ( shift3[iTab][intQbin] + inter * (shift3[iTab][intQbin + 1] - shift3[iTab][intQbin]) ) * psFac; } else Qmove3 = shift3[iTab][nStep3[iTab]] *psFac; double Q2new3 = Q2old * pow( Qold / (Qold + 3. * lambda * Qmove3), 2. / 3.); // Calculate corresponding three-momentum shift. Q2Diff = Q2new3 - Q2old; sumQ2E = Q2Diff + eSum * eSum; rootA = eSum * eDiff * p2AbsDiff - p2DiffAbs * sumQ2E; rootB = p2DiffAbs * sumQ2E - p2AbsDiff * p2AbsDiff; factor = 0.5 * ( rootA + sqrtpos(rootA * rootA + Q2Diff * (sumQ2E - eDiff * eDiff) * rootB) ) / rootB; // Extra dampening factor to go from BE_3 to BE_32. factor *= 1. - exp(-Q2old * R2Ref2); // Add shifts to sum. (Energy component dummy.) pDiff = factor * (hadronBE[i1].p - hadronBE[i2].p); hadronBE[i1].pComp += pDiff; hadronBE[i2].pComp -= pDiff; } //========================================================================== } // end namespace Pythia8
bsd-3-clause
Wouter0100/croogo
Install/Config/Data/MetaData.php
235
<?php class MetaData { public $table = 'meta'; public $records = array( array( 'id' => '1', 'model' => 'Node', 'foreign_key' => '1', 'key' => 'meta_keywords', 'value' => 'key1, key2', 'weight' => '' ), ); }
mit
phatpenguin/boxen-belgarion
.bundle/ruby/1.9.1/gems/puppet-3.1.0/spec/unit/module_tool/install_directory_spec.rb
2479
require 'spec_helper' require 'puppet/module_tool/install_directory' describe Puppet::ModuleTool::InstallDirectory do def expect_normal_results results = installer.run results[:installed_modules].length.should eq 1 results[:installed_modules][0][:module].should == "pmtacceptance-stdlib" results[:installed_modules][0][:version][:vstring].should == "1.0.0" results end it "(#15202) creates the install directory" do target_dir = the_directory('foo', :directory? => false, :exist? => false) target_dir.expects(:mkpath) install = Puppet::ModuleTool::InstallDirectory.new(target_dir) install.prepare('pmtacceptance-stdlib', '1.0.0') end it "(#15202) errors when the directory is not accessible" do target_dir = the_directory('foo', :directory? => false, :exist? => false) target_dir.expects(:mkpath).raises(Errno::EACCES) install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error( Puppet::ModuleTool::Errors::PermissionDeniedCreateInstallDirectoryError ) end it "(#15202) errors when an entry along the path is not a directory" do target_dir = the_directory("foo/bar", :exist? => false, :directory? => false) target_dir.expects(:mkpath).raises(Errno::EEXIST) install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error(Puppet::ModuleTool::Errors::InstallPathExistsNotDirectoryError) end it "(#15202) simply re-raises an unknown error" do target_dir = the_directory("foo/bar", :exist? => false, :directory? => false) target_dir.expects(:mkpath).raises("unknown error") install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error("unknown error") end it "(#15202) simply re-raises an unknown system call error" do target_dir = the_directory("foo/bar", :exist? => false, :directory? => false) target_dir.expects(:mkpath).raises(SystemCallError, "unknown") install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error(SystemCallError) end def the_directory(name, options) dir = mock("Pathname<#{name}>") dir.stubs(:exist?).returns(options.fetch(:exist?, true)) dir.stubs(:directory?).returns(options.fetch(:directory?, true)) dir end end
mit
zenners/angular-contacts
node_modules/firebase/node_modules/faye-websocket/node_modules/websocket-driver/node_modules/websocket-extensions/node_modules/jstest/node_modules/karma/node_modules/karma-chrome-launcher/node_modules/karma/node_modules/cucumber/lib/cucumber/ast/background.js
838
function Background(keyword, name, description, uri, line) { var Cucumber = require('../../cucumber'); var steps = Cucumber.Type.Collection(); var self = { getKeyword: function getKeyword() { return keyword; }, getName: function getName() { return name; }, getDescription: function getDescription() { return description; }, getUri: function getUri() { return uri; }, getLine: function getLine() { return line; }, addStep: function addStep(step) { var lastStep = self.getLastStep(); step.setPreviousStep(lastStep); steps.add(step); }, getLastStep: function getLastStep() { return steps.getLast(); }, getSteps: function getSteps() { return steps; } }; return self; } module.exports = Background;
mit
Codewow/GameGolem
php/moderate/hdfdfh.php
142
<?php include_once("../submitted-header.php") ?><?php include_once("../submitted-body.php") ?><?php include_once("../submitted-footer.php") ?>
mit
bianca/career-facilitation
application/third_party/PHPExcel/CachedObjectStorage/MemoryGZip.php
4323
<?php /** * PHPExcel * * Copyright (c) 2006 - 2013 PHPExcel * * 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 * * @category PHPExcel * @package PHPExcel_CachedObjectStorage * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ /** * PHPExcel_CachedObjectStorage_MemoryGZip * * @category PHPExcel * @package PHPExcel_CachedObjectStorage * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_CachedObjectStorage_MemoryGZip extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache { /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object * * @return void * @throws PHPExcel_Exception */ protected function _storeData() { if ($this->_currentCellIsDirty) { $this->_currentObject->detach(); $this->_cellCache[$this->_currentObjectID] = gzdeflate(serialize($this->_currentObject)); $this->_currentCellIsDirty = false; } $this->_currentObjectID = $this->_currentObject = null; } // function _storeData() /** * Add or Update a cell in cache identified by coordinate address * * @param string $pCoord Coordinate address of the cell to update * @param PHPExcel_Cell $cell Cell to update * @return void * @throws PHPExcel_Exception */ public function addCacheData($pCoord, PHPExcel_Cell $cell) { if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { $this->_storeData(); } $this->_currentObjectID = $pCoord; $this->_currentObject = $cell; $this->_currentCellIsDirty = true; return $cell; } // function addCacheData() /** * Get cell at a specific coordinate * * @param string $pCoord Coordinate of the cell * @throws PHPExcel_Exception * @return PHPExcel_Cell Cell that was found, or null if not found */ public function getCacheData($pCoord) { if ($pCoord === $this->_currentObjectID) { return $this->_currentObject; } $this->_storeData(); // Check if the entry that has been requested actually exists if (!isset($this->_cellCache[$pCoord])) { // Return null if requested entry doesn't exist in cache return null; } // Set current entry to the requested entry $this->_currentObjectID = $pCoord; $this->_currentObject = unserialize(gzinflate($this->_cellCache[$pCoord])); // Re-attach this as the cell's parent $this->_currentObject->attach($this); // Return requested entry return $this->_currentObject; } // function getCacheData() /** * Get a list of all cell addresses currently held in cache * * @return array of string */ public function getCellList() { if ($this->_currentObjectID !== null) { $this->_storeData(); } return parent::getCellList(); } /** * Clear the cell collection and disconnect from our parent * * @return void */ public function unsetWorksheetCells() { if(!is_null($this->_currentObject)) { $this->_currentObject->detach(); $this->_currentObject = $this->_currentObjectID = null; } $this->_cellCache = array(); // detach ourself from the worksheet, so that it can then delete this object successfully $this->_parent = null; } // function unsetWorksheetCells() }
mit
ezgatrabajo/sf_prueba1
vendor/symfony/symfony/src/Symfony/Component/Intl/Data/Bundle/Reader/JsonBundleReader.php
1686
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Intl\Data\Bundle\Reader; use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; use Symfony\Component\Intl\Exception\RuntimeException; /** * Reads .json resource bundles. * * @author Bernhard Schussek <bschussek@gmail.com> * * @internal */ class JsonBundleReader implements BundleReaderInterface { /** * {@inheritdoc} */ public function read($path, $locale) { $fileName = $path.'/'.$locale.'.json'; // prevent directory traversal attacks if (dirname($fileName) !== $path) { throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName)); } if (!file_exists($fileName)) { throw new ResourceBundleNotFoundException(sprintf( 'The resource bundle "%s" does not exist.', $fileName )); } if (!is_file($fileName)) { throw new RuntimeException(sprintf( 'The resource bundle "%s" is not a file.', $fileName )); } $data = json_decode(file_get_contents($fileName), true); if (null === $data) { throw new RuntimeException(sprintf( 'The resource bundle "%s" contains invalid JSON: %s', $fileName, json_last_error_msg() )); } return $data; } }
mit
Gurgel100/gcc
gcc/testsuite/g++.dg/debug/dwarf2/default-arg1.C
204
// PR c++/65821 // { dg-options "-gdwarf-2 -dA" } int b = 12; inline void foo(const int &x = (b+3)) { b = x; } int main() { foo(); // { dg-final { scan-assembler-not "default-arg1.C:6" } } }
gpl-2.0
gcoco/GoldenCheetah
deprecated/StravaUploadDialog.cpp
16919
/* * Copyright (c) 2011-2013 Justin F. Knotzke (jknotzke@shampoo.ca), * Damien.Grauser (damien.grauser@pev-geneve.ch) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "StravaUploadDialog.h" #include "Settings.h" #include <QHttp> #include <QUrl> #include <QScriptEngine> #include "TimeUtils.h" #include "Units.h" // acccess to metrics #include "MetricAggregator.h" #include "RideMetric.h" #include "DBAccess.h" #include "TcxRideFile.h" StravaUploadDialog::StravaUploadDialog(MainWindow *mainWindow, RideItem *item) : mainWindow(mainWindow) { STRAVA_URL1 = "http://www.strava.com/api/v1/"; STRAVA_URL2 = "http://www.strava.com/api/v2/"; STRAVA_URL_SSL = "https://www.strava.com/api/v2/"; ride = item; uploadId = ride->ride()->getTag("Strava uploadId", ""); activityId = ride->ride()->getTag("Strava actityId", ""); //setAttribute(Qt::WA_DeleteOnClose); // we allocate these on the stack setWindowTitle("Strava"); QVBoxLayout *mainLayout = new QVBoxLayout(this); QGroupBox *groupBox = new QGroupBox(tr("Choose which channels you wish to send: ")); //gpsChk = new QCheckBox(tr("GPS")); altitudeChk = new QCheckBox(tr("Altitude")); powerChk = new QCheckBox(tr("Power")); cadenceChk = new QCheckBox(tr("Cadence")); heartrateChk = new QCheckBox(tr("Heartrate")); const RideFileDataPresent *dataPresent = ride->ride()->areDataPresent(); altitudeChk->setEnabled(dataPresent->alt); altitudeChk->setChecked(dataPresent->alt); powerChk->setEnabled(dataPresent->watts); powerChk->setChecked(dataPresent->watts); cadenceChk->setEnabled(dataPresent->cad); cadenceChk->setChecked(dataPresent->cad); heartrateChk->setEnabled(dataPresent->hr); heartrateChk->setChecked(dataPresent->hr); QGridLayout *vbox = new QGridLayout(); //vbox->addWidget(gpsChk,0,0); vbox->addWidget(powerChk,0,0); vbox->addWidget(altitudeChk,0,1); vbox->addWidget(cadenceChk,1,0); vbox->addWidget(heartrateChk,1,1); groupBox->setLayout(vbox); mainLayout->addWidget(groupBox); // show progress QVBoxLayout *progressLayout = new QVBoxLayout; progressBar = new QProgressBar(this); progressLabel = new QLabel("", this); progressLayout->addWidget(progressBar); progressLayout->addWidget(progressLabel); QHBoxLayout *buttonLayout = new QHBoxLayout; uploadButton = new QPushButton(tr("&Upload Ride"), this); buttonLayout->addWidget(uploadButton); /*searchActivityButton = new QPushButton(tr("&Update info"), this); buttonLayout->addWidget(searchActivityButton); getActivityButton = new QPushButton(tr("&Load Ride"), this); buttonLayout->addWidget(getActivityButton);*/ cancelButton = new QPushButton(tr("&Cancel"), this); buttonLayout->addStretch(); buttonLayout->addWidget(cancelButton); //mainLayout->addWidget(groupBox); mainLayout->addLayout(progressLayout); mainLayout->addLayout(buttonLayout); connect(uploadButton, SIGNAL(clicked()), this, SLOT(uploadToStrava())); //connect(searchActivityButton, SIGNAL(clicked()), this, SLOT(getActivityFromStrava())); //connect(getActivityButton, SIGNAL(clicked()), this, SLOT(reject())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); //connect(workoutTimeChk, SIGNAL(stateChanged(int)), this, SLOT(onCheck(int))); //connect(timeRidingChk, SIGNAL(stateChanged(int)), this, SLOT(onCheck(int))); //connect(totalDistanceChk, SIGNAL(stateChanged(int)), this, SLOT(onCheck(int))); //uploadToStrava(); } void StravaUploadDialog::uploadToStrava() { show(); overwrite = true; if(activityId.length()>0) { overwrite = false; dialog = new QDialog(); QVBoxLayout *layout = new QVBoxLayout; QVBoxLayout *layoutLabel = new QVBoxLayout(); QLabel *label = new QLabel(); label->setText(tr("This Ride is marked as already on Strava. Are you sure you want to upload it?")); layoutLabel->addWidget(label); QPushButton *ok = new QPushButton(tr("OK"), this); QPushButton *cancel = new QPushButton(tr("Cancel"), this); QHBoxLayout *buttons = new QHBoxLayout(); buttons->addStretch(); buttons->addWidget(cancel); buttons->addWidget(ok); connect(ok, SIGNAL(clicked()), this, SLOT(okClicked())); connect(cancel, SIGNAL(clicked()), this, SLOT(cancelClicked())); layout->addLayout(layoutLabel); layout->addLayout(buttons); dialog->setLayout(layout); if (!dialog->exec()) return; } requestLogin(); if(!loggedIn) { /*QMessageBox aMsgBox; aMsgBox.setText(tr("Cannot login to Strava. Check username/password")); aMsgBox.exec();*/ reject(); } requestUpload(); if(!uploadSuccessful) { progressLabel->setText("Error uploading to Strava"); } else { //requestVerifyUpload(); progressLabel->setText(tr("Successfully uploaded to Strava\n")+uploadStatus); } uploadButton->setVisible(false); cancelButton->setText("OK"); QApplication::processEvents(); } void StravaUploadDialog::getActivityFromStrava() { if (token.length()==0) requestLogin(); if(!loggedIn) { /*QMessageBox aMsgBox; aMsgBox.setText(tr("Cannot login to Strava. Check username/password")); aMsgBox.exec();*/ reject(); } requestSearchRide(); //verifyUpload(); //QMessageBox aMsgBox; //aMsgBox.setText(tr("Successfully uploaded to Strava\n")+uploadStatus); //aMsgBox.exec(); return; } void StravaUploadDialog::okClicked() { dialog->accept(); return; } void StravaUploadDialog::cancelClicked() { dialog->reject(); return; } void StravaUploadDialog::requestLogin() { progressLabel->setText(tr("Login...")); progressBar->setValue(5); QString username = appsettings->cvalue(mainWindow->cyclist, GC_STRUSER).toString(); QString password = appsettings->cvalue(mainWindow->cyclist, GC_STRPASS).toString(); QNetworkAccessManager networkMgr; QEventLoop eventLoop; connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestLoginFinished(QNetworkReply*))); connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit())); QByteArray data; /*data += "{\"email\": \"" + username + "\","; data += "\"password\": \"" + password + "\","; data += "\"agreed_to_terms\": \"true\"}";*/ QUrl params; params.addQueryItem("email", username); params.addQueryItem("password",password); params.addQueryItem("agreed_to_terms", "true"); data = params.encodedQuery(); QUrl url = QUrl( STRAVA_URL_SSL + "/authentication/login"); QNetworkRequest request = QNetworkRequest(url); //request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded"); networkMgr.post( request, data); eventLoop.exec(); } void StravaUploadDialog::requestLoginFinished(QNetworkReply *reply) { loggedIn = false; if (reply->error() == QNetworkReply::NoError) { QString response = reply->readLine(); //qDebug() << response; if(response.contains("token")) { QScriptValue sc; QScriptEngine se; sc = se.evaluate("("+response+")"); token = sc.property("token").toString(); athleteId = sc.property("athlete").property("id").toString(); loggedIn = true; } else { token = ""; } } else { token = ""; //qDebug() << reply->error(); #ifdef Q_OS_MACX #define GC_PREF tr("Golden Cheetah->Preferences") #else #define GC_PREF tr("Tools->Options") #endif QString advise = QString(tr("Please make sure to fill the Strava login info found under\n %1.")).arg(GC_PREF); QMessageBox err(QMessageBox::Critical, tr("Strava login Error"), advise); err.exec(); } } // Documentation is at: // https://strava.pbworks.com/w/page/39241255/v2%20upload%20create void StravaUploadDialog::requestUpload() { progressLabel->setText(tr("Upload ride...")); progressBar->setValue(10); QEventLoop eventLoop; QNetworkAccessManager networkMgr; int prevSecs = 0; long diffSecs = 0; int year = ride->fileName.left(4).toInt(); int month = ride->fileName.mid(5,2).toInt(); int day = ride->fileName.mid(8,2).toInt(); int hour = ride->fileName.mid(11,2).toInt(); int minute = ride->fileName.mid(14,2).toInt();; int second = ride->fileName.mid(17,2).toInt();; QDate rideDate = QDate(year, month, day); QTime rideTime = QTime(hour, minute, second); QDateTime rideDateTime = QDateTime(rideDate, rideTime); connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestUploadFinished(QNetworkReply*))); connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit())); bool json = false; if (json) { QString out; QVector<RideFilePoint*> vectorPoints = ride->ride()->dataPoints(); int totalSize = vectorPoints.size(); int size = 0; out += "{\"token\": \"" + token + "\",\"data\":["; foreach (const RideFilePoint *point, ride->ride()->dataPoints()) { size++; if (point->secs == 0.0) continue; diffSecs = point->secs - prevSecs; prevSecs = point->secs; rideDateTime = rideDateTime.addSecs(diffSecs); out += "[\""; out += rideDateTime.toUTC().toString(Qt::ISODate); out += "\","; out += QString("%1").arg(point->lat,0,'f',GPS_COORD_TO_STRING); out += ","; out += QString("%1").arg(point->lon,0,'f',GPS_COORD_TO_STRING); if (altitudeChk->isChecked()) { out += ","; out += QString("%1").arg(point->alt); } if (powerChk->isChecked()) { out += ","; out += QString("%1").arg(point->watts); } if (altitudeChk->isChecked()) { out += ","; out += QString("%1").arg(point->cad); } if (heartrateChk->isChecked()) { out += ","; out += QString("%1").arg(point->hr); } out += "]"; if(totalSize == size) out += "],"; else out += ","; } out += "\"type\": \"json\", "; out += "\"data_fields\": \[\"time\", \"latitude\", \"longitude\""; if (altitudeChk->isChecked()) out += ", \"elevation\""; if (powerChk->isChecked()) out += ", \"watts\""; if (cadenceChk->isChecked()) out += ", \"cadence\""; if (heartrateChk->isChecked()) out += ", \"heartrate\""; out += "]}"; QUrl url = QUrl(STRAVA_URL2 + "/upload"); QNetworkRequest request = QNetworkRequest(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); progressBar->setValue(40); progressLabel->setText(tr("Upload ride... Sending")); networkMgr.post( request, out.toAscii()); } else { QByteArray data; QUrl params; TcxFileReader reader; params.addQueryItem("token", token); params.addQueryItem("type", "tcx"); params.addQueryItem("data", reader.toByteArray(mainWindow, ride->ride(), altitudeChk->isChecked(), powerChk->isChecked(), heartrateChk->isChecked(), cadenceChk->isChecked())); data = params.encodedQuery(); QUrl url = QUrl(STRAVA_URL2 + "/upload"); QNetworkRequest request = QNetworkRequest(url); request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded"); progressBar->setValue(40); progressLabel->setText(tr("Upload ride... Sending")); networkMgr.post( request, data); } //qDebug() << out; eventLoop.exec(); } void StravaUploadDialog::requestUploadFinished(QNetworkReply *reply) { progressBar->setValue(90); progressLabel->setText(tr("Upload finished.")); uploadSuccessful = false; if (reply->error() != QNetworkReply::NoError) qDebug() << "Error from upload " <<reply->error(); else { QString response = reply->readLine(); //qDebug() << response; QScriptValue sc; QScriptEngine se; sc = se.evaluate("("+response+")"); uploadId = sc.property("upload_id").toString(); ride->ride()->setTag("Strava uploadId", uploadId); ride->setDirty(true); //qDebug() << "uploadId: " << uploadId; progressBar->setValue(100); uploadSuccessful = true; } //qDebug() << reply->readAll(); } void StravaUploadDialog::requestVerifyUpload() { progressBar->setValue(0); progressLabel->setText(tr("Ride processing...")); QEventLoop eventLoop; QNetworkAccessManager networkMgr; connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestVerifyUploadFinished(QNetworkReply*))); connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit())); QByteArray out; QUrl url = QUrl(STRAVA_URL2 + "/upload/status/"+uploadId+"?token="+token); QNetworkRequest request = QNetworkRequest(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); networkMgr.post( request, out); eventLoop.exec(); } void StravaUploadDialog::requestVerifyUploadFinished(QNetworkReply *reply) { uploadSuccessful = false; if (reply->error() != QNetworkReply::NoError) qDebug() << "Error from upload " <<reply->error(); else { QString response = reply->readLine(); //qDebug() << response; QScriptValue sc; QScriptEngine se; sc = se.evaluate("("+response+")"); uploadProgress = sc.property("upload_progress").toString(); //qDebug() << "upload_progress: " << uploadProgress; progressBar->setValue(uploadProgress.toInt()); activityId = sc.property("activity_id").toString(); if (activityId.length() == 0) { requestVerifyUpload(); return; } ride->ride()->setTag("Strava actityId", activityId); ride->setDirty(true); sc = se.evaluate("("+response+")"); uploadStatus = sc.property("upload_status").toString(); //qDebug() << "upload_status: " << uploadStatus; progressLabel->setText(uploadStatus); if (uploadProgress.toInt() < 97) { requestVerifyUpload(); return; } uploadSuccessful = true; } //qDebug() << reply->readAll(); } void StravaUploadDialog::requestSearchRide() { progressBar->setValue(0); progressLabel->setText(tr("Searching corresponding Ride")); QEventLoop eventLoop; QNetworkAccessManager networkMgr; connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestSearchRideFinished(QNetworkReply*))); connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit())); QByteArray out; QUrl url = QUrl(STRAVA_URL1 + "rides?athleteId="+athleteId+"&startDate="+ride->ride()->startTime().toString("yyyy-MM-dd")+"&endDate="+ride->ride()->startTime().addDays(1).toString("yyyy-MM-dd")); QNetworkRequest request = QNetworkRequest(url); //request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); networkMgr.get(request); eventLoop.exec(); } void StravaUploadDialog::requestSearchRideFinished(QNetworkReply *reply) { uploadSuccessful = false; if (reply->error() != QNetworkReply::NoError) qDebug() << "Error from upload " <<reply->error(); else { QString response = reply->readLine(); //qDebug() << response; } //qDebug() << reply->readAll(); }
gpl-2.0
SpacePorts/Cubesat-Mission-Online-Database
vendor/respect/validation/tests/library/Respect/Validation/Rules/WritableTest.php
1516
<?php namespace Respect\Validation\Rules; $GLOBALS['is_writable'] = null; function is_writable($writable) { $return = \is_writable($writable); // Running the real function if (null !== $GLOBALS['is_writable']) { $return = $GLOBALS['is_writable']; $GLOBALS['is_writable'] = null; } return $return; } class WritableTest extends \PHPUnit_Framework_TestCase { /** * @covers Respect\Validation\Rules\Writable::validate */ public function testValidWritableFileShouldReturnTrue() { $GLOBALS['is_writable'] = true; $rule = new Writable(); $input = '/path/of/a/valid/writable/file.txt'; $this->assertTrue($rule->validate($input)); } /** * @covers Respect\Validation\Rules\Writable::validate */ public function testInvalidWritableFileShouldReturnFalse() { $GLOBALS['is_writable'] = false; $rule = new Writable(); $input = '/path/of/an/invalid/writable/file.txt'; $this->assertFalse($rule->validate($input)); } /** * @covers Respect\Validation\Rules\Writable::validate */ public function testShouldValidateObjects() { $rule = new Writable(); $object = $this->getMock('SplFileInfo', array('isWritable'), array('somefile.txt')); $object->expects($this->once()) ->method('isWritable') ->will($this->returnValue(true)); $this->assertTrue($rule->validate($object)); } }
gpl-2.0
feirie/Mycat-Server
src/main/java/io/mycat/server/config/node/CharsetConfig.java
326
package io.mycat.server.config.node; import java.util.HashMap; import java.util.Map; public class CharsetConfig { private Map<String, Object> props = new HashMap<String, Object>(); public Map<String, Object> getProps() { return props; } public void setProps(Map<String, Object> props) { this.props = props; } }
gpl-2.0
deftsoft/Joomla
administrator/components/com_newsfeeds/views/newsfeed/tmpl/edit_params.php
951
<?php /** * @version $Id: edit_params.php 20196 2011-01-09 02:40:25Z ian $ * @package Joomla.Administrator * @subpackage com_newsfeeds * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access. defined('_JEXEC') or die; $fieldSets = $this->form->getFieldsets('params'); foreach ($fieldSets as $name => $fieldSet) : echo JHtml::_('sliders.panel',JText::_($fieldSet->label), $name.'-params'); if (isset($fieldSet->description) && trim($fieldSet->description)) : echo '<p class="tip">'.$this->escape(JText::_($fieldSet->description)).'</p>'; endif; ?> <fieldset class="panelform"> <ul class="adminformlist"> <?php foreach ($this->form->getFieldset($name) as $field) : ?> <li><?php echo $field->label; ?> <?php echo $field->input; ?></li> <?php endforeach; ?> </ul> </fieldset> <?php endforeach; ?>
gpl-2.0
idskiv/wotlk
src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp
12177
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * 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/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "InstanceScript.h" #include "ahnkahet.h" /* Ahn'kahet encounters: 0 - Elder Nadox 1 - Prince Taldaram 2 - Jedoga Shadowseeker 3 - Herald Volazj 4 - Amanitar (Heroic only) */ #define MAX_ENCOUNTER 5 enum Achievements { ACHIEV_VOLUNTEER_WORK = 2056 }; class instance_ahnkahet : public InstanceMapScript { public: instance_ahnkahet() : InstanceMapScript("instance_ahnkahet", 619) { } struct instance_ahnkahet_InstanceScript : public InstanceScript { instance_ahnkahet_InstanceScript(Map* map) : InstanceScript(map) {} uint64 Elder_Nadox; uint64 Prince_Taldaram; uint64 Jedoga_Shadowseeker; uint64 Herald_Volazj; uint64 Amanitar; uint64 Prince_TaldaramSpheres[2]; uint64 Prince_TaldaramPlatform; uint64 Prince_TaldaramGate; std::set<uint64> InitiandGUIDs; uint64 JedogaSacrifices; uint64 JedogaTarget; uint32 m_auiEncounter[MAX_ENCOUNTER]; uint32 spheres[2]; uint8 InitiandCnt; uint8 switchtrigger; std::string str_data; void Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); InitiandGUIDs.clear(); Elder_Nadox =0; Prince_Taldaram =0; Jedoga_Shadowseeker =0; Herald_Volazj =0; Amanitar =0; spheres[0] = NOT_STARTED; spheres[1] = NOT_STARTED; InitiandCnt = 0; switchtrigger = 0; JedogaSacrifices = 0; JedogaTarget = 0; } bool IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (m_auiEncounter[i] == IN_PROGRESS) return true; return false; } void OnCreatureCreate(Creature* creature) { switch (creature->GetEntry()) { case 29309: Elder_Nadox = creature->GetGUID(); break; case 29308: Prince_Taldaram = creature->GetGUID(); break; case 29310: Jedoga_Shadowseeker = creature->GetGUID(); break; case 29311: Herald_Volazj = creature->GetGUID(); break; case 30258: Amanitar = creature->GetGUID(); break; case 30114: InitiandGUIDs.insert(creature->GetGUID()); break; } } void OnGameObjectCreate(GameObject* go) { switch (go->GetEntry()) { case 193564: Prince_TaldaramPlatform = go->GetGUID(); if (m_auiEncounter[1] == DONE) HandleGameObject(0, true, go); break; case 193093: Prince_TaldaramSpheres[0] = go->GetGUID(); if (spheres[0] == IN_PROGRESS) { go->SetGoState(GO_STATE_ACTIVE); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); } else go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); break; case 193094: Prince_TaldaramSpheres[1] = go->GetGUID(); if (spheres[1] == IN_PROGRESS) { go->SetGoState(GO_STATE_ACTIVE); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); } else go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); break; case 192236: Prince_TaldaramGate = go->GetGUID(); // Web gate past Prince Taldaram if (m_auiEncounter[1] == DONE) HandleGameObject(0, true, go); break; } } void SetData64(uint32 idx, uint64 guid) OVERRIDE { switch (idx) { case DATA_ADD_JEDOGA_OPFER: JedogaSacrifices = guid; break; case DATA_PL_JEDOGA_TARGET: JedogaTarget = guid; break; } } uint64 GetData64(uint32 identifier) const OVERRIDE { switch (identifier) { case DATA_ELDER_NADOX: return Elder_Nadox; case DATA_PRINCE_TALDARAM: return Prince_Taldaram; case DATA_JEDOGA_SHADOWSEEKER: return Jedoga_Shadowseeker; case DATA_HERALD_VOLAZJ: return Herald_Volazj; case DATA_AMANITAR: return Amanitar; case DATA_SPHERE1: return Prince_TaldaramSpheres[0]; case DATA_SPHERE2: return Prince_TaldaramSpheres[1]; case DATA_PRINCE_TALDARAM_PLATFORM: return Prince_TaldaramPlatform; case DATA_ADD_JEDOGA_INITIAND: { std::vector<uint64> vInitiands; vInitiands.clear(); for (std::set<uint64>::const_iterator itr = InitiandGUIDs.begin(); itr != InitiandGUIDs.end(); ++itr) { Creature* cr = instance->GetCreature(*itr); if (cr && cr->IsAlive()) vInitiands.push_back(*itr); } if (vInitiands.empty()) return 0; uint8 j = urand(0, vInitiands.size() -1); return vInitiands[j]; } case DATA_ADD_JEDOGA_OPFER: return JedogaSacrifices; case DATA_PL_JEDOGA_TARGET: return JedogaTarget; } return 0; } void SetData(uint32 type, uint32 data) OVERRIDE { switch (type) { case DATA_ELDER_NADOX_EVENT: m_auiEncounter[0] = data; break; case DATA_PRINCE_TALDARAM_EVENT: if (data == DONE) HandleGameObject(Prince_TaldaramGate, true); m_auiEncounter[1] = data; break; case DATA_JEDOGA_SHADOWSEEKER_EVENT: m_auiEncounter[2] = data; if (data == DONE) { for (std::set<uint64>::const_iterator itr = InitiandGUIDs.begin(); itr != InitiandGUIDs.end(); ++itr) { Creature* cr = instance->GetCreature(*itr); if (cr && cr->IsAlive()) { cr->SetVisible(false); cr->setDeathState(JUST_DIED); cr->RemoveCorpse(); } } } break; case DATA_HERALD_VOLAZJ_EVENT: m_auiEncounter[3] = data; break; case DATA_AMANITAR_EVENT: m_auiEncounter[4] = data; break; case DATA_SPHERE1_EVENT: spheres[0] = data; break; case DATA_SPHERE2_EVENT: spheres[1] = data; break; case DATA_JEDOGA_TRIGGER_SWITCH: switchtrigger = data; break; case DATA_JEDOGA_RESET_INITIANDS: for (std::set<uint64>::const_iterator itr = InitiandGUIDs.begin(); itr != InitiandGUIDs.end(); ++itr) { Creature* cr = instance->GetCreature(*itr); if (cr) { cr->Respawn(); if (!cr->IsInEvadeMode()) cr->AI()->EnterEvadeMode(); } } break; } if (data == DONE) SaveToDB(); } uint32 GetData(uint32 type) const OVERRIDE { switch (type) { case DATA_ELDER_NADOX_EVENT: return m_auiEncounter[0]; case DATA_PRINCE_TALDARAM_EVENT: return m_auiEncounter[1]; case DATA_JEDOGA_SHADOWSEEKER_EVENT: return m_auiEncounter[2]; case DATA_HERALD_VOLAZJ: return m_auiEncounter[3]; case DATA_AMANITAR_EVENT: return m_auiEncounter[4]; case DATA_SPHERE1_EVENT: return spheres[0]; case DATA_SPHERE2_EVENT: return spheres[1]; case DATA_ALL_INITIAND_DEAD: for (std::set<uint64>::const_iterator itr = InitiandGUIDs.begin(); itr != InitiandGUIDs.end(); ++itr) { Creature* cr = instance->GetCreature(*itr); if (!cr || (cr && cr->IsAlive())) return 0; } return 1; case DATA_JEDOGA_TRIGGER_SWITCH: return switchtrigger; } return 0; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "A K " << m_auiEncounter[0] << ' ' << m_auiEncounter[1] << ' ' << m_auiEncounter[2] << ' ' << m_auiEncounter[3] << ' ' << m_auiEncounter[4] << ' ' << spheres[0] << ' ' << spheres[1]; str_data = saveStream.str(); OUT_SAVE_INST_DATA_COMPLETE; return str_data; } void Load(const char* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); char dataHead1, dataHead2; uint16 data0, data1, data2, data3, data4, data5, data6; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2 >> data0 >> data1 >> data2 >> data3 >> data4 >> data5 >> data6; if (dataHead1 == 'A' && dataHead2 == 'K') { m_auiEncounter[0] = data0; m_auiEncounter[1] = data1; m_auiEncounter[2] = data2; m_auiEncounter[3] = data3; m_auiEncounter[4] = data4; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; spheres[0] = data5; spheres[1] = data6; } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } }; InstanceScript* GetInstanceScript(InstanceMap* map) const OVERRIDE { return new instance_ahnkahet_InstanceScript(map); } }; void AddSC_instance_ahnkahet() { new instance_ahnkahet(); }
gpl-2.0
LyndonMarques/devdollibar
htdocs/core/js/editinplace.js
11931
// Copyright (C) 2011-2014 Regis Houssin <regis.houssin@capnetworks.com> // Copyright (C) 2011 Laurent Destailleur <eldy@users.sourceforge.net> // // 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 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 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/core/js/editinplace.js // \brief File that include javascript functions for edit in place // $(document).ready(function() { var element = $('#jeditable_element').html(); var table_element = $('#jeditable_table_element').html(); var fk_element = $('#jeditable_fk_element').html(); if ($('.editval_textarea').length > 0) { $('.editval_textarea').editable(urlSaveInPlace, { type : 'textarea', rows : $('#textarea_' + $('.editval_textarea').attr('id').substr(8) + '_rows').val(), cols : $('#textarea_' + $('.editval_textarea').attr('id').substr(8) + '_cols').val(), id : 'field', tooltip : tooltipInPlace, placeholder : '&nbsp;', cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, loadurl : urlLoadInPlace, loaddata : function(result, settings) { return getParameters(this, 'textarea'); }, submitdata : function(result, settings) { return getParameters(this, 'textarea'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_textarea').hover( function () { $('#viewval_' + $(this).attr('id')).addClass("viewval_hover"); }, function () { $('#viewval_' + $(this).attr('id')).removeClass("viewval_hover"); } ); $('.editkey_textarea').click(function() { $('#viewval_' + $(this).attr('id')).click(); }); $('.viewval_textarea.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_textarea').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } if (typeof ckeditorConfig != 'undefined') { $('.editval_ckeditor').editable(urlSaveInPlace, { type : 'ckeditor', id : 'field', onblur : 'ignore', tooltip : tooltipInPlace, placeholder : '&nbsp;', cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, ckeditor : { customConfig: ckeditorConfig, toolbar: $('#ckeditor_toolbar').val(), filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl, filebrowserImageBrowseUrl : ckeditorFilebrowserImageBrowseUrl, filebrowserWindowWidth : '900', filebrowserWindowHeight : '500', filebrowserImageWindowWidth : '900', filebrowserImageWindowHeight : '500' }, submitdata : function(result, settings) { return getParameters(this, 'ckeditor'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_ckeditor').hover( function () { $('#viewval_' + $(this).attr('id')).addClass("viewval_hover"); }, function () { $('#viewval_' + $(this).attr('id')).removeClass("viewval_hover"); } ); $('.editkey_ckeditor').click(function() { $( '#viewval_' + $(this).attr('id') ).click(); }); $('.viewval_ckeditor.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_ckeditor').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } if ($('.editval_string').length > 0) { $('.editval_string').editable(urlSaveInPlace, { type : 'text', id : 'field', width : 300, tooltip : tooltipInPlace, placeholder : placeholderInPlace, cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, submitdata : function(result, settings) { return getParameters(this, 'string'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_string').hover( function () { $('#viewval_' + $(this).attr('id')).addClass("viewval_hover"); }, function () { $('#viewval_' + $(this).attr('id')).removeClass("viewval_hover"); } ); $('.editkey_string').click(function() { $( '#viewval_' + $(this).attr('id') ).click(); }); $('.viewval_string.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_string').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } if ($('.editval_numeric').length > 0) { $('.editval_numeric').editable(urlSaveInPlace, { type : 'text', id : 'field', width : 100, tooltip : tooltipInPlace, placeholder : placeholderInPlace, cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, submitdata : function(result, settings) { return getParameters(this, 'numeric'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_numeric').hover( function () { $( '#viewval_' + $(this).attr('id') ).addClass("viewval_hover"); }, function () { $( '#viewval_' + $(this).attr('id') ).removeClass("viewval_hover"); } ); $('.editkey_numeric').click(function() { $( '#viewval_' + $(this).attr('id') ).click(); }); $('.viewval_numeric.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_numeric').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } if ($('.editval_datepicker').length > 0) { $('.editval_datepicker').editable(urlSaveInPlace, { type : 'datepicker', id : 'field', onblur : 'ignore', tooltip : tooltipInPlace, placeholder : '&nbsp;', cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, submitdata : function(result, settings) { return getParameters(this, 'datepicker'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_datepicker').hover( function () { $('#viewval_' + $(this).attr('id')).addClass("viewval_hover"); }, function () { $('#viewval_' + $(this).attr('id')).removeClass("viewval_hover"); } ); $('.viewval_datepicker.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_datepicker').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } if ($('.editval_select').length > 0) { $('.editval_select').editable(urlSaveInPlace, { type : 'select', id : 'field', onblur : 'ignore', cssclass : 'flat', tooltip : tooltipInPlace, placeholder : '&nbsp;', cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, loadurl : urlLoadInPlace, loaddata : function(result, settings) { return getParameters(this, 'select'); }, submitdata : function(result, settings) { return getParameters(this, 'select'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_select').hover( function () { $('#viewval_' + $(this).attr('id')).addClass("viewval_hover"); }, function () { $('#viewval_' + $(this).attr('id')).removeClass("viewval_hover"); } ); $('.viewval_select.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_select').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } // for test only (not stable) if ($('.editval_autocomplete').length > 0) { $('.editval_autocomplete').editable(urlSaveInPlace, { type : 'autocomplete', id : 'field', width : 300, onblur : 'ignore', tooltip : tooltipInPlace, placeholder : '&nbsp;', cancel : cancelInPlace, submit : submitInPlace, indicator : indicatorInPlace, autocomplete : { source : urlLoadInPlace, data : function(result, settings) { return getParameters(this, 'select'); } }, submitdata : function(result, settings) { return getParameters(this, 'select'); }, callback : function(result, settings) { getResult(this, result); }, onreset : function(result, settings) { getDefault(settings); } }); $('.editkey_autocomplete').hover( function () { $('#viewval_' + $(this).attr('id')).addClass("viewval_hover"); }, function () { $('#viewval_' + $(this).attr('id')).removeClass("viewval_hover"); } ); $('.viewval_autocomplete.active').click(function() { $('#viewval_' + $(this).attr('id').substr(8)).hide(); $('#editval_' + $(this).attr('id').substr(8)).show().click(); }); $('.editkey_autocomplete').click(function() { $('#viewval_' + $(this).attr('id')).hide(); $('#editval_' + $(this).attr('id')).show().click(); }); } function getParameters(obj, type) { var htmlname = $(obj).attr('id').substr(8); var element = $('#element_' + htmlname).val(); var table_element = $('#table_element_' + htmlname).val(); var fk_element = $('#fk_element_' + htmlname).val(); var loadmethod = $('#loadmethod_' + htmlname).val(); var savemethod = $('#savemethod_' + htmlname).val(); var ext_element = $('#ext_element_' + htmlname).val(); var timestamp = $('#timestamp').val(); return { type: type, element: element, table_element: table_element, fk_element: fk_element, loadmethod: loadmethod, savemethod: savemethod, timestamp: timestamp, ext_element: ext_element }; } function getResult(obj, result) { var res = $.parseJSON(result); if (res.error) { $(obj).html(obj.revert); var htmlname = $(obj).attr('id').substr(8); var errormsg = $( '#errormsg_' + htmlname ).val(); if (errormsg != undefined) { $.jnotify(errormsg, "error", true); } else { $.jnotify(res.error, "error", true); } } else { var htmlname = $(obj).attr('id').substr(8); var successmsg = $( '#successmsg_' + htmlname ).val(); if (successmsg != undefined) { $.jnotify(successmsg, "ok"); } $(obj).html(res.value); $(obj).hide(); $('#viewval_' + htmlname).html(res.view); $('#viewval_' + htmlname).show(); } } function getDefault(settings) { var htmlname = $(settings).attr('id').substr(8); $('#editval_' + htmlname).hide(); $('#viewval_' + htmlname).show(); } });
gpl-3.0
unix4you2/pcoder
inc/bootstrap/js/plugins/collapse.js
5979
/* ======================================================================== * Bootstrap: collapse.js v3.3.1 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.1' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true, trigger: '[data-toggle="collapse"]' } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this }) Plugin.call($target, option) }) }(jQuery);
gpl-3.0
applifireAlgo/HR
hrproject/src/main/webapp/ext/src/selection/TreeModel.js
4637
/** * Adds custom behavior for left/right keyboard navigation for use with a tree. * Depends on the view having an expand and collapse method which accepts a * record. This selection model is created by default for {@link Ext.tree.Panel}. */ Ext.define('Ext.selection.TreeModel', { extend: 'Ext.selection.RowModel', alias: 'selection.treemodel', /** * @cfg {Boolean} pruneRemoved @hide */ constructor: function(config) { this.callParent(arguments); // If pruneRemoved is required, we must listen to the *TreeStore* to know when nodes // are added and removed if (this.pruneRemoved) { this.pruneRemoved = false; this.pruneRemovedNodes = true; } }, // binds the store to the selModel. bindStore: function(store, initial) { var me = this; me.callParent(arguments); // TreePanel should have injected a reference to the TreeStore so that we can // listen for node removal. if (me.pruneRemovedNodes) { me.view.mon(me.treeStore, { remove: me.onNodeRemove, scope: me }); } }, onNodeRemove: function(parent, node, isMove) { // deselection of deleted records done in base Model class if (!isMove) { this.deselectDeletedRecords([node]); } }, onKeyRight: function(e, t) { this.navExpand(e, t); }, navExpand: function(e, t) { var me = this, focused = me.getLastFocused(), view = me.view; if (focused) { // tree node is already expanded, go down instead // this handles both the case where we navigate to firstChild and if // there are no children to the nextSibling if (focused.isExpanded()) { me.onKeyDown(e, t); // if its not a leaf node, expand it } else if (focused.isExpandable()) { // If we are the normal side of a locking pair, only the tree view can do expanding if (!view.isTreeView) { view = view.lockingPartner; } view.expand(focused); if (focused) { me.onLastFocusChanged(null, focused); } } } }, onKeyLeft: function(e, t) { this.navCollapse(e, t); }, navCollapse: function(e, t) { var me = this, focused = me.getLastFocused(), view = me.view, parentNode; if (focused) { parentNode = focused.parentNode; // if focused node is already expanded, collapse it if (focused.isExpanded()) { // If we are the normal side of a locking pair, only the tree view can do collapsing if (!view.isTreeView) { view = view.lockingPartner; } view.collapse(focused); me.onLastFocusChanged(null, focused); // has a parentNode and its not root // TODO: this needs to cover the case where the root isVisible } else if (parentNode && !parentNode.isRoot()) { // Select a range of records when doing multiple selection. if (e.shiftKey) { me.selectRange(parentNode, focused, e.ctrlKey, 'up'); me.setLastFocused(parentNode); // just move focus, not selection } else if (e.ctrlKey) { me.setLastFocused(parentNode); // select it } else { me.select(parentNode); } } this.onLastFocusChanged(null, focused); } }, onKeySpace: function(e, t) { if (e.record.data.checked != null) { this.toggleCheck(e); } else { this.callParent(arguments); } }, onKeyEnter: function(e, t) { if (e.record.data.checked != null) { this.toggleCheck(e); } else { this.callParent(arguments); } }, toggleCheck: function(e) { var view = this.view, selected = this.getLastSelected(); e.stopEvent(); if (selected) { // If we are the normal side of a locking pair, only the tree view can do on heckChange if (!view.isTreeView) { view = view.lockingPartner; } view.onCheckChange(selected); } } });
gpl-3.0
stahta01/codeblocks-svn2git
src/templates/win32/opengl-main.cpp
4213
/************************** * Includes * **************************/ #include <windows.h> #include <gl/gl.h> /************************** * Function Declarations * **************************/ LRESULT CALLBACK WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC); void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC); /************************** * WinMain * **************************/ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { WNDCLASS wc; HWND hWnd; HDC hDC; HGLRC hRC; MSG msg; BOOL bQuit = FALSE; float theta = 0.0f; /* register window class */ wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon (NULL, IDI_APPLICATION); wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = "GLSample"; RegisterClass (&wc); /* create main window */ hWnd = CreateWindow ( "GLSample", "OpenGL Sample", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, 256, 256, NULL, NULL, hInstance, NULL); /* enable OpenGL for the window */ EnableOpenGL (hWnd, &hDC, &hRC); /* program main loop */ while (!bQuit) { /* check for messages */ if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { /* handle or dispatch messages */ if (msg.message == WM_QUIT) { bQuit = TRUE; } else { TranslateMessage (&msg); DispatchMessage (&msg); } } else { /* OpenGL animation code goes here */ glClearColor (0.0f, 0.0f, 0.0f, 0.0f); glClear (GL_COLOR_BUFFER_BIT); glPushMatrix (); glRotatef (theta, 0.0f, 0.0f, 1.0f); glBegin (GL_TRIANGLES); glColor3f (1.0f, 0.0f, 0.0f); glVertex2f (0.0f, 1.0f); glColor3f (0.0f, 1.0f, 0.0f); glVertex2f (0.87f, -0.5f); glColor3f (0.0f, 0.0f, 1.0f); glVertex2f (-0.87f, -0.5f); glEnd (); glPopMatrix (); SwapBuffers (hDC); theta += 1.0f; Sleep (1); } } /* shutdown OpenGL */ DisableOpenGL (hWnd, hDC, hRC); /* destroy the window explicitly */ DestroyWindow (hWnd); return msg.wParam; } /******************** * Window Procedure * ********************/ LRESULT CALLBACK WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: return 0; case WM_CLOSE: PostQuitMessage (0); return 0; case WM_DESTROY: return 0; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: PostQuitMessage(0); return 0; } return 0; default: return DefWindowProc (hWnd, message, wParam, lParam); } } /******************* * Enable OpenGL * *******************/ void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC) { PIXELFORMATDESCRIPTOR pfd; int iFormat; /* get the device context (DC) */ *hDC = GetDC (hWnd); /* set the pixel format for the DC */ ZeroMemory (&pfd, sizeof (pfd)); pfd.nSize = sizeof (pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; iFormat = ChoosePixelFormat (*hDC, &pfd); SetPixelFormat (*hDC, iFormat, &pfd); /* create and enable the render context (RC) */ *hRC = wglCreateContext( *hDC ); wglMakeCurrent( *hDC, *hRC ); } /****************** * Disable OpenGL * ******************/ void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC) { wglMakeCurrent (NULL, NULL); wglDeleteContext (hRC); ReleaseDC (hWnd, hDC); }
gpl-3.0
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/twisted/enterprise/row.py
4124
# -*- test-case-name: twisted.test.test_reflector -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ DEPRECATED. A (R)elational (O)bject (W)rapper. This is an extremely thin wrapper. Maintainer: Dave Peticolas """ import warnings from twisted.enterprise.util import DBError, NOQUOTE, getKeyColumn, dbTypeMap class RowObject: """ I represent a row in a table in a relational database. My class is "populated" by a Reflector object. After I am populated, instances of me are able to interact with a particular database table. You should use a class derived from this class for each database table. reflector.loadObjectsFrom() is used to create sets of instance of objects of this class from database tables. Once created, the "key column" attributes cannot be changed. Class Attributes that users must supply:: rowKeyColumns # list of key columns in form: [(columnName, typeName)] rowTableName # name of database table rowColumns # list of the columns in the table with the correct # case.this will be used to create member variables. rowFactoryMethod # method to create an instance of this class. # HACK: must be in a list!!! [factoryMethod] (optional) rowForeignKeys # keys to other tables (optional) """ populated = 0 # set on the class when the class is "populated" with SQL dirty = 0 # set on an instance when the instance is out-of-sync with the database def __init__(self): """ DEPRECATED. """ warnings.warn("twisted.enterprise.row is deprecated since Twisted 8.0", category=DeprecationWarning, stacklevel=2) def assignKeyAttr(self, attrName, value): """Assign to a key attribute. This cannot be done through normal means to protect changing keys of db objects. """ found = 0 for keyColumn, type in self.rowKeyColumns: if keyColumn == attrName: found = 1 if not found: raise DBError("%s is not a key columns." % attrName) self.__dict__[attrName] = value def findAttribute(self, attrName): """Find an attribute by caseless name. """ for attr, type in self.rowColumns: if attr.lower() == attrName.lower(): return getattr(self, attr) raise DBError("Unable to find attribute %s" % attrName) def __setattr__(self, name, value): """Special setattr to prevent changing of key values. """ # build where clause if getKeyColumn(self.__class__, name): raise DBError("cannot assign value <%s> to key column attribute <%s> of RowObject class" % (value,name)) if name in self.rowColumns: if value != self.__dict__.get(name,None) and not self.dirty: self.setDirty(1) self.__dict__[name] = value def createDefaultAttributes(self): """Populate instance with default attributes. This is used when creating a new instance NOT from the database. """ for attr in self.rowColumns: if getKeyColumn(self.__class__, attr): continue for column, ctype, typeid in self.dbColumns: if column.lower(column) == attr.lower(): q = dbTypeMap.get(ctype, None) if q == NOQUOTE: setattr(self, attr, 0) else: setattr(self, attr, "") def setDirty(self, flag): """Use this to set the 'dirty' flag. (note: this avoids infinite recursion in __setattr__, and prevents the 'dirty' flag ) """ self.__dict__["dirty"] = flag def getKeyTuple(self): keys = [] keys.append(self.rowTableName) for keyName, keyType in self.rowKeyColumns: keys.append( getattr(self, keyName) ) return tuple(keys) __all__ = ['RowObject']
gpl-3.0
Ereza/Fansubs.cat
services/libs/google-api-php-client-2.4.1/vendor/google/apiclient-services/src/Google/Service/ServiceUsage/BatchEnableServicesResponse.php
1578
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_ServiceUsage_BatchEnableServicesResponse extends Google_Collection { protected $collection_key = 'services'; protected $failuresType = 'Google_Service_ServiceUsage_EnableFailure'; protected $failuresDataType = 'array'; protected $servicesType = 'Google_Service_ServiceUsage_GoogleApiServiceusageV1Service'; protected $servicesDataType = 'array'; /** * @param Google_Service_ServiceUsage_EnableFailure */ public function setFailures($failures) { $this->failures = $failures; } /** * @return Google_Service_ServiceUsage_EnableFailure */ public function getFailures() { return $this->failures; } /** * @param Google_Service_ServiceUsage_GoogleApiServiceusageV1Service */ public function setServices($services) { $this->services = $services; } /** * @return Google_Service_ServiceUsage_GoogleApiServiceusageV1Service */ public function getServices() { return $this->services; } }
agpl-3.0
coreymbryant/libmesh
contrib/boost/include/boost/functional/hash/detail/float_functions.hpp
13584
// Copyright 2005-2009 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_FLOAT_FUNCTIONS_HPP) #define BOOST_FUNCTIONAL_HASH_DETAIL_FLOAT_FUNCTIONS_HPP #include <boost/config.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/config/no_tr1/cmath.hpp> // Set BOOST_HASH_CONFORMANT_FLOATS to 1 for libraries known to have // sufficiently good floating point support to not require any // workarounds. // // When set to 0, the library tries to automatically // use the best available implementation. This normally works well, but // breaks when ambiguities are created by odd namespacing of the functions. // // Note that if this is set to 0, the library should still take full // advantage of the platform's floating point support. #if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__LIBCOMO__) # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER) // Rogue Wave library: # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(_LIBCPP_VERSION) // libc++ # define BOOST_HASH_CONFORMANT_FLOATS 1 #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) // GNU libstdc++ 3 # if defined(__GNUC__) && __GNUC__ >= 4 # define BOOST_HASH_CONFORMANT_FLOATS 1 # else # define BOOST_HASH_CONFORMANT_FLOATS 0 # endif #elif defined(__STL_CONFIG_H) // generic SGI STL # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__MSL_CPP__) // MSL standard lib: # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__IBMCPP__) // VACPP std lib (probably conformant for much earlier version). # if __IBMCPP__ >= 1210 # define BOOST_HASH_CONFORMANT_FLOATS 1 # else # define BOOST_HASH_CONFORMANT_FLOATS 0 # endif #elif defined(MSIPL_COMPILE_H) // Modena C++ standard library # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER) // Dinkumware Library (this has to appear after any possible replacement libraries): # if _CPPLIB_VER >= 405 # define BOOST_HASH_CONFORMANT_FLOATS 1 # else # define BOOST_HASH_CONFORMANT_FLOATS 0 # endif #else # define BOOST_HASH_CONFORMANT_FLOATS 0 #endif #if BOOST_HASH_CONFORMANT_FLOATS // The standard library is known to be compliant, so don't use the // configuration mechanism. namespace boost { namespace hash_detail { template <typename Float> struct call_ldexp { typedef Float float_type; inline Float operator()(Float x, int y) const { return std::ldexp(x, y); } }; template <typename Float> struct call_frexp { typedef Float float_type; inline Float operator()(Float x, int* y) const { return std::frexp(x, y); } }; template <typename Float> struct select_hash_type { typedef Float type; }; } } #else // BOOST_HASH_CONFORMANT_FLOATS == 0 // The C++ standard requires that the C float functions are overloarded // for float, double and long double in the std namespace, but some of the older // library implementations don't support this. On some that don't, the C99 // float functions (frexpf, frexpl, etc.) are available. // // The following tries to automatically detect which are available. namespace boost { namespace hash_detail { // Returned by dummy versions of the float functions. struct not_found { // Implicitly convertible to float and long double in order to avoid // a compile error when the dummy float functions are used. inline operator float() const { return 0; } inline operator long double() const { return 0; } }; // A type for detecting the return type of functions. template <typename T> struct is; template <> struct is<float> { char x[10]; }; template <> struct is<double> { char x[20]; }; template <> struct is<long double> { char x[30]; }; template <> struct is<boost::hash_detail::not_found> { char x[40]; }; // Used to convert the return type of a function to a type for sizeof. template <typename T> is<T> float_type(T); // call_ldexp // // This will get specialized for float and long double template <typename Float> struct call_ldexp { typedef double float_type; inline double operator()(double a, int b) const { using namespace std; return ldexp(a, b); } }; // call_frexp // // This will get specialized for float and long double template <typename Float> struct call_frexp { typedef double float_type; inline double operator()(double a, int* b) const { using namespace std; return frexp(a, b); } }; } } // A namespace for dummy functions to detect when the actual function we want // isn't available. ldexpl, ldexpf etc. might be added tby the macros below. // // AFAICT these have to be outside of the boost namespace, as if they're in // the boost namespace they'll always be preferable to any other function // (since the arguments are built in types, ADL can't be used). namespace boost_hash_detect_float_functions { template <class Float> boost::hash_detail::not_found ldexp(Float, int); template <class Float> boost::hash_detail::not_found frexp(Float, int*); } // Macros for generating specializations of call_ldexp and call_frexp. // // check_cpp and check_c99 check if the C++ or C99 functions are available. // // Then the call_* functions select an appropriate implementation. // // I used c99_func in a few places just to get a unique name. // // Important: when using 'using namespace' at namespace level, include as // little as possible in that namespace, as Visual C++ has an odd bug which // can cause the namespace to be imported at the global level. This seems to // happen mainly when there's a template in the same namesapce. #define BOOST_HASH_CALL_FLOAT_FUNC(cpp_func, c99_func, type1, type2) \ namespace boost_hash_detect_float_functions { \ template <class Float> \ boost::hash_detail::not_found c99_func(Float, type2); \ } \ \ namespace boost { \ namespace hash_detail { \ namespace c99_func##_detect { \ using namespace std; \ using namespace boost_hash_detect_float_functions; \ \ struct check { \ static type1 x; \ static type2 y; \ BOOST_STATIC_CONSTANT(bool, cpp = \ sizeof(float_type(cpp_func(x,y))) \ == sizeof(is<type1>)); \ BOOST_STATIC_CONSTANT(bool, c99 = \ sizeof(float_type(c99_func(x,y))) \ == sizeof(is<type1>)); \ }; \ } \ \ template <bool x> \ struct call_c99_##c99_func : \ boost::hash_detail::call_##cpp_func<double> {}; \ \ template <> \ struct call_c99_##c99_func<true> { \ typedef type1 float_type; \ \ template <typename T> \ inline type1 operator()(type1 a, T b) const \ { \ using namespace std; \ return c99_func(a, b); \ } \ }; \ \ template <bool x> \ struct call_cpp_##c99_func : \ call_c99_##c99_func< \ ::boost::hash_detail::c99_func##_detect::check::c99 \ > {}; \ \ template <> \ struct call_cpp_##c99_func<true> { \ typedef type1 float_type; \ \ template <typename T> \ inline type1 operator()(type1 a, T b) const \ { \ using namespace std; \ return cpp_func(a, b); \ } \ }; \ \ template <> \ struct call_##cpp_func<type1> : \ call_cpp_##c99_func< \ ::boost::hash_detail::c99_func##_detect::check::cpp \ > {}; \ } \ } #define BOOST_HASH_CALL_FLOAT_MACRO(cpp_func, c99_func, type1, type2) \ namespace boost { \ namespace hash_detail { \ \ template <> \ struct call_##cpp_func<type1> { \ typedef type1 float_type; \ inline type1 operator()(type1 x, type2 y) const { \ return c99_func(x, y); \ } \ }; \ } \ } #if defined(ldexpf) BOOST_HASH_CALL_FLOAT_MACRO(ldexp, ldexpf, float, int) #else BOOST_HASH_CALL_FLOAT_FUNC(ldexp, ldexpf, float, int) #endif #if defined(ldexpl) BOOST_HASH_CALL_FLOAT_MACRO(ldexp, ldexpl, long double, int) #else BOOST_HASH_CALL_FLOAT_FUNC(ldexp, ldexpl, long double, int) #endif #if defined(frexpf) BOOST_HASH_CALL_FLOAT_MACRO(frexp, frexpf, float, int*) #else BOOST_HASH_CALL_FLOAT_FUNC(frexp, frexpf, float, int*) #endif #if defined(frexpl) BOOST_HASH_CALL_FLOAT_MACRO(frexp, frexpl, long double, int*) #else BOOST_HASH_CALL_FLOAT_FUNC(frexp, frexpl, long double, int*) #endif #undef BOOST_HASH_CALL_FLOAT_MACRO #undef BOOST_HASH_CALL_FLOAT_FUNC namespace boost { namespace hash_detail { template <typename Float1, typename Float2> struct select_hash_type_impl { typedef double type; }; template <> struct select_hash_type_impl<float, float> { typedef float type; }; template <> struct select_hash_type_impl<long double, long double> { typedef long double type; }; // select_hash_type // // If there is support for a particular floating point type, use that // otherwise use double (there's always support for double). template <typename Float> struct select_hash_type : select_hash_type_impl< BOOST_DEDUCED_TYPENAME call_ldexp<Float>::float_type, BOOST_DEDUCED_TYPENAME call_frexp<Float>::float_type > {}; } } #endif // BOOST_HASH_CONFORMANT_FLOATS #endif
lgpl-2.1
jmluy/elasticsearch
server/src/main/java/org/elasticsearch/indices/recovery/plan/SourceOnlyRecoveryPlannerService.java
1916
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.indices.recovery.plan; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.core.Nullable; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.store.Store; import org.elasticsearch.index.store.StoreFileMetadata; import java.util.List; import static org.elasticsearch.common.util.CollectionUtils.concatLists; public class SourceOnlyRecoveryPlannerService implements RecoveryPlannerService { public static final RecoveryPlannerService INSTANCE = new SourceOnlyRecoveryPlannerService(); @Override public void computeRecoveryPlan( ShardId shardId, @Nullable String shardStateIdentifier, Store.MetadataSnapshot sourceMetadata, Store.MetadataSnapshot targetMetadata, long startingSeqNo, int translogOps, Version targetVersion, boolean useSnapshots, ActionListener<ShardRecoveryPlan> listener ) { ActionListener.completeWith(listener, () -> { Store.RecoveryDiff recoveryDiff = sourceMetadata.recoveryDiff(targetMetadata); List<StoreFileMetadata> filesMissingInTarget = concatLists(recoveryDiff.missing, recoveryDiff.different); return new ShardRecoveryPlan( ShardRecoveryPlan.SnapshotFilesToRecover.EMPTY, filesMissingInTarget, recoveryDiff.identical, startingSeqNo, translogOps, sourceMetadata ); }); } }
apache-2.0
jmluy/elasticsearch
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LowerCaseTokenFilterFactory.java
2246
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.analysis.common; import org.apache.lucene.analysis.LowerCaseFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.el.GreekLowerCaseFilter; import org.apache.lucene.analysis.ga.IrishLowerCaseFilter; import org.apache.lucene.analysis.tr.TurkishLowerCaseFilter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.AbstractTokenFilterFactory; import org.elasticsearch.index.analysis.NormalizingTokenFilterFactory; /** * Factory for {@link LowerCaseFilter} and some language-specific variants * supported by the {@code language} parameter: * <ul> * <li>greek: {@link GreekLowerCaseFilter} * <li>irish: {@link IrishLowerCaseFilter} * <li>turkish: {@link TurkishLowerCaseFilter} * </ul> */ public class LowerCaseTokenFilterFactory extends AbstractTokenFilterFactory implements NormalizingTokenFilterFactory { private final String lang; LowerCaseTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) { super(indexSettings, name, settings); this.lang = settings.get("language", null); } @Override public TokenStream create(TokenStream tokenStream) { if (lang == null) { return new LowerCaseFilter(tokenStream); } else if (lang.equalsIgnoreCase("greek")) { return new GreekLowerCaseFilter(tokenStream); } else if (lang.equalsIgnoreCase("irish")) { return new IrishLowerCaseFilter(tokenStream); } else if (lang.equalsIgnoreCase("turkish")) { return new TurkishLowerCaseFilter(tokenStream); } else { throw new IllegalArgumentException("language [" + lang + "] not support for lower case"); } } }
apache-2.0
jmluy/elasticsearch
build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/RemoveWarningsTests.java
3917
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.gradle.internal.test.rest.transform.warnings; import com.fasterxml.jackson.databind.node.ObjectNode; import org.elasticsearch.gradle.internal.test.rest.transform.RestTestTransform; import org.elasticsearch.gradle.internal.test.rest.transform.TransformTests; import org.junit.Test; import java.util.Collections; import java.util.List; import java.util.Set; public class RemoveWarningsTests extends TransformTests { private static final String WARNINGS = "warnings"; /** * test file does not any warnings defined */ @Test public void testRemoveWarningsNoPreExisting() throws Exception { String testName = "/rest/transform/warnings/without_existing_warnings.yml"; List<ObjectNode> tests = getTests(testName); validateSetupDoesNotExist(tests); List<ObjectNode> transformedTests = transformTests(tests); printTest(testName, transformedTests); validateSetupDoesNotExist(transformedTests); validateBodyHasNoWarnings(WARNINGS, transformedTests); } /** * test file has preexisting multiple warnings */ @Test public void testRemoveWarningWithPreExisting() throws Exception { String testName = "/rest/transform/warnings/with_existing_warnings.yml"; List<ObjectNode> tests = getTests(testName); validateSetupExist(tests); validateBodyHasWarnings(WARNINGS, tests, Set.of("a", "b")); List<ObjectNode> transformedTests = transformTests(tests); printTest(testName, transformedTests); validateSetupAndTearDown(transformedTests); validateBodyHasWarnings(WARNINGS, tests, Set.of("b")); } @Test public void testRemoveWarningWithPreExistingFromSingleTest() throws Exception { String testName = "/rest/transform/warnings/with_existing_warnings.yml"; List<ObjectNode> tests = getTests(testName); validateSetupExist(tests); validateBodyHasWarnings(WARNINGS, tests, Set.of("a", "b")); List<ObjectNode> transformedTests = transformTests(tests, getTransformationsForTest("Test warnings")); printTest(testName, transformedTests); validateSetupAndTearDown(transformedTests); validateBodyHasWarnings(WARNINGS, "Test warnings", tests, Set.of("b")); validateBodyHasWarnings(WARNINGS, "Not the test to change", tests, Set.of("a", "b")); } private List<RestTestTransform<?>> getTransformationsForTest(String testName) { return Collections.singletonList(new RemoveWarnings(Set.of("a"), testName)); } /** * test file has preexisting single warning */ @Test public void testRemoveWarningWithSinglePreExisting() throws Exception { // For simplicity, when removing the last item, it does not remove the headers/teardown and leaves an empty array String testName = "/rest/transform/warnings/with_existing_single_warnings.yml"; List<ObjectNode> tests = getTests(testName); validateSetupExist(tests); validateBodyHasWarnings(WARNINGS, tests, Set.of("a")); List<ObjectNode> transformedTests = transformTests(tests); printTest(testName, transformedTests); validateSetupAndTearDown(transformedTests); validateBodyHasEmptyNoWarnings(WARNINGS, tests); } @Override protected List<RestTestTransform<?>> getTransformations() { return Collections.singletonList(new RemoveWarnings(Set.of("a"))); } @Override protected boolean getHumanDebug() { return false; } }
apache-2.0
google/llvm-propeller
compiler-rt/test/hwasan/TestCases/new-test.cpp
404
// Test basic new functionality. // RUN: %clangxx_hwasan %s -o %t // RUN: %run %t #include <stdlib.h> #include <assert.h> #include <sanitizer/hwasan_interface.h> #include <sanitizer/allocator_interface.h> int main() { __hwasan_enable_allocator_tagging(); size_t volatile n = 0; char *a1 = new char[n]; assert(a1 != nullptr); assert(__sanitizer_get_allocated_size(a1) == 0); delete[] a1; }
apache-2.0
knative-sandbox/eventing-awssqs
vendor/github.com/cncf/xds/go/udpa/annotations/versioning.pb.validate.go
2301
// Code generated by protoc-gen-validate. DO NOT EDIT. // source: udpa/annotations/versioning.proto package annotations import ( "bytes" "errors" "fmt" "net" "net/mail" "net/url" "regexp" "strings" "time" "unicode/utf8" "google.golang.org/protobuf/types/known/anypb" ) // ensure the imports are used var ( _ = bytes.MinRead _ = errors.New("") _ = fmt.Print _ = utf8.UTFMax _ = (*regexp.Regexp)(nil) _ = (*strings.Reader)(nil) _ = net.IPv4len _ = time.Duration(0) _ = (*url.URL)(nil) _ = (*mail.Address)(nil) _ = anypb.Any{} ) // Validate checks the field values on VersioningAnnotation with the rules // defined in the proto definition for this message. If any rules are // violated, an error is returned. func (m *VersioningAnnotation) Validate() error { if m == nil { return nil } // no validation rules for PreviousMessageType return nil } // VersioningAnnotationValidationError is the validation error returned by // VersioningAnnotation.Validate if the designated constraints aren't met. type VersioningAnnotationValidationError struct { field string reason string cause error key bool } // Field function returns field value. func (e VersioningAnnotationValidationError) Field() string { return e.field } // Reason function returns reason value. func (e VersioningAnnotationValidationError) Reason() string { return e.reason } // Cause function returns cause value. func (e VersioningAnnotationValidationError) Cause() error { return e.cause } // Key function returns key value. func (e VersioningAnnotationValidationError) Key() bool { return e.key } // ErrorName returns error name. func (e VersioningAnnotationValidationError) ErrorName() string { return "VersioningAnnotationValidationError" } // Error satisfies the builtin error interface func (e VersioningAnnotationValidationError) Error() string { cause := "" if e.cause != nil { cause = fmt.Sprintf(" | caused by: %v", e.cause) } key := "" if e.key { key = "key for " } return fmt.Sprintf( "invalid %sVersioningAnnotation.%s: %s%s", key, e.field, e.reason, cause) } var _ error = VersioningAnnotationValidationError{} var _ interface { Field() string Reason() string Key() bool Cause() error ErrorName() string } = VersioningAnnotationValidationError{}
apache-2.0
RiverWeng/jstorm
jstorm-core/src/main/java/backtype/storm/generated/GlobalStreamId.java
15316
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package backtype.storm.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2015-7-27") public class GlobalStreamId implements org.apache.thrift.TBase<GlobalStreamId, GlobalStreamId._Fields>, java.io.Serializable, Cloneable, Comparable<GlobalStreamId> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GlobalStreamId"); private static final org.apache.thrift.protocol.TField COMPONENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("componentId", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField STREAM_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("streamId", org.apache.thrift.protocol.TType.STRING, (short)2); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new GlobalStreamIdStandardSchemeFactory()); schemes.put(TupleScheme.class, new GlobalStreamIdTupleSchemeFactory()); } private String componentId; // required private String streamId; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { COMPONENT_ID((short)1, "componentId"), STREAM_ID((short)2, "streamId"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // COMPONENT_ID return COMPONENT_ID; case 2: // STREAM_ID return STREAM_ID; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.COMPONENT_ID, new org.apache.thrift.meta_data.FieldMetaData("componentId", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.STREAM_ID, new org.apache.thrift.meta_data.FieldMetaData("streamId", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GlobalStreamId.class, metaDataMap); } public GlobalStreamId() { } public GlobalStreamId( String componentId, String streamId) { this(); this.componentId = componentId; this.streamId = streamId; } /** * Performs a deep copy on <i>other</i>. */ public GlobalStreamId(GlobalStreamId other) { if (other.is_set_componentId()) { this.componentId = other.componentId; } if (other.is_set_streamId()) { this.streamId = other.streamId; } } public GlobalStreamId deepCopy() { return new GlobalStreamId(this); } @Override public void clear() { this.componentId = null; this.streamId = null; } public String get_componentId() { return this.componentId; } public void set_componentId(String componentId) { this.componentId = componentId; } public void unset_componentId() { this.componentId = null; } /** Returns true if field componentId is set (has been assigned a value) and false otherwise */ public boolean is_set_componentId() { return this.componentId != null; } public void set_componentId_isSet(boolean value) { if (!value) { this.componentId = null; } } public String get_streamId() { return this.streamId; } public void set_streamId(String streamId) { this.streamId = streamId; } public void unset_streamId() { this.streamId = null; } /** Returns true if field streamId is set (has been assigned a value) and false otherwise */ public boolean is_set_streamId() { return this.streamId != null; } public void set_streamId_isSet(boolean value) { if (!value) { this.streamId = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case COMPONENT_ID: if (value == null) { unset_componentId(); } else { set_componentId((String)value); } break; case STREAM_ID: if (value == null) { unset_streamId(); } else { set_streamId((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case COMPONENT_ID: return get_componentId(); case STREAM_ID: return get_streamId(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case COMPONENT_ID: return is_set_componentId(); case STREAM_ID: return is_set_streamId(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof GlobalStreamId) return this.equals((GlobalStreamId)that); return false; } public boolean equals(GlobalStreamId that) { if (that == null) return false; boolean this_present_componentId = true && this.is_set_componentId(); boolean that_present_componentId = true && that.is_set_componentId(); if (this_present_componentId || that_present_componentId) { if (!(this_present_componentId && that_present_componentId)) return false; if (!this.componentId.equals(that.componentId)) return false; } boolean this_present_streamId = true && this.is_set_streamId(); boolean that_present_streamId = true && that.is_set_streamId(); if (this_present_streamId || that_present_streamId) { if (!(this_present_streamId && that_present_streamId)) return false; if (!this.streamId.equals(that.streamId)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_componentId = true && (is_set_componentId()); list.add(present_componentId); if (present_componentId) list.add(componentId); boolean present_streamId = true && (is_set_streamId()); list.add(present_streamId); if (present_streamId) list.add(streamId); return list.hashCode(); } @Override public int compareTo(GlobalStreamId other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(is_set_componentId()).compareTo(other.is_set_componentId()); if (lastComparison != 0) { return lastComparison; } if (is_set_componentId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.componentId, other.componentId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(is_set_streamId()).compareTo(other.is_set_streamId()); if (lastComparison != 0) { return lastComparison; } if (is_set_streamId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.streamId, other.streamId); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("GlobalStreamId("); boolean first = true; sb.append("componentId:"); if (this.componentId == null) { sb.append("null"); } else { sb.append(this.componentId); } first = false; if (!first) sb.append(", "); sb.append("streamId:"); if (this.streamId == null) { sb.append("null"); } else { sb.append(this.streamId); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (!is_set_componentId()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'componentId' is unset! Struct:" + toString()); } if (!is_set_streamId()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'streamId' is unset! Struct:" + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class GlobalStreamIdStandardSchemeFactory implements SchemeFactory { public GlobalStreamIdStandardScheme getScheme() { return new GlobalStreamIdStandardScheme(); } } private static class GlobalStreamIdStandardScheme extends StandardScheme<GlobalStreamId> { public void read(org.apache.thrift.protocol.TProtocol iprot, GlobalStreamId struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // COMPONENT_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.componentId = iprot.readString(); struct.set_componentId_isSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // STREAM_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.streamId = iprot.readString(); struct.set_streamId_isSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, GlobalStreamId struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.componentId != null) { oprot.writeFieldBegin(COMPONENT_ID_FIELD_DESC); oprot.writeString(struct.componentId); oprot.writeFieldEnd(); } if (struct.streamId != null) { oprot.writeFieldBegin(STREAM_ID_FIELD_DESC); oprot.writeString(struct.streamId); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class GlobalStreamIdTupleSchemeFactory implements SchemeFactory { public GlobalStreamIdTupleScheme getScheme() { return new GlobalStreamIdTupleScheme(); } } private static class GlobalStreamIdTupleScheme extends TupleScheme<GlobalStreamId> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, GlobalStreamId struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; oprot.writeString(struct.componentId); oprot.writeString(struct.streamId); } @Override public void read(org.apache.thrift.protocol.TProtocol prot, GlobalStreamId struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; struct.componentId = iprot.readString(); struct.set_componentId_isSet(true); struct.streamId = iprot.readString(); struct.set_streamId_isSet(true); } } }
apache-2.0
dinfuehr/rust
src/test/run-pass/issue-15774.rs
802
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings)] #![allow(unused_imports)] enum Foo { A } mod bar { pub fn normal(x: ::Foo) { use Foo::A; match x { A => {} } } pub fn wrong(x: ::Foo) { match x { ::Foo::A => {} } } } pub fn main() { bar::normal(Foo::A); bar::wrong(Foo::A); }
apache-2.0
kawamuray/docker
vendor/src/github.com/docker/libcontainer/cgroups/fs/apply_raw.go
4953
package fs import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "github.com/docker/libcontainer/cgroups" ) var ( subsystems = map[string]subsystem{ "devices": &DevicesGroup{}, "memory": &MemoryGroup{}, "cpu": &CpuGroup{}, "cpuset": &CpusetGroup{}, "cpuacct": &CpuacctGroup{}, "blkio": &BlkioGroup{}, "perf_event": &PerfEventGroup{}, "freezer": &FreezerGroup{}, } CgroupProcesses = "cgroup.procs" ) // The absolute path to the root of the cgroup hierarchies. var cgroupRoot string // TODO(vmarmol): Report error here, we'll probably need to wait for the new API. func init() { // we can pick any subsystem to find the root cpuRoot, err := cgroups.FindCgroupMountpoint("cpu") if err != nil { return } cgroupRoot = filepath.Dir(cpuRoot) if _, err := os.Stat(cgroupRoot); err != nil { return } } type subsystem interface { // Returns the stats, as 'stats', corresponding to the cgroup under 'path'. GetStats(path string, stats *cgroups.Stats) error // Removes the cgroup represented by 'data'. Remove(*data) error // Creates and joins the cgroup represented by data. Set(*data) error } type data struct { root string cgroup string c *cgroups.Cgroup pid int } func Apply(c *cgroups.Cgroup, pid int) (map[string]string, error) { d, err := getCgroupData(c, pid) if err != nil { return nil, err } paths := make(map[string]string) defer func() { if err != nil { cgroups.RemovePaths(paths) } }() for name, sys := range subsystems { if err := sys.Set(d); err != nil { return nil, err } // FIXME: Apply should, ideally, be reentrant or be broken up into a separate // create and join phase so that the cgroup hierarchy for a container can be // created then join consists of writing the process pids to cgroup.procs p, err := d.path(name) if err != nil { if cgroups.IsNotFound(err) { continue } return nil, err } paths[name] = p } return paths, nil } // Symmetrical public function to update device based cgroups. Also available // in the systemd implementation. func ApplyDevices(c *cgroups.Cgroup, pid int) error { d, err := getCgroupData(c, pid) if err != nil { return err } devices := subsystems["devices"] return devices.Set(d) } func GetStats(systemPaths map[string]string) (*cgroups.Stats, error) { stats := cgroups.NewStats() for name, path := range systemPaths { sys, ok := subsystems[name] if !ok || !cgroups.PathExists(path) { continue } if err := sys.GetStats(path, stats); err != nil { return nil, err } } return stats, nil } // Freeze toggles the container's freezer cgroup depending on the state // provided func Freeze(c *cgroups.Cgroup, state cgroups.FreezerState) error { d, err := getCgroupData(c, 0) if err != nil { return err } c.Freezer = state freezer := subsystems["freezer"] return freezer.Set(d) } func GetPids(c *cgroups.Cgroup) ([]int, error) { d, err := getCgroupData(c, 0) if err != nil { return nil, err } dir, err := d.path("devices") if err != nil { return nil, err } return cgroups.ReadProcsFile(dir) } func getCgroupData(c *cgroups.Cgroup, pid int) (*data, error) { if cgroupRoot == "" { return nil, fmt.Errorf("failed to find the cgroup root") } cgroup := c.Name if c.Parent != "" { cgroup = filepath.Join(c.Parent, cgroup) } return &data{ root: cgroupRoot, cgroup: cgroup, c: c, pid: pid, }, nil } func (raw *data) parent(subsystem string) (string, error) { initPath, err := cgroups.GetInitCgroupDir(subsystem) if err != nil { return "", err } return filepath.Join(raw.root, subsystem, initPath), nil } func (raw *data) path(subsystem string) (string, error) { // If the cgroup name/path is absolute do not look relative to the cgroup of the init process. if filepath.IsAbs(raw.cgroup) { path := filepath.Join(raw.root, subsystem, raw.cgroup) if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { return "", cgroups.NewNotFoundError(subsystem) } return "", err } return path, nil } parent, err := raw.parent(subsystem) if err != nil { return "", err } return filepath.Join(parent, raw.cgroup), nil } func (raw *data) join(subsystem string) (string, error) { path, err := raw.path(subsystem) if err != nil { return "", err } if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) { return "", err } if err := writeFile(path, CgroupProcesses, strconv.Itoa(raw.pid)); err != nil { return "", err } return path, nil } func writeFile(dir, file, data string) error { return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) } func readFile(dir, file string) (string, error) { data, err := ioutil.ReadFile(filepath.Join(dir, file)) return string(data), err } func removePath(p string, err error) error { if err != nil { return err } if p != "" { return os.RemoveAll(p) } return nil }
apache-2.0
codrut3/tensorflow
tensorflow/contrib/lite/testing/split_test.cc
1940
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/contrib/lite/testing/split.h" #include <gmock/gmock.h> #include <gtest/gtest.h> namespace tflite { namespace testing { namespace { using ::testing::ElementsAre; using ::testing::Pair; TEST(SplitTest, SplitToPos) { EXPECT_THAT(SplitToPos("test;:1-2-3 ;: test", ";:"), ElementsAre(Pair(0, 4), Pair(6, 12), Pair(14, 19))); EXPECT_THAT(SplitToPos("test;:1-2-3 ;: test", ":"), ElementsAre(Pair(0, 5), Pair(6, 13), Pair(14, 19))); EXPECT_THAT(SplitToPos("test", ":"), ElementsAre(Pair(0, 4))); EXPECT_THAT(SplitToPos("test ", ":"), ElementsAre(Pair(0, 5))); EXPECT_THAT(SplitToPos("", ":"), ElementsAre()); EXPECT_THAT(SplitToPos("test ", ""), ElementsAre(Pair(0, 5))); EXPECT_THAT(SplitToPos("::::", ":"), ElementsAre()); } TEST(SplitTest, SplitString) { EXPECT_THAT(Split<string>("A;B;C", ";"), ElementsAre("A", "B", "C")); } TEST(SplitTest, SplitFloat) { EXPECT_THAT(Split<float>("1.0 B 1e-5", " "), ElementsAre(1.0, 0.0, 1e-5)); } TEST(SplitTest, SplitInt) { EXPECT_THAT(Split<int>("1,-1,258", ","), ElementsAre(1, -1, 258)); } TEST(SplitTest, SplitUint8) { EXPECT_THAT(Split<uint8_t>("1,-1,258", ","), ElementsAre(1, 255, 2)); } } // namespace } // namespace testing } // namespace tflite
apache-2.0
feelobot/kubernetes
pkg/volume/aws_ebs/aws_ebs.go
11510
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package aws_ebs import ( "fmt" "os" "path" "path/filepath" "strconv" "strings" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider" "github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider/aws" "github.com/GoogleCloudPlatform/kubernetes/pkg/types" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" "github.com/GoogleCloudPlatform/kubernetes/pkg/util/exec" "github.com/GoogleCloudPlatform/kubernetes/pkg/util/mount" "github.com/GoogleCloudPlatform/kubernetes/pkg/volume" "github.com/golang/glog" ) // This is the primary entrypoint for volume plugins. func ProbeVolumePlugins() []volume.VolumePlugin { return []volume.VolumePlugin{&awsElasticBlockStorePlugin{nil}} } type awsElasticBlockStorePlugin struct { host volume.VolumeHost } var _ volume.VolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.PersistentVolumePlugin = &awsElasticBlockStorePlugin{} const ( awsElasticBlockStorePluginName = "kubernetes.io/aws-ebs" ) func (plugin *awsElasticBlockStorePlugin) Init(host volume.VolumeHost) { plugin.host = host } func (plugin *awsElasticBlockStorePlugin) Name() string { return awsElasticBlockStorePluginName } func (plugin *awsElasticBlockStorePlugin) CanSupport(spec *volume.Spec) bool { return spec.PersistentVolumeSource.AWSElasticBlockStore != nil || spec.VolumeSource.AWSElasticBlockStore != nil } func (plugin *awsElasticBlockStorePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { return []api.PersistentVolumeAccessMode{ api.ReadWriteOnce, } } func (plugin *awsElasticBlockStorePlugin) NewBuilder(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions, mounter mount.Interface) (volume.Builder, error) { // Inject real implementations here, test through the internal function. return plugin.newBuilderInternal(spec, pod.UID, &AWSDiskUtil{}, mounter) } func (plugin *awsElasticBlockStorePlugin) newBuilderInternal(spec *volume.Spec, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.Builder, error) { // EBSs used directly in a pod have a ReadOnly flag set by the pod author. // EBSs used as a PersistentVolume gets the ReadOnly flag indirectly through the persistent-claim volume used to mount the PV var readOnly bool var ebs *api.AWSElasticBlockStoreVolumeSource if spec.VolumeSource.AWSElasticBlockStore != nil { ebs = spec.VolumeSource.AWSElasticBlockStore readOnly = ebs.ReadOnly } else { ebs = spec.PersistentVolumeSource.AWSElasticBlockStore readOnly = spec.ReadOnly } volumeID := ebs.VolumeID fsType := ebs.FSType partition := "" if ebs.Partition != 0 { partition = strconv.Itoa(ebs.Partition) } return &awsElasticBlockStoreBuilder{ awsElasticBlockStore: &awsElasticBlockStore{ podUID: podUID, volName: spec.Name, volumeID: volumeID, manager: manager, mounter: mounter, plugin: plugin, }, fsType: fsType, partition: partition, readOnly: readOnly, diskMounter: &awsSafeFormatAndMount{mounter, exec.New()}}, nil } func (plugin *awsElasticBlockStorePlugin) NewCleaner(volName string, podUID types.UID, mounter mount.Interface) (volume.Cleaner, error) { // Inject real implementations here, test through the internal function. return plugin.newCleanerInternal(volName, podUID, &AWSDiskUtil{}, mounter) } func (plugin *awsElasticBlockStorePlugin) newCleanerInternal(volName string, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.Cleaner, error) { return &awsElasticBlockStoreCleaner{&awsElasticBlockStore{ podUID: podUID, volName: volName, manager: manager, mounter: mounter, plugin: plugin, }}, nil } // Abstract interface to PD operations. type ebsManager interface { // Attaches the disk to the kubelet's host machine. AttachAndMountDisk(b *awsElasticBlockStoreBuilder, globalPDPath string) error // Detaches the disk from the kubelet's host machine. DetachDisk(c *awsElasticBlockStoreCleaner) error } // awsElasticBlockStore volumes are disk resources provided by Google Compute Engine // that are attached to the kubelet's host machine and exposed to the pod. type awsElasticBlockStore struct { volName string podUID types.UID // Unique id of the PD, used to find the disk resource in the provider. volumeID string // Utility interface that provides API calls to the provider to attach/detach disks. manager ebsManager // Mounter interface that provides system calls to mount the global path to the pod local path. mounter mount.Interface plugin *awsElasticBlockStorePlugin } func detachDiskLogError(ebs *awsElasticBlockStore) { err := ebs.manager.DetachDisk(&awsElasticBlockStoreCleaner{ebs}) if err != nil { glog.Warningf("Failed to detach disk: %v (%v)", ebs, err) } } // getVolumeProvider returns the AWS Volumes interface func (ebs *awsElasticBlockStore) getVolumeProvider() (aws_cloud.Volumes, error) { name := "aws" cloud, err := cloudprovider.GetCloudProvider(name, nil) if err != nil { return nil, err } volumes, ok := cloud.(aws_cloud.Volumes) if !ok { return nil, fmt.Errorf("Cloud provider does not support volumes") } return volumes, nil } type awsElasticBlockStoreBuilder struct { *awsElasticBlockStore // Filesystem type, optional. fsType string // Specifies the partition to mount partition string // Specifies whether the disk will be attached as read-only. readOnly bool // diskMounter provides the interface that is used to mount the actual block device. diskMounter mount.Interface } var _ volume.Builder = &awsElasticBlockStoreBuilder{} // SetUp attaches the disk and bind mounts to the volume path. func (b *awsElasticBlockStoreBuilder) SetUp() error { return b.SetUpAt(b.GetPath()) } // SetUpAt attaches the disk and bind mounts to the volume path. func (b *awsElasticBlockStoreBuilder) SetUpAt(dir string) error { // TODO: handle failed mounts here. mountpoint, err := b.mounter.IsMountPoint(dir) glog.V(4).Infof("PersistentDisk set up: %s %v %v", dir, mountpoint, err) if err != nil && !os.IsNotExist(err) { return err } if mountpoint { return nil } globalPDPath := makeGlobalPDPath(b.plugin.host, b.volumeID) if err := b.manager.AttachAndMountDisk(b, globalPDPath); err != nil { return err } if err := os.MkdirAll(dir, 0750); err != nil { // TODO: we should really eject the attach/detach out into its own control loop. detachDiskLogError(b.awsElasticBlockStore) return err } // Perform a bind mount to the full path to allow duplicate mounts of the same PD. options := []string{"bind"} if b.readOnly { options = append(options, "ro") } err = b.mounter.Mount(globalPDPath, dir, "", options) if err != nil { mountpoint, mntErr := b.mounter.IsMountPoint(dir) if mntErr != nil { glog.Errorf("isMountpoint check failed: %v", mntErr) return err } if mountpoint { if mntErr = b.mounter.Unmount(dir); mntErr != nil { glog.Errorf("Failed to unmount: %v", mntErr) return err } mountpoint, mntErr := b.mounter.IsMountPoint(dir) if mntErr != nil { glog.Errorf("isMountpoint check failed: %v", mntErr) return err } if mountpoint { // This is very odd, we don't expect it. We'll try again next sync loop. glog.Errorf("%s is still mounted, despite call to unmount(). Will try again next sync loop.", dir) return err } } os.Remove(dir) // TODO: we should really eject the attach/detach out into its own control loop. detachDiskLogError(b.awsElasticBlockStore) return err } return nil } func (b *awsElasticBlockStoreBuilder) IsReadOnly() bool { return b.readOnly } func makeGlobalPDPath(host volume.VolumeHost, volumeID string) string { // Clean up the URI to be more fs-friendly name := volumeID name = strings.Replace(name, "://", "/", -1) return path.Join(host.GetPluginDir(awsElasticBlockStorePluginName), "mounts", name) } func getVolumeIDFromGlobalMount(host volume.VolumeHost, globalPath string) (string, error) { basePath := path.Join(host.GetPluginDir(awsElasticBlockStorePluginName), "mounts") rel, err := filepath.Rel(basePath, globalPath) if err != nil { return "", err } if strings.Contains(rel, "../") { return "", fmt.Errorf("Unexpected mount path: " + globalPath) } // Reverse the :// replacement done in makeGlobalPDPath volumeID := rel if strings.HasPrefix(volumeID, "aws/") { volumeID = strings.Replace(volumeID, "aws/", "aws://", 1) } glog.V(2).Info("Mapping mount dir ", globalPath, " to volumeID ", volumeID) return volumeID, nil } func (ebs *awsElasticBlockStore) GetPath() string { name := awsElasticBlockStorePluginName return ebs.plugin.host.GetPodVolumeDir(ebs.podUID, util.EscapeQualifiedNameForDisk(name), ebs.volName) } type awsElasticBlockStoreCleaner struct { *awsElasticBlockStore } var _ volume.Cleaner = &awsElasticBlockStoreCleaner{} // Unmounts the bind mount, and detaches the disk only if the PD // resource was the last reference to that disk on the kubelet. func (c *awsElasticBlockStoreCleaner) TearDown() error { return c.TearDownAt(c.GetPath()) } // Unmounts the bind mount, and detaches the disk only if the PD // resource was the last reference to that disk on the kubelet. func (c *awsElasticBlockStoreCleaner) TearDownAt(dir string) error { mountpoint, err := c.mounter.IsMountPoint(dir) if err != nil { glog.V(2).Info("Error checking if mountpoint ", dir, ": ", err) return err } if !mountpoint { glog.V(2).Info("Not mountpoint, deleting") return os.Remove(dir) } refs, err := mount.GetMountRefs(c.mounter, dir) if err != nil { glog.V(2).Info("Error getting mountrefs for ", dir, ": ", err) return err } if len(refs) == 0 { glog.Warning("Did not find pod-mount for ", dir, " during tear-down") } // Unmount the bind-mount inside this pod if err := c.mounter.Unmount(dir); err != nil { glog.V(2).Info("Error unmounting dir ", dir, ": ", err) return err } // If len(refs) is 1, then all bind mounts have been removed, and the // remaining reference is the global mount. It is safe to detach. if len(refs) == 1 { // c.volumeID is not initially set for volume-cleaners, so set it here. c.volumeID, err = getVolumeIDFromGlobalMount(c.plugin.host, refs[0]) if err != nil { glog.V(2).Info("Could not determine volumeID from mountpoint ", refs[0], ": ", err) return err } if err := c.manager.DetachDisk(&awsElasticBlockStoreCleaner{c.awsElasticBlockStore}); err != nil { glog.V(2).Info("Error detaching disk ", c.volumeID, ": ", err) return err } } else { glog.V(2).Infof("Found multiple refs; won't detach EBS volume: %v", refs) } mountpoint, mntErr := c.mounter.IsMountPoint(dir) if mntErr != nil { glog.Errorf("isMountpoint check failed: %v", mntErr) return err } if !mountpoint { if err := os.Remove(dir); err != nil { glog.V(2).Info("Error removing mountpoint ", dir, ": ", err) return err } } return nil }
apache-2.0
tejima/OP3PKG
apps/pc_frontend/modules/member/templates/showActivitySuccess.php
775
<?php $title = $id === $sf_user->getMemberId() ? __('My %activity%', array( '%activity%' => $op_term['activity']->pluralize()->titleize() )) : __('%activity% of %0%', array( '%activity%' => $op_term['activity']->pluralize()->titleize(), '%0%' => $member->getName() )) ?> <?php if ($pager->getNbResults()): ?> <?php slot('pager') ?> <?php op_include_pager_navigation($pager, 'member/showActivity?page=%d&id='.$id) ?> <?php end_slot(); ?> <?php include_slot('pager') ?> <?php include_partial('default/activityBox', array( 'title' => $title, 'activities' => $pager->getResults()) ) ?> <?php include_slot('pager') ?> <?php else: ?> <?php op_include_parts('box', 'ActivityBox', array( 'body' => __('There is no %activity%.'), 'title' => $title )) ?> <?php endif; ?>
apache-2.0
jmluy/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/DeleteCalendarAction.java
2353
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ml.action; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ActionType; import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.xpack.core.ml.calendars.Calendar; import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper; import java.io.IOException; import java.util.Objects; public class DeleteCalendarAction extends ActionType<AcknowledgedResponse> { public static final DeleteCalendarAction INSTANCE = new DeleteCalendarAction(); public static final String NAME = "cluster:admin/xpack/ml/calendars/delete"; private DeleteCalendarAction() { super(NAME, AcknowledgedResponse::readFrom); } public static class Request extends AcknowledgedRequest<Request> { private String calendarId; public Request(StreamInput in) throws IOException { super(in); calendarId = in.readString(); } public Request(String calendarId) { this.calendarId = ExceptionsHelper.requireNonNull(calendarId, Calendar.ID.getPreferredName()); } public String getCalendarId() { return calendarId; } @Override public ActionRequestValidationException validate() { return null; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(calendarId); } @Override public int hashCode() { return Objects.hash(calendarId); } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } Request other = (Request) obj; return Objects.equals(calendarId, other.calendarId); } } }
apache-2.0
gfyoung/elasticsearch
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistField.java
1911
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.painless.spi; import java.util.Objects; /** * Field represents the equivalent of a Java field available as a whitelisted class field * within Painless. Fields for Painless classes may be accessed exactly as fields for Java classes * are using the '.' operator on an existing class variable/field. */ public class WhitelistField { /** Information about where this method was whitelisted from. */ public final String origin; /** The field name used to look up the field reflection object. */ public final String fieldName; /** The canonical type name for the field which can be used to look up the Java field through reflection. */ public final String canonicalTypeNameParameter; /** Standard constructor. All values must be not {@code null}. */ public WhitelistField(String origin, String fieldName, String canonicalTypeNameParameter) { this.origin = Objects.requireNonNull(origin); this.fieldName = Objects.requireNonNull(fieldName); this.canonicalTypeNameParameter = Objects.requireNonNull(canonicalTypeNameParameter); } }
apache-2.0
bdrillard/spark
sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/WideTableBenchmark.scala
2129
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.execution.benchmark import org.apache.spark.benchmark.Benchmark import org.apache.spark.sql.internal.SQLConf /** * Benchmark to measure performance for wide table. * {{{ * To run this benchmark: * 1. without sbt: bin/spark-submit --class <this class> * --jars <spark core test jar>,<spark catalyst test jar> <spark sql test jar> * 2. build/sbt "sql/test:runMain <this class>" * 3. generate result: SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt "sql/test:runMain <this class>" * Results will be written to "benchmarks/WideTableBenchmark-results.txt". * }}} */ object WideTableBenchmark extends SqlBasedBenchmark { override def runBenchmarkSuite(mainArgs: Array[String]): Unit = { runBenchmark("projection on wide table") { val N = 1 << 20 val df = spark.range(N) val columns = (0 until 400).map{ i => s"id as id$i"} val benchmark = new Benchmark("projection on wide table", N, output = output) Seq("10", "100", "1024", "2048", "4096", "8192", "65536").foreach { n => benchmark.addCase(s"split threshold $n", numIters = 5) { iter => withSQLConf(SQLConf.CODEGEN_METHOD_SPLIT_THRESHOLD.key -> n) { df.selectExpr(columns: _*).foreach(_ => ()) } } } benchmark.run() } } }
apache-2.0
fivejjs/PTVS
Common/Product/SharedProject/ProjectResources.cs
15207
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Resources; using System.Runtime.CompilerServices; using System.Threading; namespace Microsoft.VisualStudioTools.Project { internal class SR { internal const string AddReferenceDialogTitle = "AddReferenceDialogTitle"; internal const string AddReferenceExtensions = "AddReferenceExtensions"; internal const string AddToNullProjectError = "AddToNullProjectError"; internal const string Advanced = "Advanced"; internal const string AttributeLoad = "AttributeLoad"; internal const string BuildAction = "BuildAction"; internal const string BuildActionDescription = "BuildActionDescription"; internal const string BuildCaption = "BuildCaption"; internal const string BuildVerbosity = "BuildVerbosity"; internal const string BuildVerbosityDescription = "BuildVerbosityDescription"; internal const string BuildEventError = "BuildEventError"; internal const string Cancel = "Cancel"; internal const string CancelQueryEdit = "CancelQueryEdit"; internal const string CancelQueryEditMultiple = "CancelQueryEditMultiple"; internal const string CannotAddFileExists = "CannotAddFileExists"; internal const string CannotAddFileThatIsOpenInEditor = "CannotAddFileThatIsOpenInEditor"; internal const string CannotAddAsDescendantOfSelf = "CannotAddAsDescendantOfSelf"; internal const string CannotMoveFolderExists = "CannotMoveFolderExists"; internal const string CannotMoveIntoSameDirectory = "CannotMoveIntoSameDirectory"; internal const string CannotMoveIntoSubfolder = "CannotMoveIntoSubfolder"; internal const string CanNotSaveFileNotOpeneInEditor = "CanNotSaveFileNotOpeneInEditor"; internal const string cli1 = "cli1"; internal const string Compile = "Compile"; internal const string ConfirmExtensionChange = "ConfirmExtensionChange"; internal const string Content = "Content"; internal const string CopyToLocal = "CopyToLocal"; internal const string CopyToLocalDescription = "CopyToLocalDescription"; internal const string CustomTool = "CustomTool"; internal const string CustomToolDescription = "CustomToolDescription"; internal const string CustomToolNamespace = "CustomToolNamespace"; internal const string CustomToolNamespaceDescription = "CustomToolNamespaceDescription"; internal const string DetailsImport = "DetailsImport"; internal const string DetailsUserImport = "DetailsUserImport"; internal const string DetailsItem = "DetailsItem"; internal const string DetailsItemLocation = "DetailsItemLocation"; internal const string DetailsProperty = "DetailsProperty"; internal const string DetailsTarget = "DetailsTarget"; internal const string DetailsUsingTask = "DetailsUsingTask"; internal const string Detailed = "Detailed"; internal const string Diagnostic = "Diagnostic"; internal const string DirectoryExists = "DirectoryExists"; internal const string DirectoryExistsShortMessage = "DirectoryExistsShortMessage"; internal const string EditorViewError = "EditorViewError"; internal const string EmbeddedResource = "EmbeddedResource"; internal const string Error = "Error"; internal const string ErrorDetail = "ErrorDetail"; internal const string ErrorInvalidFileName = "ErrorInvalidFileName"; internal const string ErrorInvalidLaunchUrl = "ErrorInvalidLaunchUrl"; internal const string ErrorInvalidProjectName = "ErrorInvalidProjectName"; internal const string ErrorReferenceCouldNotBeAdded = "ErrorReferenceCouldNotBeAdded"; internal const string ErrorMsBuildRegistration = "ErrorMsBuildRegistration"; internal const string ErrorSaving = "ErrorSaving"; internal const string Exe = "Exe"; internal const string ExpectedObjectOfType = "ExpectedObjectOfType"; internal const string FailedToRetrieveProperties = "FailedToRetrieveProperties"; internal const string FileNameCannotContainALeadingPeriod = "FileNameCannotContainALeadingPeriod"; internal const string FileCannotBeRenamedToAnExistingFile = "FileCannotBeRenamedToAnExistingFile"; internal const string FileAlreadyExistsAndCannotBeRenamed = "FileAlreadyExistsAndCannotBeRenamed"; internal const string FileAlreadyExists = "FileAlreadyExists"; internal const string FileAlreadyExistsCaption = "FileAlreadyExistsCaption"; internal const string FileAlreadyInProject = "FileAlreadyInProject"; internal const string FileAlreadyInProjectCaption = "FileAlreadyInProjectCaption"; internal const string FileCopyError = "FileCopyError"; internal const string FileName = "FileName"; internal const string FileNameDescription = "FileNameDescription"; internal const string FileOrFolderAlreadyExists = "FileOrFolderAlreadyExists"; internal const string FileOrFolderCannotBeFound = "FileOrFolderCannotBeFound"; internal const string FileProperties = "FileProperties"; internal const string FolderCannotBeCreatedOnDisk = "FolderCannotBeCreatedOnDisk"; internal const string FolderName = "FolderName"; internal const string FolderNameDescription = "FolderNameDescription"; internal const string FolderPathTooLongShortMessage = "FolderPathTooLongShortMessage"; internal const string FolderProperties = "FolderProperties"; internal const string FullPath = "FullPath"; internal const string FullPathDescription = "FullPathDescription"; internal const string General = "General"; internal const string ItemDoesNotExistInProjectDirectory = "ItemDoesNotExistInProjectDirectory"; internal const string InvalidAutomationObject = "InvalidAutomationObject"; internal const string InvalidLoggerType = "InvalidLoggerType"; internal const string InvalidParameter = "InvalidParameter"; internal const string LaunchUrl = "LaunchUrl"; internal const string LaunchUrlDescription = "LaunchUrlDescription"; internal const string Library = "Library"; internal const string LinkedItemsAreNotSupported = "LinkedItemsAreNotSupported"; internal const string Minimal = "Minimal"; internal const string Misc = "Misc"; internal const string None = "None"; internal const string Normal = "Normal"; internal const string NestedProjectFailedToReload = "NestedProjectFailedToReload"; internal const string OutputPath = "OutputPath"; internal const string OutputPathDescription = "OutputPathDescription"; internal const string OverwriteFilesInExistingFolder = "OverwriteFilesInExistingFolder"; internal const string PasteFailed = "PasteFailed"; internal const string ParameterMustBeAValidGuid = "ParameterMustBeAValidGuid"; internal const string ParameterMustBeAValidItemId = "ParameterMustBeAValidItemId"; internal const string ParameterCannotBeNullOrEmpty = "ParameterCannotBeNullOrEmpty"; internal const string PathTooLong = "PathTooLong"; internal const string PathTooLongShortMessage = "PathTooLongShortMessage"; internal const string ProjectContainsCircularReferences = "ProjectContainsCircularReferences"; internal const string Program = "Program"; internal const string Project = "Project"; internal const string ProjectFile = "ProjectFile"; internal const string ProjectFileDescription = "ProjectFileDescription"; internal const string ProjectFolder = "ProjectFolder"; internal const string ProjectFolderDescription = "ProjectFolderDescription"; internal const string ProjectHome = "ProjectHome"; internal const string ProjectHomeDescription = "ProjectHomeDescription"; internal const string ProjectProperties = "ProjectProperties"; internal const string Quiet = "Quiet"; internal const string QueryReloadNestedProject = "QueryReloadNestedProject"; internal const string ReferenceAlreadyExists = "ReferenceAlreadyExists"; internal const string ReferencesNodeName = "ReferencesNodeName"; internal const string ReferenceProperties = "ReferenceProperties"; internal const string RefName = "RefName"; internal const string RefNameDescription = "RefNameDescription"; internal const string RenameFolder = "RenameFolder"; internal const string Retry = "Retry"; internal const string RTL = "RTL"; internal const string SaveCaption = "SaveCaption"; internal const string SaveModifiedDocuments = "SaveModifiedDocuments"; internal const string SaveOfProjectFileOutsideCurrentDirectory = "SaveOfProjectFileOutsideCurrentDirectory"; internal const string ScriptArguments = "ScriptArguments"; internal const string ScriptArgumentsDescription = "ScriptArgumentsDescription"; internal const string SeeActivityLog = "SeeActivityLog"; internal const string Settings = "Settings"; internal const string SourceUrlNotFound = "SourceUrlNotFound"; internal const string StandardEditorViewError = "StandardEditorViewError"; internal const string StartupFile = "StartupFile"; internal const string StartupFileDescription = "StartupFileDescription"; internal const string StartWebBrowser = "StartWebBrowser"; internal const string StartWebBrowserDescription = "StartWebBrowserDescription"; internal const string UnknownInParentheses = "UnknownInParentheses"; internal const string URL = "URL"; internal const string UseOfDeletedItemError = "UseOfDeletedItemError"; internal const string v1 = "v1"; internal const string v11 = "v11"; internal const string v2 = "v2"; internal const string v3 = "v3"; internal const string v35 = "v35"; internal const string v4 = "v4"; internal const string Warning = "Warning"; internal const string WorkingDirectory = "WorkingDirectory"; internal const string WorkingDirectoryDescription = "WorkingDirectoryDescription"; internal const string WinExe = "WinExe"; internal const string Publish = "Publish"; internal const string PublishDescription = "PublishDescription"; internal const string WebPiFeed = "WebPiFeed"; internal const string WebPiProduct = "WebPiProduct"; internal const string WebPiFeedDescription = "WebPiFeedDescription"; internal const string WebPiFeedError = "WebPiFeedError"; internal const string WebPiProductDescription = "WebPiProductDescription"; internal const string WebPiReferenceProperties = "WebPiReferenceProperties"; internal const string UnexpectedUpgradeError = "UnexpectedUpgradeError"; internal const string UpgradeNotRequired = "UpgradeNotRequired"; internal const string UpgradeCannotCheckOutProject = "UpgradeCannotCheckOutProject"; internal const string UpgradeCannotLoadProject = "UpgradeCannotLoadProject"; private static readonly Lazy<ResourceManager> _manager = new Lazy<ResourceManager>( () => new ResourceManager("Microsoft.VisualStudio.Project", typeof(SR).Assembly), LazyThreadSafetyMode.ExecutionAndPublication ); private static ResourceManager Manager { get { return _manager.Value; } } #if DEBUG // Detect incorrect calls [Obsolete] internal static string GetString(string value, CultureInfo c) { return null; } #endif protected static string GetStringInternal(ResourceManager manager, string value, object[] args) { string result = manager.GetString(value, CultureInfo.CurrentUICulture); if (result == null) { return null; } if (args.Length == 0) { Debug.Assert(result.IndexOf("{0}") < 0, "Resource string '" + value + "' requires format arguments."); return result; } Debug.WriteLineIf( Enumerable.Range(0, args.Length).Any(i => result.IndexOf(string.Format("{{{0}", i)) < 0), string.Format("Resource string '{0}' does not use all {1} arguments", value, args.Length) ); Debug.WriteLineIf( result.IndexOf(string.Format("{{{0}", args.Length)) >= 0, string.Format("Resource string '{0}' requires more than {1} argument(s)", value, args.Length) ); return string.Format(CultureInfo.CurrentUICulture, result, args); } public static string GetString(string value, params object[] args) { var result = GetStringInternal(Manager, value, args); Debug.Assert(result != null, "String resource '" + value + "' is missing"); return result ?? value; } private const string UnhandledException = "UnhandledException"; /// <summary> /// Gets a localized string suitable for logging details about an /// otherwise unhandled exception. This should not generally be shown to /// users through the UI. /// </summary> internal static string GetUnhandledExceptionString( Exception ex, Type callerType, [CallerFilePath] string callerFile = null, [CallerLineNumber] int callerLineNumber = 0, [CallerMemberName] string callerName = null ) { if (string.IsNullOrEmpty(callerName)) { callerName = callerType != null ? callerType.FullName : string.Empty; } else if (callerType != null) { callerName = callerType.FullName + "." + callerName; } return GetString(UnhandledException, ex, callerFile ?? String.Empty, callerLineNumber, callerName); } } }
apache-2.0
cluo512/storm
external/storm-opentsdb/src/main/java/org/apache/storm/opentsdb/bolt/OpenTsdbBolt.java
7757
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.storm.opentsdb.bolt; import org.apache.storm.opentsdb.OpenTsdbMetricDatapoint; import org.apache.storm.opentsdb.client.ClientResponse; import org.apache.storm.opentsdb.client.OpenTsdbClient; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.tuple.Tuple; import org.apache.storm.utils.BatchHelper; import org.apache.storm.utils.TupleUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Basic bolt implementation for storing timeseries datapoints to OpenTSDB. * <p/> * List of {@link OpenTsdbMetricDatapoint} is generated for each tuple with the configured {@code tupleOpenTsdbDatapointMappers}. * All these datapoints are batched till the given {@code batchSize} or {@code flushIntervalInSeconds} is reached. * <p/> * * Example topology: * <blockquote><pre> * OpenTsdbClient.Builder builder = OpenTsdbClient.newBuilder(openTsdbUrl).sync(30_000).returnDetails(); * final OpenTsdbBolt openTsdbBolt = new OpenTsdbBolt(builder, Collections.singletonList(TupleOpenTsdbDatapointMapper.DEFAULT_MAPPER)); * openTsdbBolt.withBatchSize(10).withFlushInterval(2).failTupleForFailedMetrics(); * topologyBuilder.setBolt("opentsdb", openTsdbBolt).shuffleGrouping("metric-gen"); * </pre></blockquote> * */ public class OpenTsdbBolt extends BaseRichBolt { private static final Logger LOG = LoggerFactory.getLogger(OpenTsdbBolt.class); private final OpenTsdbClient.Builder openTsdbClientBuilder; private final List<? extends ITupleOpenTsdbDatapointMapper> tupleOpenTsdbDatapointMappers; private int batchSize; private int flushIntervalInSeconds; private boolean failTupleForFailedMetrics; private BatchHelper batchHelper; private OpenTsdbClient openTsdbClient; private Map<OpenTsdbMetricDatapoint, Tuple> metricPointsWithTuple = new HashMap<>(); private OutputCollector collector; public OpenTsdbBolt(OpenTsdbClient.Builder openTsdbClientBuilder, ITupleOpenTsdbDatapointMapper tupleOpenTsdbDatapointMapper) { this.openTsdbClientBuilder = openTsdbClientBuilder; this.tupleOpenTsdbDatapointMappers = Collections.singletonList(tupleOpenTsdbDatapointMapper); } public OpenTsdbBolt(OpenTsdbClient.Builder openTsdbClientBuilder, List<? extends ITupleOpenTsdbDatapointMapper> tupleOpenTsdbDatapointMappers) { this.openTsdbClientBuilder = openTsdbClientBuilder; this.tupleOpenTsdbDatapointMappers = tupleOpenTsdbDatapointMappers; } public OpenTsdbBolt withFlushInterval(int flushIntervalInSeconds) { this.flushIntervalInSeconds = flushIntervalInSeconds; return this; } public OpenTsdbBolt withBatchSize(int batchSize) { this.batchSize = batchSize; return this; } /** * When it is invoked, this bolt acks only the tuples which have successful metrics stored into OpenTSDB and fails * the respective tuples of the failed metrics. * * @return same instance by setting {@code failTupleForFailedMetrics} to true */ public OpenTsdbBolt failTupleForFailedMetrics() { this.failTupleForFailedMetrics = true; return this; } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; batchHelper = new BatchHelper(batchSize, collector); openTsdbClient = openTsdbClientBuilder.build(); } @Override public void execute(Tuple tuple) { try { if (batchHelper.shouldHandle(tuple)) { final List<OpenTsdbMetricDatapoint> metricDataPoints = getMetricPoints(tuple); for (OpenTsdbMetricDatapoint metricDataPoint : metricDataPoints) { metricPointsWithTuple.put(metricDataPoint, tuple); } batchHelper.addBatch(tuple); } if (batchHelper.shouldFlush()) { LOG.debug("Sending metrics of size [{}]", metricPointsWithTuple.size()); ClientResponse.Details clientResponse = openTsdbClient.writeMetricPoints(metricPointsWithTuple.keySet()); if (failTupleForFailedMetrics && clientResponse != null && clientResponse.getFailed() > 0) { final List<ClientResponse.Details.Error> errors = clientResponse.getErrors(); LOG.error("Some of the metric points failed with errors: [{}]", clientResponse); if (errors != null && !errors.isEmpty()) { Set<Tuple> failedTuples = new HashSet<>(); for (ClientResponse.Details.Error error : errors) { final Tuple failedTuple = metricPointsWithTuple.get(error.getDatapoint()); if (failedTuple != null) { failedTuples.add(failedTuple); } } for (Tuple batchedTuple : batchHelper.getBatchTuples()) { if (failedTuples.contains(batchedTuple)) { collector.fail(batchedTuple); } else { collector.ack(batchedTuple); } } } else { throw new RuntimeException("Some of the metric points failed with details: " + errors); } } else { LOG.debug("Acknowledging batched tuples"); batchHelper.ack(); } metricPointsWithTuple.clear(); } } catch (Exception e) { batchHelper.fail(e); metricPointsWithTuple.clear(); } } private List<OpenTsdbMetricDatapoint> getMetricPoints(Tuple tuple) { List<OpenTsdbMetricDatapoint> metricDataPoints = new ArrayList<>(); for (ITupleOpenTsdbDatapointMapper tupleOpenTsdbDatapointMapper : tupleOpenTsdbDatapointMappers) { metricDataPoints.add(tupleOpenTsdbDatapointMapper.getMetricPoint(tuple)); } return metricDataPoints; } @Override public void cleanup() { openTsdbClient.cleanup(); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // this is a sink and no result to emit. } @Override public Map<String, Object> getComponentConfiguration() { return TupleUtils.putTickFrequencyIntoComponentConfig(super.getComponentConfiguration(), flushIntervalInSeconds); } }
apache-2.0
knative-sandbox/eventing-awssqs
vendor/google.golang.org/grpc/xds/internal/balancer/clusterresolver/logging.go
981
/* * * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package clusterresolver import ( "fmt" "google.golang.org/grpc/grpclog" internalgrpclog "google.golang.org/grpc/internal/grpclog" ) const prefix = "[xds-cluster-resolver-lb %p] " var logger = grpclog.Component("xds") func prefixLogger(p *clusterResolverBalancer) *internalgrpclog.PrefixLogger { return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf(prefix, p)) }
apache-2.0
hajee/biemond-orawls
lib/puppet/type/wls_server_template/listenport.rb
239
newproperty(:listenport) do include EasyType include EasyType::Mungers::Integer desc 'The listenport of the server' defaultto 7001 to_translate_to_resource do | raw_resource| raw_resource['listenport'].to_f.to_i end end
apache-2.0
Nogrod/jint
Jint.Tests.Ecma/TestCases/ch11/11.8/11.8.6/S11.8.6_A3.js
1338
// Copyright 2009 the Sputnik authors. All rights reserved. /** * If ShiftExpression is not an object, throw TypeError * * @path ch11/11.8/11.8.6/S11.8.6_A3.js * @description Checking all the types of primitives */ //CHECK#1 try { true instanceof true; $ERROR('#1: true instanceof true throw TypeError'); } catch (e) { if (e instanceof TypeError !== true) { $ERROR('#1: true instanceof true throw TypeError'); } } //CHECK#2 try { 1 instanceof 1; $ERROR('#2: 1 instanceof 1 throw TypeError'); } catch (e) { if (e instanceof TypeError !== true) { $ERROR('#2: 1 instanceof 1 throw TypeError'); } } //CHECK#3 try { "string" instanceof "string"; $ERROR('#3: "string" instanceof "string" throw TypeError'); } catch (e) { if (e instanceof TypeError !== true) { $ERROR('#3: "string" instanceof "string" throw TypeError'); } } //CHECK#4 try { undefined instanceof undefined; $ERROR('#4: undefined instanceof undefined throw TypeError'); } catch (e) { if (e instanceof TypeError !== true) { $ERROR('#4: undefined instanceof undefined throw TypeError'); } } //CHECK#5 try { null instanceof null; $ERROR('#5: null instanceof null throw TypeError'); } catch (e) { if (e instanceof TypeError !== true) { $ERROR('#5: null instanceof null throw TypeError'); } }
bsd-2-clause
justjoheinz/homebrew
Library/Formula/assimp.rb
1901
require 'formula' class Assimp < Formula homepage 'http://assimp.sourceforge.net/' stable do url "https://downloads.sourceforge.net/project/assimp/assimp-3.0/assimp--3.0.1270-source-only.zip" sha1 "e80a3a4326b649ed6585c0ce312ed6dd68942834" # makes assimp3 compile with clang # Reported upstream http://sourceforge.net/p/assimp/discussion/817654/thread/381fa18a # and http://sourceforge.net/p/assimp/patches/43/ # Committed in R1339, so when building HEAD no need for this patch patch :DATA end head 'https://github.com/assimp/assimp.git' depends_on 'cmake' => :build depends_on 'boost' def install system "cmake", ".", *std_cmake_args system "make install" end end __END__ diff --git a/CMakeLists.txt b/CMakeLists.txt index 3d5833e..d0cdd7c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required( VERSION 2.6 ) PROJECT( Assimp ) # Define here the needed parameters -set (ASSIMP_SV_REVISION 1264) +set (ASSIMP_SV_REVISION 255) set (ASSIMP_VERSION_MAJOR 3) set (ASSIMP_VERSION_MINOR 0) set (ASSIMP_VERSION_PATCH ${ASSIMP_SV_REVISION}) # subversion revision? diff --git a/code/STEPFile.h b/code/STEPFile.h index f958956..510e051 100644 --- a/code/STEPFile.h +++ b/code/STEPFile.h @@ -195,13 +195,13 @@ namespace STEP { // conversion support. template <typename T> const T& ResolveSelect(const DB& db) const { - return Couple<T>(db).MustGetObject(To<EXPRESS::ENTITY>())->To<T>(); + return Couple<T>(db).MustGetObject(To<EXPRESS::ENTITY>())->template To<T>(); } template <typename T> const T* ResolveSelectPtr(const DB& db) const { const EXPRESS::ENTITY* e = ToPtr<EXPRESS::ENTITY>(); - return e?Couple<T>(db).MustGetObject(*e)->ToPtr<T>():(const T*)0; + return e?Couple<T>(db).MustGetObject(*e)->template ToPtr<T>():(const T*)0; } public:
bsd-2-clause
ltilve/ChromiumGStreamerBackend
chromeos/dbus/bluetooth_profile_service_provider.cc
9406
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/dbus/bluetooth_profile_service_provider.h" #include "base/bind.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/threading/platform_thread.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_bluetooth_profile_service_provider.h" #include "dbus/exported_object.h" #include "dbus/message.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace chromeos { // The BluetoothProfileServiceProvider implementation used in production. class BluetoothProfileServiceProviderImpl : public BluetoothProfileServiceProvider { public: BluetoothProfileServiceProviderImpl(dbus::Bus* bus, const dbus::ObjectPath& object_path, Delegate* delegate) : origin_thread_id_(base::PlatformThread::CurrentId()), bus_(bus), delegate_(delegate), object_path_(object_path), weak_ptr_factory_(this) { VLOG(1) << "Creating Bluetooth Profile: " << object_path_.value(); exported_object_ = bus_->GetExportedObject(object_path_); exported_object_->ExportMethod( bluetooth_profile::kBluetoothProfileInterface, bluetooth_profile::kRelease, base::Bind(&BluetoothProfileServiceProviderImpl::Release, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothProfileServiceProviderImpl::OnExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_profile::kBluetoothProfileInterface, bluetooth_profile::kNewConnection, base::Bind(&BluetoothProfileServiceProviderImpl::NewConnection, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothProfileServiceProviderImpl::OnExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_profile::kBluetoothProfileInterface, bluetooth_profile::kRequestDisconnection, base::Bind(&BluetoothProfileServiceProviderImpl::RequestDisconnection, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothProfileServiceProviderImpl::OnExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_profile::kBluetoothProfileInterface, bluetooth_profile::kCancel, base::Bind(&BluetoothProfileServiceProviderImpl::Cancel, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothProfileServiceProviderImpl::OnExported, weak_ptr_factory_.GetWeakPtr())); } ~BluetoothProfileServiceProviderImpl() override { VLOG(1) << "Cleaning up Bluetooth Profile: " << object_path_.value(); // Unregister the object path so we can reuse with a new agent. bus_->UnregisterExportedObject(object_path_); } private: // Returns true if the current thread is on the origin thread. bool OnOriginThread() { return base::PlatformThread::CurrentId() == origin_thread_id_; } // Called by dbus:: when the profile is unregistered from the Bluetooth // daemon, generally by our request. void Release(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); delegate_->Released(); response_sender.Run(dbus::Response::FromMethodCall(method_call)); } // Called by dbus:: when the Bluetooth daemon establishes a new connection // to the profile. void NewConnection(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; scoped_ptr<dbus::FileDescriptor> fd(new dbus::FileDescriptor()); dbus::MessageReader array_reader(NULL); if (!reader.PopObjectPath(&device_path) || !reader.PopFileDescriptor(fd.get()) || !reader.PopArray(&array_reader)) { LOG(WARNING) << "NewConnection called with incorrect paramters: " << method_call->ToString(); return; } Delegate::Options options; while (array_reader.HasMoreData()) { dbus::MessageReader dict_entry_reader(NULL); std::string key; if (!array_reader.PopDictEntry(&dict_entry_reader) || !dict_entry_reader.PopString(&key)) { LOG(WARNING) << "NewConnection called with incorrect paramters: " << method_call->ToString(); } else { if (key == bluetooth_profile::kVersionProperty) dict_entry_reader.PopVariantOfUint16(&options.version); else if (key == bluetooth_profile::kFeaturesProperty) dict_entry_reader.PopVariantOfUint16(&options.features); } } Delegate::ConfirmationCallback callback = base::Bind( &BluetoothProfileServiceProviderImpl::OnConfirmation, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->NewConnection(device_path, fd.Pass(), options, callback); } // Called by dbus:: when the Bluetooth daemon is about to disconnect the // profile. void RequestDisconnection( dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; if (!reader.PopObjectPath(&device_path)) { LOG(WARNING) << "RequestDisconnection called with incorrect paramters: " << method_call->ToString(); return; } Delegate::ConfirmationCallback callback = base::Bind( &BluetoothProfileServiceProviderImpl::OnConfirmation, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->RequestDisconnection(device_path, callback); } // Called by dbus:: when the request failed before a reply was returned // from the device. void Cancel(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); delegate_->Cancel(); response_sender.Run(dbus::Response::FromMethodCall(method_call)); } // Called by dbus:: when a method is exported. void OnExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by the Delegate in response to a method requiring confirmation. void OnConfirmation(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender, Delegate::Status status) { DCHECK(OnOriginThread()); switch (status) { case Delegate::SUCCESS: { response_sender.Run(dbus::Response::FromMethodCall(method_call)); break; } case Delegate::REJECTED: { response_sender.Run(dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_profile::kErrorRejected, "rejected")); break; } case Delegate::CANCELLED: { response_sender.Run(dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_profile::kErrorCanceled, "canceled")); break; } default: NOTREACHED() << "Unexpected status code from delegate: " << status; } } // Origin thread (i.e. the UI thread in production). base::PlatformThreadId origin_thread_id_; // D-Bus bus object is exported on, not owned by this object and must // outlive it. dbus::Bus* bus_; // All incoming method calls are passed on to the Delegate and a callback // passed to generate the reply. |delegate_| is generally the object that // owns this one, and must outlive it. Delegate* delegate_; // D-Bus object path of object we are exporting, kept so we can unregister // again in our destructor. dbus::ObjectPath object_path_; // D-Bus object we are exporting, owned by this object. scoped_refptr<dbus::ExportedObject> exported_object_; // Weak pointer factory for generating 'this' pointers that might live longer // than we do. // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. base::WeakPtrFactory<BluetoothProfileServiceProviderImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(BluetoothProfileServiceProviderImpl); }; BluetoothProfileServiceProvider::BluetoothProfileServiceProvider() { } BluetoothProfileServiceProvider::~BluetoothProfileServiceProvider() { } // static BluetoothProfileServiceProvider* BluetoothProfileServiceProvider::Create( dbus::Bus* bus, const dbus::ObjectPath& object_path, Delegate* delegate) { if (!DBusThreadManager::Get()->IsUsingStub(DBusClientBundle::BLUETOOTH)) { return new BluetoothProfileServiceProviderImpl(bus, object_path, delegate); } else { return new FakeBluetoothProfileServiceProvider(object_path, delegate); } } } // namespace chromeos
bsd-3-clause
nilproject/NiL.JS
TestSets/tests/sputnik/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-605.js
1214
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-605.js * @description ES5 Attributes - all attributes in Object.freeze are correct */ function testcase() { var desc = Object.getOwnPropertyDescriptor(Object, "freeze"); var propertyAreCorrect = (desc.writable === true && desc.enumerable === false && desc.configurable === true); var temp = Object.freeze; try { Object.freeze = "2010"; var isWritable = (Object.freeze === "2010"); var isEnumerable = false; for (var prop in Object) { if (prop === "freeze") { isEnumerable = true; } } delete Object.freeze; var isConfigurable = !Object.hasOwnProperty("freeze"); return propertyAreCorrect && isWritable && !isEnumerable && isConfigurable; } finally { Object.defineProperty(Object, "freeze", { value: temp, writable: true, enumerable: false, configurable: true }); } } runTestCase(testcase);
bsd-3-clause
kinwahlai/phantomjs-ghostdriver
src/qt/src/corelib/tools/qvsnprintf.cpp
4076
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module 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 "qplatformdefs.h" #include "qbytearray.h" #include "qstring.h" #include "string.h" QT_BEGIN_NAMESPACE #ifndef QT_VSNPRINTF /*! \relates QByteArray A portable \c vsnprintf() function. Will call \c ::vsnprintf(), \c ::_vsnprintf(), or \c ::vsnprintf_s depending on the system, or fall back to an internal version. \a fmt is the \c printf() format string. The result is put into \a str, which is a buffer of at least \a n bytes. The caller is responsible to call \c va_end() on \a ap. \warning Since vsnprintf() shows different behavior on certain platforms, you should not rely on the return value or on the fact that you will always get a 0 terminated string back. Ideally, you should never call this function but use QString::sprintf() instead. \sa qsnprintf(), QString::sprintf() */ int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap) { if (!str || !fmt) return -1; QString buf; buf.vsprintf(fmt, ap); QByteArray ba = buf.toLocal8Bit(); if (n > 0) { size_t blen = qMin(size_t(ba.length()), size_t(n - 1)); memcpy(str, ba.constData(), blen); str[blen] = '\0'; // make sure str is always 0 terminated } return ba.length(); } #else QT_BEGIN_INCLUDE_NAMESPACE #include <stdio.h> QT_END_INCLUDE_NAMESPACE int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap) { return QT_VSNPRINTF(str, n, fmt, ap); } #endif /*! \relates QByteArray A portable snprintf() function, calls qvsnprintf. \a fmt is the \c printf() format string. The result is put into \a str, which is a buffer of at least \a n bytes. \warning Call this function only when you know what you are doing since it shows different behavior on certain platforms. Use QString::sprintf() to format a string instead. \sa qvsnprintf(), QString::sprintf() */ int qsnprintf(char *str, size_t n, const char *fmt, ...) { va_list ap; va_start(ap, fmt); int ret = qvsnprintf(str, n, fmt, ap); va_end(ap); return ret; } QT_END_NAMESPACE
bsd-3-clause
Betisman/node-workshop-learning
challenge1/finished/foo.js
64
0060547250224 hieu47 - o k hitqt5 - e hit7kt - g hi6qsn - kevin
mit
ahocevar/cdnjs
ajax/libs/F2/1.4.5/f2.no-jquery-or-bootstrap.js
286788
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; } /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function () { // Detect the `define` function exposed by asynchronous module loaders. The // strict `define` check is necessary for compatibility with `r.js`. var isLoader = typeof define === "function" && define.amd; // A set of types used to distinguish objects from primitives. var objectTypes = { "function": true, "object": true }; // Detect the `exports` object exposed by CommonJS implementations. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; // Use the `global` object exposed by Node (including Browserify via // `insert-module-globals`), Narwhal, and Ringo as the default context, // and the `window` object in browsers. Rhino exports a `global` function // instead. var root = objectTypes[typeof window] && window || this, freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { root = freeGlobal; } // Public: Initializes JSON 3 using the given `context` object, attaching the // `stringify` and `parse` functions to the specified `exports` object. function runInContext(context, exports) { context || (context = root["Object"]()); exports || (exports = root["Object"]()); // Native constructor aliases. var Number = context["Number"] || root["Number"], String = context["String"] || root["String"], Object = context["Object"] || root["Object"], Date = context["Date"] || root["Date"], SyntaxError = context["SyntaxError"] || root["SyntaxError"], TypeError = context["TypeError"] || root["TypeError"], Math = context["Math"] || root["Math"], nativeJSON = context["JSON"] || root["JSON"]; // Delegate to the native `stringify` and `parse` implementations. if (typeof nativeJSON == "object" && nativeJSON) { exports.stringify = nativeJSON.stringify; exports.parse = nativeJSON.parse; } // Convenience aliases. var objectProto = Object.prototype, getClass = objectProto.toString, isProperty, forEach, undef; // Test the `Date#getUTC*` methods. Based on work by @Yaffle. var isExtended = new Date(-3509827334573292); try { // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical // results for certain dates in Opera >= 10.53. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && // Safari < 2.0.2 stores the internal millisecond time value correctly, // but clips the values returned by the date methods to the range of // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} // Internal: Determines whether the native `JSON.stringify` and `parse` // implementations are spec-compliant. Based on work by Ken Snyder. function has(name) { if (has[name] !== undef) { // Return cached feature test result. return has[name]; } var isSupported; if (name == "bug-string-char-index") { // IE <= 7 doesn't support accessing string characters using square // bracket notation. IE 8 only supports this for primitives. isSupported = "a"[0] != "a"; } else if (name == "json") { // Indicates whether both `JSON.stringify` and `JSON.parse` are // supported. isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; // Test `JSON.stringify`. if (name == "json-stringify") { var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { // A test function object with a custom `toJSON` method. (value = function () { return 1; }).toJSON = value; try { stringifySupported = // Firefox 3.1b1 and b2 serialize string, number, and boolean // primitives as object literals. stringify(0) === "0" && // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object // literals. stringify(new Number()) === "0" && stringify(new String()) == '""' && // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or // does not define a canonical JSON representation (this applies to // objects with `toJSON` properties as well, *unless* they are nested // within an object or array). stringify(getClass) === undef && // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and // FF 3.1b3 pass this test. stringify(undef) === undef && // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, // respectively, if the value is omitted entirely. stringify() === undef && // FF 3.1b1, 2 throw an error if the given value is not a number, // string, array, object, Boolean, or `null` literal. This applies to // objects with custom `toJSON` methods as well, unless they are nested // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` // methods entirely. stringify(value) === "1" && stringify([value]) == "[1]" && // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of // `"[null]"`. stringify([undef]) == "[null]" && // YUI 3.0.0b1 fails to serialize `null` literals. stringify(null) == "null" && // FF 3.1b1, 2 halts serialization if an array contains a function: // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 // elides non-JSON values from objects and arrays, unless they // define custom `toJSON` methods. stringify([undef, getClass, null]) == "[null,null,null]" && // Simple serialization test. FF 3.1b1 uses Unicode escape sequences // where character escape codes are expected (e.g., `\b` => `\u0008`). stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly // serialize extended years. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && // The milliseconds are optional in ES 5, but required in 5.1. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative // four-digit years instead of six-digit years. Credits: @Yaffle. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond // values less than 1000. Credits: @Yaffle. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } // Test `JSON.parse`. if (name == "json-parse") { var parse = exports.parse; if (typeof parse == "function") { try { // FF 3.1b1, b2 will throw an exception if a bare literal is provided. // Conforming implementations should also coerce the initial argument to // a string prior to parsing. if (parse("0") === 0 && !parse(false)) { // Simple parsing test. value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { // FF 4.0 and 4.0.1 allow leading `+` signs and leading // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow // certain octal literals. parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal // points. These environments, along with FF 3.1b1 and 2, // also allow trailing commas in JSON objects and arrays. parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { // Common `[[Class]]` name aliases. var functionClass = "[object Function]", dateClass = "[object Date]", numberClass = "[object Number]", stringClass = "[object String]", arrayClass = "[object Array]", booleanClass = "[object Boolean]"; // Detect incomplete support for accessing string characters by index. var charIndexBuggy = has("bug-string-char-index"); // Define additional utility methods if the `Date` methods are buggy. if (!isExtended) { var floor = Math.floor; // A mapping between the months of the year and the number of days between // January 1st and the first of the respective month. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; // Internal: Calculates the number of days between the Unix epoch and the // first day of the given month. var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } // Internal: Determines if a property is a direct property of the given // object. Delegates to the native `Object#hasOwnProperty` method. if (!(isProperty = objectProto.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { // The *proto* property cannot be set multiple times in recent // versions of Firefox and SeaMonkey. "toString": 1 }, members).toString != getClass) { // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but // supports the mutable *proto* property. isProperty = function (property) { // Capture and break the object's prototype chain (see section 8.6.2 // of the ES 5.1 spec). The parenthesized expression prevents an // unsafe transformation by the Closure Compiler. var original = this.__proto__, result = property in (this.__proto__ = null, this); // Restore the original prototype chain. this.__proto__ = original; return result; }; } else { // Capture a reference to the top-level `Object` constructor. constructor = members.constructor; // Use the `constructor` property to simulate `Object#hasOwnProperty` in // other environments. isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } // Internal: Normalizes the `for...in` iteration algorithm across // environments. Each enumerated key is yielded to a `callback` function. forEach = function (object, callback) { var size = 0, Properties, members, property; // Tests for bugs in the current environment's `for...in` algorithm. The // `valueOf` property inherits the non-enumerable flag from // `Object.prototype` in older versions of IE, Netscape, and Mozilla. (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; // Iterate over a new instance of the `Properties` class. members = new Properties(); for (property in members) { // Ignore all properties inherited from `Object.prototype`. if (isProperty.call(members, property)) { size++; } } Properties = members = null; // Normalize the iteration algorithm. if (!size) { // A list of non-enumerable properties inherited from `Object.prototype`. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable // properties. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; for (property in object) { // Gecko <= 1.0 enumerates the `prototype` property of functions under // certain conditions; IE does not. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } // Manually invoke the callback for each non-enumerable property. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { // Safari <= 2.0.4 enumerates shadowed properties twice. forEach = function (object, callback) { // Create a set of iterated properties. var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { // Store each property name to prevent double enumeration. The // `prototype` property of functions is not enumerated due to cross- // environment inconsistencies. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { // No bugs detected; use the standard `for...in` algorithm. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } // Manually invoke the callback for the `constructor` property due to // cross-environment inconsistencies. if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; // Public: Serializes a JavaScript `value` as a JSON string. The optional // `filter` argument may specify either a function that alters how object and // array members are serialized, or an array of strings and numbers that // indicates which properties should be serialized. The optional `width` // argument may be either a string or number that specifies the indentation // level of the output. if (!has("json-stringify")) { // Internal: A map of control characters and their escaped equivalents. var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; // Internal: Converts `value` into a zero-padded string such that its // length is at least equal to `width`. The `width` must be <= 6. var leadingZeroes = "000000"; var toPaddedString = function (width, value) { // The `|| 0` expression is necessary to work around a bug in // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. return (leadingZeroes + (value || 0)).slice(-width); }; // Internal: Double-quotes a string `value`, replacing all ASCII control // characters (characters with code unit values between 0 and 31) with // their escaped equivalents. This is an implementation of the // `Quote(value)` operation defined in ES 5.1 section 15.12.3. var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); for (; index < length; index++) { var charCode = value.charCodeAt(index); // If the character is a control character, append its Unicode or // shorthand escape sequence; otherwise, append the character as-is. switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += useCharIndex ? symbols[index] : value.charAt(index); } } return result + '"'; }; // Internal: Recursively serializes an object. Implements the // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { // Necessary for host object support. value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { // Dates are serialized according to the `Date#toJSON` method // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 // for the ISO 8601 date time string format. if (getDay) { // Manually compute the year, month, date, hours, minutes, // seconds, and milliseconds if the `getUTC*` methods are // buggy. Adapted from @Yaffle's `date-shim` project. date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); // The `time` value specifies the time within the day (see ES // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used // to compute `A modulo B`, as the `%` operator does not // correspond to the `modulo` operation for negative numbers. time = (value % 864e5 + 864e5) % 864e5; // The hours, minutes, seconds, and milliseconds are obtained by // decomposing the time within the day. See section 15.9.1.10. hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } // Serialize extended years correctly. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + // Months, dates, hours, minutes, and seconds should have two // digits; milliseconds should have three. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + // Milliseconds are optional in ES 5.0, but required in 5.1. "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 // ignores all `toJSON` methods on these objects unless they are // defined directly on an instance. value = value.toJSON(property); } } if (callback) { // If a replacement function was provided, call it to obtain the value // for serialization. value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { // Booleans are represented literally. return "" + value; } else if (className == numberClass) { // JSON numbers must be finite. `Infinity` and `NaN` are serialized as // `"null"`. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { // Strings are double-quoted and escaped. return quote("" + value); } // Recursively serialize objects and arrays. if (typeof value == "object") { // Check for cyclic structures. This is a linear search; performance // is inversely proportional to the number of unique nested objects. for (length = stack.length; length--;) { if (stack[length] === value) { // Cyclic structures cannot be serialized by `JSON.stringify`. throw TypeError(); } } // Add the object to the stack of traversed objects. stack.push(value); results = []; // Save the current indentation level and indent one additional level. prefix = indentation; indentation += whitespace; if (className == arrayClass) { // Recursively serialize array elements. for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { // Recursively serialize object members. Members are selected from // either a user-specified list of property names, or the object // itself. forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} // is not the empty string, let `member` {quote(property) + ":"} // be the concatenation of `member` and the `space` character." // The "`space` character" refers to the literal space // character, not the `space` {width} argument provided to // `JSON.stringify`. results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } // Remove the object from the traversed object stack. stack.pop(); return result; } }; // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. exports.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (objectTypes[typeof filter] && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { // Convert the property names array into a makeshift set. properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { // Convert the `width` to an integer and create a string containing // `width` number of space characters. if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } // Opera <= 7.54u2 discards the values associated with empty string keys // (`""`) only if they are used directly within an object member list // (e.g., `!("" in { "": 1})`). return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } // Public: Parses a JSON source string. if (!has("json-parse")) { var fromCharCode = String.fromCharCode; // Internal: A map of escaped control characters and their unescaped // equivalents. var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; // Internal: Stores the parser state. var Index, Source; // Internal: Resets the parser state and throws a `SyntaxError`. var abort = function () { Index = Source = null; throw SyntaxError(); }; // Internal: Returns the next token, or `"$"` if the parser has reached // the end of the source string. A token may be a string, number, `null` // literal, or Boolean literal. var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: // Skip whitespace tokens, including tabs, carriage returns, line // feeds, and space characters. Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at // the current position. value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: // `"` delimits a JSON string; advance to the next character and // begin parsing the string. String tokens are prefixed with the // sentinel `@` character to distinguish them from punctuators and // end-of-string tokens. for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { // Unescaped ASCII control characters (those with a code unit // less than the space character) are not permitted. abort(); } else if (charCode == 92) { // A reverse solidus (`\`) marks the beginning of an escaped // control character (including `"`, `\`, and `/`) or Unicode // escape sequence. charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: // Revive escaped control characters. value += Unescapes[charCode]; Index++; break; case 117: // `\u` marks the beginning of a Unicode escape sequence. // Advance to the first character and validate the // four-digit code point. begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); // A valid sequence comprises four hexdigits (case- // insensitive) that form a single hexadecimal value. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { // Invalid Unicode escape sequence. abort(); } } // Revive the escaped character. value += fromCharCode("0x" + source.slice(begin, Index)); break; default: // Invalid escape sequence. abort(); } } else { if (charCode == 34) { // An unescaped double-quote character marks the end of the // string. break; } charCode = source.charCodeAt(Index); begin = Index; // Optimize for the common case where a string is valid. while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } // Append the string as-is. value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { // Advance to the next character and return the revived string. Index++; return value; } // Unterminated string. abort(); default: // Parse numbers and literals. begin = Index; // Advance past the negative sign, if one is specified. if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } // Parse an integer or floating-point value. if (charCode >= 48 && charCode <= 57) { // Leading zeroes are interpreted as octal literals. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { // Illegal octal literal. abort(); } isSigned = false; // Parse the integer component. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); // Floats cannot contain a leading decimal point; however, this // case is already accounted for by the parser. if (source.charCodeAt(Index) == 46) { position = ++Index; // Parse the decimal component. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal trailing decimal. abort(); } Index = position; } // Parse exponents. The `e` denoting the exponent is // case-insensitive. charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); // Skip past the sign following the exponent, if one is // specified. if (charCode == 43 || charCode == 45) { Index++; } // Parse the exponential component. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal empty exponent. abort(); } Index = position; } // Coerce the parsed value to a JavaScript number. return +source.slice(begin, Index); } // A negative sign may only precede numbers. if (isSigned) { abort(); } // `true`, `false`, and `null` literals. if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } // Unrecognized token. abort(); } } // Return the sentinel `$` character if the parser has reached the end // of the source string. return "$"; }; // Internal: Parses a JSON `value` token. var get = function (value) { var results, hasMembers; if (value == "$") { // Unexpected end of input. abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { // Remove the sentinel `@` character. return value.slice(1); } // Parse object and array literals. if (value == "[") { // Parses a JSON array, returning a new JavaScript array. results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing square bracket marks the end of the array literal. if (value == "]") { break; } // If the array literal contains elements, the current token // should be a comma separating the previous element from the // next. if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { // Unexpected trailing `,` in array literal. abort(); } } else { // A `,` must separate each array element. abort(); } } // Elisions and leading commas are not permitted. if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { // Parses a JSON object, returning a new JavaScript object. results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing curly brace marks the end of the object literal. if (value == "}") { break; } // If the object literal contains members, the current token // should be a comma separator. if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { // Unexpected trailing `,` in object literal. abort(); } } else { // A `,` must separate each object member. abort(); } } // Leading commas are not permitted, object property names must be // double-quoted strings, and a `:` must separate each property // name and value. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } // Unexpected token encountered. abort(); } return value; }; // Internal: Updates a traversed object member. var update = function (source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; // Internal: Recursively traverses a parsed JSON object, invoking the // `callback` function for each value. This is an implementation of the // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { // `forEach` can't be used to traverse an array in Opera <= 8.54 // because its `Object#hasOwnProperty` implementation returns `false` // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; // Public: `JSON.parse`. See ES 5.1 section 15.12.2. exports.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); // If a JSON string contains multiple tokens, it is invalid. if (lex() != "$") { abort(); } // Reset the parser state. Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } exports["runInContext"] = runInContext; return exports; } if (freeExports && !isLoader) { // Export for CommonJS environments. runInContext(root, freeExports); } else { // Export for web browsers and JavaScript engines. var nativeJSON = root.JSON, previousJSON = root["JSON3"], isRestored = false; var JSON3 = runInContext(root, (root["JSON3"] = { // Public: Restores the original value of the global `JSON` object and // returns a reference to the `JSON3` object. "noConflict": function () { if (!isRestored) { isRestored = true; root.JSON = nativeJSON; root["JSON3"] = previousJSON; nativeJSON = previousJSON = null; } return JSON3; } })); root.JSON = { "parse": JSON3.parse, "stringify": JSON3.stringify }; } // Export for asynchronous module loaders. if (isLoader) { define(function () { return JSON3; }); } }).call(this); /*! * Hij1nx requires the following notice to accompany EventEmitter: * * Copyright (c) 2011 hij1nx * * http://www.twitter.com/hij1nx * * Version: 2013-09-17 * GitHub SHA: 3caacce662998d7903d368b0c0f847f259cae0f7 * https://github.com/hij1nx/EventEmitter2 * Diff this version to master: https://github.com/hij1nx/EventEmitter2/compare/3caacce662998d7903d368b0c0f847f259cae0f7...master * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ ;!function(exports, undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = {}; if (this._conf) { configure.call(this, this._conf); } } function configure(conf) { if (conf) { this._conf = conf; conf.delimiter && (this.delimiter = conf.delimiter); conf.maxListeners && (this._events.maxListeners = conf.maxListeners); conf.wildcard && (this.wildcard = conf.wildcard); conf.newListener && (this.newListener = conf.newListener); if (this.wildcard) { this.listenerTree = {}; } } } function EventEmitter(conf) { this._events = {}; this.newListener = false; configure.call(this, conf); } // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name) { if (!tree[name]) { tree[name] = {}; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else if(typeof tree._listeners === 'function') { tree._listeners = [tree._listeners, listener]; } else if (isArray(tree._listeners)) { tree._listeners.push(listener); if (!tree._listeners.warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && tree._listeners.length > m) { tree._listeners.warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', tree._listeners.length); console.trace(); } } } return true; } name = type.shift(); } return true; } // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { this._events || init.call(this); this._events.maxListeners = n; if (!this._conf) this._conf = {}; this._conf.maxListeners = n; }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { this.many(event, 1, fn); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } fn.apply(this, arguments); } listener._origin = fn; this.on(event, listener); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener' && !this.newListener) { if (!this._events.newListener) { return false; } } // Loop through the *_all* functions and invoke them. if (this._all) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; for (i = 0, l = this._all.length; i < l; i++) { this.event = type; this._all[i].apply(this, args); } } // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._all && !this._events.error && !(this.wildcard && this.listenerTree.error)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } var handler; if(this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; if (arguments.length === 1) { handler.call(this); } else if (arguments.length > 1) switch (arguments.length) { case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (handler) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { this.event = type; listeners[i].apply(this, args); } return (listeners.length > 0) || this._all; } else { return this._all; } }; EventEmitter.prototype.on = function(type, listener) { if (typeof type === 'function') { this.onAny(type); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if(this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if(typeof this._events[type] === 'function') { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } return this; }; EventEmitter.prototype.onAny = function(fn) { if(!this._all) { this._all = []; } if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } // Add the function to the event listener collection. this._all.push(fn); return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { continue; } if(this.wildcard) { leaf._listeners.splice(position, 1); } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } return this; } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); return this; } } } else { this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else { if (!this._events[type]) return this; this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if(this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; // if (typeof define === 'function' && define.amd) { // define('EventEmitter2', [], function() { // return EventEmitter; // }); // } else { exports.EventEmitter2 = EventEmitter; // } }(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window); /** * easyXDM * http://easyxdm.net/ * Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) { /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // var global = this; var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded var emptyFn = Function.prototype; var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4) var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global) var easyXDM = {}; var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite var IFRAME_PREFIX = "easyXDM_"; var HAS_NAME_PROPERTY_BUG; var useHash = false; // whether to use the hash over the query var flashVersion; // will be set if using flash var HAS_FLASH_THROTTLED_BUG; // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(object, property){ var t = typeof object[property]; return t == 'function' || (!!(t == 'object' && object[property])) || t == 'unknown'; } function isHostObject(object, property){ return !!(typeof(object[property]) == 'object' && object[property]); } // end // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ function isArray(o){ return Object.prototype.toString.call(o) === '[object Array]'; } // end function hasFlash(){ var name = "Shockwave Flash", mimeType = "application/x-shockwave-flash"; if (!undef(navigator.plugins) && typeof navigator.plugins[name] == "object") { // adapted from the swfobject code var description = navigator.plugins[name].description; if (description && !undef(navigator.mimeTypes) && navigator.mimeTypes[mimeType] && navigator.mimeTypes[mimeType].enabledPlugin) { flashVersion = description.match(/\d+/g); } } if (!flashVersion) { var flash; try { flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); flashVersion = Array.prototype.slice.call(flash.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1); flash = null; } catch (notSupportedException) { } } if (!flashVersion) { return false; } var major = parseInt(flashVersion[0], 10), minor = parseInt(flashVersion[1], 10); HAS_FLASH_THROTTLED_BUG = major > 9 && minor > 0; return true; } /* * Cross Browser implementation for adding and removing event listeners. */ var on, un; if (isHostMethod(window, "addEventListener")) { on = function(target, type, listener){ target.addEventListener(type, listener, false); }; un = function(target, type, listener){ target.removeEventListener(type, listener, false); }; } else if (isHostMethod(window, "attachEvent")) { on = function(object, sEvent, fpNotify){ object.attachEvent("on" + sEvent, fpNotify); }; un = function(object, sEvent, fpNotify){ object.detachEvent("on" + sEvent, fpNotify); }; } else { throw new Error("Browser not supported"); } /* * Cross Browser implementation of DOMContentLoaded. */ var domIsReady = false, domReadyQueue = [], readyState; if ("readyState" in document) { // If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and // 'interactive' (HTML5 specs, recent WebKit builds) states. // https://bugs.webkit.org/show_bug.cgi?id=45119 readyState = document.readyState; domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive")); } else { // If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately // when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not. // We only need a body to add elements to, so the existence of document.body is enough for us. domIsReady = !!document.body; } function dom_onReady(){ if (domIsReady) { return; } domIsReady = true; for (var i = 0; i < domReadyQueue.length; i++) { domReadyQueue[i](); } domReadyQueue.length = 0; } if (!domIsReady) { if (isHostMethod(window, "addEventListener")) { on(document, "DOMContentLoaded", dom_onReady); } else { on(document, "readystatechange", function(){ if (document.readyState == "complete") { dom_onReady(); } }); if (document.documentElement.doScroll && window === top) { var doScrollCheck = function(){ if (domIsReady) { return; } // http://javascript.nwbox.com/IEContentLoaded/ try { document.documentElement.doScroll("left"); } catch (e) { setTimeout(doScrollCheck, 1); return; } dom_onReady(); }; doScrollCheck(); } } // A fallback to window.onload, that will always work on(window, "load", dom_onReady); } /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {Object} scope An optional scope for the function to be called with. */ function whenReady(fn, scope){ if (domIsReady) { fn.call(scope); return; } domReadyQueue.push(function(){ fn.call(scope); }); } /** * Returns an instance of easyXDM from the parent window with * respect to the namespace. * * @return An instance of easyXDM (in the parent window) */ function getParentObject(){ var obj = parent; if (namespace !== "") { for (var i = 0, ii = namespace.split("."); i < ii.length; i++) { obj = obj[ii[i]]; } } return obj.easyXDM; } /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ function noConflict(ns){ window.easyXDM = _easyXDM; namespace = ns; if (namespace) { IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_"; } return easyXDM; } /* * Methods for working with URLs */ /** * Get the domain name from a url. * @param {String} url The url to extract the domain from. * @return The domain part of the url. * @type {String} */ function getDomainName(url){ return url.match(reURI)[3]; } /** * Get the port for a given URL, or "" if none * @param {String} url The url to extract the port from. * @return The port part of the url. * @type {String} */ function getPort(url){ return url.match(reURI)[4] || ""; } /** * Returns a string containing the schema, domain and if present the port * @param {String} url The url to extract the location from * @return {String} The location part of the url */ function getLocation(url){ var m = url.toLowerCase().match(reURI); var proto = m[2], domain = m[3], port = m[4] || ""; if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) { port = ""; } return proto + "//" + domain + port; } /** * Resolves a relative url into an absolute one. * @param {String} url The path to resolve. * @return {String} The resolved url. */ function resolveUrl(url){ // replace all // except the one in proto with / url = url.replace(reDoubleSlash, "$1/"); // If the url is a valid url we do nothing if (!url.match(/^(http||https):\/\//)) { // If this is a relative path var path = (url.substring(0, 1) === "/") ? "" : location.pathname; if (path.substring(path.length - 1) !== "/") { path = path.substring(0, path.lastIndexOf("/") + 1); } url = location.protocol + "//" + location.host + path + url; } // reduce all 'xyz/../' to just '' while (reParent.test(url)) { url = url.replace(reParent, ""); } return url; } /** * Appends the parameters to the given url.<br/> * The base url can contain existing query parameters. * @param {String} url The base url. * @param {Object} parameters The parameters to add. * @return {String} A new valid url with the parameters appended. */ function appendQueryParameters(url, parameters){ var hash = "", indexOf = url.indexOf("#"); if (indexOf !== -1) { hash = url.substring(indexOf); url = url.substring(0, indexOf); } var q = []; for (var key in parameters) { if (parameters.hasOwnProperty(key)) { q.push(key + "=" + encodeURIComponent(parameters[key])); } } return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash; } // build the query object either from location.query, if it contains the xdm_e argument, or from location.hash var query = (function(input){ input = input.substring(1).split("&"); var data = {}, pair, i = input.length; while (i--) { pair = input[i].split("="); data[pair[0]] = decodeURIComponent(pair[1]); } return data; }(/xdm_e=/.test(location.search) ? location.search : location.hash)); /* * Helper methods */ /** * Helper for checking if a variable/property is undefined * @param {Object} v The variable to test * @return {Boolean} True if the passed variable is undefined */ function undef(v){ return typeof v === "undefined"; } /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ var getJSON = function(){ var cached = {}; var obj = { a: [1, 2, 3] }, json = "{\"a\":[1,2,3]}"; if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) { // this is a working JSON instance return JSON; } if (Object.toJSON) { if (Object.toJSON(obj).replace((/\s/g), "") === json) { // this is a working stringify method cached.stringify = Object.toJSON; } } if (typeof String.prototype.evalJSON === "function") { obj = json.evalJSON(); if (obj.a && obj.a.length === 3 && obj.a[2] === 3) { // this is a working parse method cached.parse = function(str){ return str.evalJSON(); }; } } if (cached.stringify && cached.parse) { // Only memoize the result if we have valid instance getJSON = function(){ return cached; }; return cached; } return null; }; /** * Applies properties from the source object to the target object.<br/> * @param {Object} target The target of the properties. * @param {Object} source The source of the properties. * @param {Boolean} noOverwrite Set to True to only set non-existing properties. */ function apply(destination, source, noOverwrite){ var member; for (var prop in source) { if (source.hasOwnProperty(prop)) { if (prop in destination) { member = source[prop]; if (typeof member === "object") { apply(destination[prop], member, noOverwrite); } else if (!noOverwrite) { destination[prop] = source[prop]; } } else { destination[prop] = source[prop]; } } } return destination; } // This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName]. function testForNamePropertyBug(){ var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input")); input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name]; document.body.removeChild(form); } /** * Creates a frame and appends it to the DOM. * @param config {object} This object can have the following properties * <ul> * <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li> * <li> {object} attr The attributes that should be set on the frame.</li> * <li> {DOMElement} container Its parent element (Optional).</li> * <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li> * </ul> * @return The frames DOMElement * @type DOMElement */ function createFrame(config){ if (undef(HAS_NAME_PROPERTY_BUG)) { testForNamePropertyBug(); } var frame; // This is to work around the problems in IE6/7 with setting the name property. // Internally this is set as 'submitName' instead when using 'iframe.name = ...' // This is not required by easyXDM itself, but is to facilitate other use cases if (HAS_NAME_PROPERTY_BUG) { frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>"); } else { frame = document.createElement("IFRAME"); frame.name = config.props.name; } frame.id = frame.name = config.props.name; delete config.props.name; if (typeof config.container == "string") { config.container = document.getElementById(config.container); } if (!config.container) { // This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers. apply(frame.style, { position: "absolute", top: "-2000px", // Avoid potential horizontal scrollbar left: "0px" }); config.container = document.body; } // HACK: IE cannot have the src attribute set when the frame is appended // into the container, so we set it to "javascript:false" as a // placeholder for now. If we left the src undefined, it would // instead default to "about:blank", which causes SSL mixed-content // warnings in IE6 when on an SSL parent page. var src = config.props.src; config.props.src = "javascript:false"; // transfer properties to the frame apply(frame, config.props); frame.border = frame.frameBorder = 0; frame.allowTransparency = true; config.container.appendChild(frame); if (config.onLoad) { on(frame, "load", config.onLoad); } // set the frame URL to the proper value (we previously set it to // "javascript:false" to work around the IE issue mentioned above) if(config.usePost) { var form = config.container.appendChild(document.createElement('form')), input; form.target = frame.name; form.action = src; form.method = 'POST'; if (typeof(config.usePost) === 'object') { for (var i in config.usePost) { if (config.usePost.hasOwnProperty(i)) { if (HAS_NAME_PROPERTY_BUG) { input = document.createElement('<input name="' + i + '"/>'); } else { input = document.createElement("INPUT"); input.name = i; } input.value = config.usePost[i]; form.appendChild(input); } } } form.submit(); form.parentNode.removeChild(form); } else { frame.src = src; } config.props.src = src; return frame; } /** * Check whether a domain is allowed using an Access Control List. * The ACL can contain * and ? as wildcards, or can be regular expressions. * If regular expressions they need to begin with ^ and end with $. * @param {Array/String} acl The list of allowed domains * @param {String} domain The domain to test. * @return {Boolean} True if the domain is allowed, false if not. */ function checkAcl(acl, domain){ // normalize into an array if (typeof acl == "string") { acl = [acl]; } var re, i = acl.length; while (i--) { re = acl[i]; re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$")); if (re.test(domain)) { return true; } } return false; } /* * Functions related to stacks */ /** * Prepares an array of stack-elements suitable for the current configuration * @param {Object} config The Transports configuration. See easyXDM.Socket for more. * @return {Array} An array of stack-elements with the TransportElement at index 0. */ function prepareTransportStack(config){ var protocol = config.protocol, stackEls; config.isHost = config.isHost || undef(query.xdm_p); useHash = config.hash || false; if (!config.props) { config.props = {}; } if (!config.isHost) { config.channel = query.xdm_c.replace(/["'<>\\]/g, ""); config.secret = query.xdm_s; config.remote = query.xdm_e.replace(/["'<>\\]/g, ""); ; protocol = query.xdm_p; if (config.acl && !checkAcl(config.acl, config.remote)) { throw new Error("Access denied for " + config.remote); } } else { config.remote = resolveUrl(config.remote); config.channel = config.channel || "default" + channelId++; config.secret = Math.random().toString(16).substring(2); if (undef(protocol)) { if (getLocation(location.href) == getLocation(config.remote)) { /* * Both documents has the same origin, lets use direct access. */ protocol = "4"; } else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) { /* * This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+ */ protocol = "1"; } else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) { /* * The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS */ protocol = "6"; } else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) { /* * This is supported in Gecko (Firefox 1+) */ protocol = "5"; } else if (config.remoteHelper) { /* * This is supported in all browsers that retains the value of window.name when * navigating from one domain to another, and where parent.frames[foo] can be used * to get access to a frame from the same domain */ protocol = "2"; } else { /* * This is supported in all browsers where [window].location is writable for all * The resize event will be used if resize is supported and the iframe is not put * into a container, else polling will be used. */ protocol = "0"; } } } config.protocol = protocol; // for conditional branching switch (protocol) { case "0":// 0 = HashTransport apply(config, { interval: 100, delay: 2000, useResize: true, useParent: false, usePolling: false }, true); if (config.isHost) { if (!config.local) { // If no local is set then we need to find an image hosted on the current domain var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image; var i = images.length; while (i--) { image = images[i]; if (image.src.substring(0, domain.length) === domain) { config.local = image.src; break; } } if (!config.local) { // If no local was set, and we are unable to find a suitable file, then we resort to using the current window config.local = window; } } var parameters = { xdm_c: config.channel, xdm_p: 0 }; if (config.local === window) { // We are using the current window to listen to config.usePolling = true; config.useParent = true; config.local = location.protocol + "//" + location.host + location.pathname + location.search; parameters.xdm_e = config.local; parameters.xdm_pa = 1; // use parent } else { parameters.xdm_e = resolveUrl(config.local); } if (config.container) { config.useResize = false; parameters.xdm_po = 1; // use polling } config.remote = appendQueryParameters(config.remote, parameters); } else { apply(config, { channel: query.xdm_c, remote: query.xdm_e, useParent: !undef(query.xdm_pa), usePolling: !undef(query.xdm_po), useResize: config.useParent ? false : config.useResize }); } stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({ encode: true, maxLength: 4000 - config.remote.length }), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "1": stackEls = [new easyXDM.stack.PostMessageTransport(config)]; break; case "2": if (config.isHost) { config.remoteHelper = resolveUrl(config.remoteHelper); } stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "3": stackEls = [new easyXDM.stack.NixTransport(config)]; break; case "4": stackEls = [new easyXDM.stack.SameOriginTransport(config)]; break; case "5": stackEls = [new easyXDM.stack.FrameElementTransport(config)]; break; case "6": if (!flashVersion) { hasFlash(); } stackEls = [new easyXDM.stack.FlashTransport(config)]; break; } // this behavior is responsible for buffering outgoing messages, and for performing lazy initialization stackEls.push(new easyXDM.stack.QueueBehavior({ lazy: config.lazy, remove: true })); return stackEls; } /** * Chains all the separate stack elements into a single usable stack.<br/> * If an element is missing a necessary method then it will have a pass-through method applied. * @param {Array} stackElements An array of stack elements to be linked. * @return {easyXDM.stack.StackElement} The last element in the chain. */ function chainStack(stackElements){ var stackEl, defaults = { incoming: function(message, origin){ this.up.incoming(message, origin); }, outgoing: function(message, recipient){ this.down.outgoing(message, recipient); }, callback: function(success){ this.up.callback(success); }, init: function(){ this.down.init(); }, destroy: function(){ this.down.destroy(); } }; for (var i = 0, len = stackElements.length; i < len; i++) { stackEl = stackElements[i]; apply(stackEl, defaults, true); if (i !== 0) { stackEl.down = stackElements[i - 1]; } if (i !== len - 1) { stackEl.up = stackElements[i + 1]; } } return stackEl; } /** * This will remove a stackelement from its stack while leaving the stack functional. * @param {Object} element The elment to remove from the stack. */ function removeFromStack(element){ element.up.down = element.down; element.down.up = element.up; element.up = element.down = null; } /* * Export the main object and any other methods applicable */ /** * @class easyXDM * A javascript library providing cross-browser, cross-domain messaging/RPC. * @version 2.4.19.3 * @singleton */ apply(easyXDM, { /** * The version of the library * @type {string} */ version: "2.4.19.3", /** * This is a map containing all the query parameters passed to the document. * All the values has been decoded using decodeURIComponent. * @type {object} */ query: query, /** * @private */ stack: {}, /** * Applies properties from the source object to the target object.<br/> * @param {object} target The target of the properties. * @param {object} source The source of the properties. * @param {boolean} noOverwrite Set to True to only set non-existing properties. */ apply: apply, /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ getJSONObject: getJSON, /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {object} scope An optional scope for the function to be called with. */ whenReady: whenReady, /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ noConflict: noConflict }); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.DomHelper * Contains methods for dealing with the DOM * @singleton */ easyXDM.DomHelper = { /** * Provides a consistent interface for adding eventhandlers * @param {Object} target The target to add the event to * @param {String} type The name of the event * @param {Function} listener The listener */ on: on, /** * Provides a consistent interface for removing eventhandlers * @param {Object} target The target to remove the event from * @param {String} type The name of the event * @param {Function} listener The listener */ un: un, /** * Checks for the presence of the JSON object. * If it is not present it will use the supplied path to load the JSON2 library. * This should be called in the documents head right after the easyXDM script tag. * http://json.org/json2.js * @param {String} path A valid path to json2.js */ requiresJSON: function(path){ if (!isHostObject(window, "JSON")) { // we need to encode the < in order to avoid an illegal token error // when the script is inlined in a document. document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>'); } } }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // (function(){ // The map containing the stored functions var _map = {}; /** * @class easyXDM.Fn * This contains methods related to function handling, such as storing callbacks. * @singleton * @namespace easyXDM */ easyXDM.Fn = { /** * Stores a function using the given name for reference * @param {String} name The name that the function should be referred by * @param {Function} fn The function to store * @namespace easyXDM.fn */ set: function(name, fn){ _map[name] = fn; }, /** * Retrieves the function referred to by the given name * @param {String} name The name of the function to retrieve * @param {Boolean} del If the function should be deleted after retrieval * @return {Function} The stored function * @namespace easyXDM.fn */ get: function(name, del){ if (!_map.hasOwnProperty(name)) { return; } var fn = _map[name]; if (del) { delete _map[name]; } return fn; } }; }()); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.Socket * This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/> * The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/> * Internally different stacks will be used depending on the browsers features and the available parameters. * <h2>How to set up</h2> * Setting up the provider: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; local: "name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * Setting up the consumer: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; remote: "http:&#47;&#47;remotedomain/page.html", * &nbsp; remoteHelper: "http:&#47;&#47;remotedomain/name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property * and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports. * @namespace easyXDM * @constructor * @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window. * @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed. * @cfg {String} remote (Consumer only) The url to the providers document. * @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000. * @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300. * @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional. * @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional. * @cfg {Function} onReady A method that should be called when the transport is ready. Optional. * @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional. * @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/> * This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $. * If none of the patterns match an Error will be thrown. * @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>. * Properties such as 'name' and 'src' will be overrided. Optional. */ easyXDM.Socket = function(config){ // create the stack var stack = chainStack(prepareTransportStack(config).concat([{ incoming: function(message, origin){ config.onMessage(message, origin); }, callback: function(success){ if (config.onReady) { config.onReady(success); } } }])), recipient = getLocation(config.remote); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; /** * Posts a message to the remote end of the channel * @param {String} message The message to send */ this.postMessage = function(message){ stack.outgoing(message, recipient); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.Rpc * Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation * of methods to be called from the remote end.<br/> * The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/> * This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods. * <h2>How to set up</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; &#47;&#47; this configuration is equal to that used by the Socket. * &nbsp; remote: "http:&#47;&#47;remotedomain/...", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the proxy * &nbsp; &nbsp; rpc.foo(... * &nbsp; } * },{ * &nbsp; local: {..}, * &nbsp; remote: {..} * }); * </code></pre> * * <h2>Exposing functions (procedures)</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: { * &nbsp; &nbsp; nameOfMethod: { * &nbsp; &nbsp; &nbsp; method: function(arg1, arg2, success, error){ * &nbsp; &nbsp; &nbsp; &nbsp; ... * &nbsp; &nbsp; &nbsp; } * &nbsp; &nbsp; }, * &nbsp; &nbsp; &#47;&#47; with shorthand notation * &nbsp; &nbsp; nameOfAnotherMethod: function(arg1, arg2, success, error){ * &nbsp; &nbsp; } * &nbsp; }, * &nbsp; remote: {...} * }); * </code></pre> * The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/> * To send a successfull result back you can use * <pre><code> * return foo; * </pre></code> * or * <pre><code> * success(foo); * </pre></code> * To return an error you can use * <pre><code> * throw new Error("foo error"); * </code></pre> * or * <pre><code> * error("foo error"); * </code></pre> * * <h2>Defining remotely exposed methods (procedures/notifications)</h2> * The definition of the remote end is quite similar: * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: { * &nbsp; &nbsp; nameOfMethod: {} * &nbsp; } * }); * </code></pre> * To call a remote method use * <pre><code> * rpc.nameOfMethod("arg1", "arg2", function(value) { * &nbsp; alert("success: " + value); * }, function(message) { * &nbsp; alert("error: " + message + ); * }); * </code></pre> * Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/> * When called with no callback a JSON-RPC 2.0 notification will be executed. * Be aware that you will not be notified of any errors with this method. * <br/> * <h2>Specifying a custom serializer</h2> * If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library * then you can specify a custom serializer using <code>serializer: foo</code> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: {...}, * &nbsp; serializer : { * &nbsp; &nbsp; parse: function(string){ ... }, * &nbsp; &nbsp; stringify: function(object) {...} * &nbsp; } * }); * </code></pre> * If <code>serializer</code> is set then the class will not attempt to use the native implementation. * @namespace easyXDM * @constructor * @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters. * @param {Object} jsonRpcConfig The description of the interface to implement. */ easyXDM.Rpc = function(config, jsonRpcConfig){ // expand shorthand notation if (jsonRpcConfig.local) { for (var method in jsonRpcConfig.local) { if (jsonRpcConfig.local.hasOwnProperty(method)) { var member = jsonRpcConfig.local[method]; if (typeof member === "function") { jsonRpcConfig.local[method] = { method: member }; } } } } // create the stack var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), { callback: function(success){ if (config.onReady) { config.onReady(success); } } }])); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.SameOriginTransport * SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/> * This can be useful for testing and for when the main application supports both internal and external sources. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.SameOriginTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send(message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: location.protocol + "//" + location.host + location.pathname, xdm_c: config.channel, xdm_p: 4 // 4 = SameOriginTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); easyXDM.Fn.set(config.channel, function(sendFn){ send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); return function(msg){ pub.up.incoming(msg, targetOrigin); }; }); } else { send = getParentObject().Fn.get(config.channel, true)(function(msg){ pub.up.incoming(msg, targetOrigin); }); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.FlashTransport * FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. * @cfg {String} secret the pre-shared secret used to secure the communication. * @cfg {String} swf The path to the swf file * @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden. * @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed */ easyXDM.stack.FlashTransport = function(config){ var pub, // the public interface frame, send, targetOrigin, swf, swfContainer; function onMessage(message, origin){ setTimeout(function(){ pub.up.incoming(message, targetOrigin); }, 0); } /** * This method adds the SWF to the DOM and prepares the initialization of the channel */ function addSwf(domain){ // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error. var url = config.swf + "?host=" + config.isHost; var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000); // prepare the init function that will fire once the swf is ready easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){ easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild; var queue = easyXDM.stack.FlashTransport[domain].queue; for (var i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; }); if (config.swfContainer) { swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer; } else { // create the container that will hold the swf swfContainer = document.createElement('div'); // http://bugs.adobe.com/jira/browse/FP-4796 // http://tech.groups.yahoo.com/group/flexcoders/message/162365 // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? { height: "20px", width: "20px", position: "fixed", right: 0, top: 0 } : { height: "1px", width: "1px", position: "absolute", overflow: "hidden", right: 0, top: 0 }); document.body.appendChild(swfContainer); } // create the object/embed var flashVars = "callback=flash_loaded" + encodeURIComponent(domain.replace(/[\-.]/g, "_")) + "&proto=" + global.location.protocol + "&domain=" + encodeURIComponent(getDomainName(global.location.href)) + "&port=" + encodeURIComponent(getPort(global.location.href)) + "&ns=" + encodeURIComponent(namespace); swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" + "<param name='allowScriptAccess' value='always'></param>" + "<param name='wmode' value='transparent'>" + "<param name='movie' value='" + url + "'></param>" + "<param name='flashvars' value='" + flashVars + "'></param>" + "<embed type='application/x-shockwave-flash' FlashVars='" + flashVars + "' allowScriptAccess='always' wmode='transparent' src='" + url + "' height='1' width='1'></embed>" + "</object>"; } return (pub = { outgoing: function(message, domain, fn){ swf.postMessage(config.channel, message.toString()); if (fn) { fn(); } }, destroy: function(){ try { swf.destroyChannel(config.channel); } catch (e) { } swf = null; if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = config.remote; // Prepare the code that will be run after the swf has been intialized easyXDM.Fn.set("flash_" + config.channel + "_init", function(){ setTimeout(function(){ pub.up.callback(true); }); }); // set up the omMessage handler easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage); config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths var swfdomain = getDomainName(config.swf); var fn = function(){ // set init to true in case the fn was called was invoked from a separate instance easyXDM.stack.FlashTransport[swfdomain].init = true; swf = easyXDM.stack.FlashTransport[swfdomain].swf; // create the channel swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost); if (config.isHost) { // if Flash is going to be throttled and we want to avoid this if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) { apply(config.props, { position: "fixed", right: 0, top: 0, height: "20px", width: "20px" }); } // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 6, // 6 = FlashTransport xdm_s: config.secret }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } }; if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) { // if the swf is in place and we are the consumer fn(); } else { // if the swf does not yet exist if (!easyXDM.stack.FlashTransport[swfdomain]) { // add the queue to hold the init fn's easyXDM.stack.FlashTransport[swfdomain] = { queue: [fn] }; addSwf(swfdomain); } else { easyXDM.stack.FlashTransport[swfdomain].queue.push(fn); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.PostMessageTransport * PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/> * <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. */ easyXDM.stack.PostMessageTransport = function(config){ var pub, // the public interface frame, // the remote frame, if any callerWindow, // the window that we will call with targetOrigin; // the domain to communicate with /** * Resolves the origin from the event object * @private * @param {Object} event The messageevent * @return {String} The scheme, host and port of the origin */ function _getOrigin(event){ if (event.origin) { // This is the HTML5 property return getLocation(event.origin); } if (event.uri) { // From earlier implementations return getLocation(event.uri); } if (event.domain) { // This is the last option and will fail if the // origin is not using the same schema as we are return location.protocol + "//" + event.domain; } throw "Unable to retrieve the origin of the event"; } /** * This is the main implementation for the onMessage event.<br/> * It checks the validity of the origin and passes the message on if appropriate. * @private * @param {Object} event The messageevent */ function _window_onMessage(event){ var origin = _getOrigin(event); if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") { pub.up.incoming(event.data.substring(config.channel.length + 1), origin); } } return (pub = { outgoing: function(message, domain, fn){ callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin); if (fn) { fn(); } }, destroy: function(){ un(window, "message", _window_onMessage); if (frame) { callerWindow = null; frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // add the event handler for listening var waitForReady = function(event){ if (event.data == config.channel + "-ready") { // replace the eventlistener callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document; un(window, "message", waitForReady); on(window, "message", _window_onMessage); setTimeout(function(){ pub.up.callback(true); }, 0); } }; on(window, "message", waitForReady); // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 1 // 1 = PostMessage }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } else { // add the event handler for listening on(window, "message", _window_onMessage); callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document; callerWindow.postMessage(config.channel + "-ready", targetOrigin); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.FrameElementTransport * FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/> * Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.FrameElementTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send.call(this, message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 5 // 5 = FrameElementTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); frame.fn = function(sendFn){ delete frame.fn; send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); // remove the function so that it cannot be used to overwrite the send function later on return function(msg){ pub.up.incoming(msg, targetOrigin); }; }; } else { // This is to mitigate origin-spoofing if (document.referrer && getLocation(document.referrer) != query.xdm_e) { window.top.location = query.xdm_e; } send = window.frameElement.fn(function(msg){ pub.up.incoming(msg, targetOrigin); }); pub.up.callback(true); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.NameTransport * NameTransport uses the window.name property to relay data. * The <code>local</code> parameter needs to be set on both the consumer and provider,<br/> * and the <code>remoteHelper</code> parameter needs to be set on the consumer. * @constructor * @param {Object} config The transports configuration. * @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host. * @namespace easyXDM.stack */ easyXDM.stack.NameTransport = function(config){ var pub; // the public interface var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl; function _sendMessage(message){ var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel; callerWindow.contentWindow.sendMessage(message, url); } function _onReady(){ if (isHost) { if (++readyCount === 2 || !isHost) { pub.up.callback(true); } } else { _sendMessage("ready"); pub.up.callback(true); } } function _onMessage(message){ pub.up.incoming(message, remoteOrigin); } function _onLoad(){ if (callback) { setTimeout(function(){ callback(true); }, 0); } } return (pub = { outgoing: function(message, domain, fn){ callback = fn; _sendMessage(message); }, destroy: function(){ callerWindow.parentNode.removeChild(callerWindow); callerWindow = null; if (isHost) { remoteWindow.parentNode.removeChild(remoteWindow); remoteWindow = null; } }, onDOMReady: function(){ isHost = config.isHost; readyCount = 0; remoteOrigin = getLocation(config.remote); config.local = resolveUrl(config.local); if (isHost) { // Register the callback easyXDM.Fn.set(config.channel, function(message){ if (isHost && message === "ready") { // Replace the handler easyXDM.Fn.set(config.channel, _onMessage); _onReady(); } }); // Set up the frame that points to the remote instance remoteUrl = appendQueryParameters(config.remote, { xdm_e: config.local, xdm_c: config.channel, xdm_p: 2 }); apply(config.props, { src: remoteUrl + '#' + config.channel, name: IFRAME_PREFIX + config.channel + "_provider" }); remoteWindow = createFrame(config); } else { config.remoteHelper = config.remote; easyXDM.Fn.set(config.channel, _onMessage); } // Set up the iframe that will be used for the transport var onLoad = function(){ // Remove the handler var w = callerWindow || this; un(w, "load", onLoad); easyXDM.Fn.set(config.channel + "_load", _onLoad); (function test(){ if (typeof w.contentWindow.sendMessage == "function") { _onReady(); } else { setTimeout(test, 50); } }()); }; callerWindow = createFrame({ props: { src: config.local + "#_4" + config.channel }, onLoad: onLoad }); }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.HashTransport * HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String/Window} local The url to the local file used for proxying messages, or the local window. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. * @cfg {Number} interval The interval used when polling for messages. */ easyXDM.stack.HashTransport = function(config){ var pub; var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow; var useParent, _remoteOrigin; function _sendMessage(message){ if (!_callerWindow) { return; } var url = config.remote + "#" + (_msgNr++) + "_" + message; ((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url; } function _handleHash(hash){ _lastMsg = hash; pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin); } /** * Checks location.hash for a new message and relays this to the receiver. * @private */ function _pollHash(){ if (!_listenerWindow) { return; } var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#"); if (indexOf != -1) { hash = href.substring(indexOf); } if (hash && hash != _lastMsg) { _handleHash(hash); } } function _attachListeners(){ _timer = setInterval(_pollHash, pollInterval); } return (pub = { outgoing: function(message, domain){ _sendMessage(message); }, destroy: function(){ window.clearInterval(_timer); if (isHost || !useParent) { _callerWindow.parentNode.removeChild(_callerWindow); } _callerWindow = null; }, onDOMReady: function(){ isHost = config.isHost; pollInterval = config.interval; _lastMsg = "#" + config.channel; _msgNr = 0; useParent = config.useParent; _remoteOrigin = getLocation(config.remote); if (isHost) { apply(config.props, { src: config.remote, name: IFRAME_PREFIX + config.channel + "_provider" }); if (useParent) { config.onLoad = function(){ _listenerWindow = window; _attachListeners(); pub.up.callback(true); }; } else { var tries = 0, max = config.delay / 50; (function getRef(){ if (++tries > max) { throw new Error("Unable to reference listenerwindow"); } try { _listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"]; } catch (ex) { } if (_listenerWindow) { _attachListeners(); pub.up.callback(true); } else { setTimeout(getRef, 50); } }()); } _callerWindow = createFrame(config); } else { _listenerWindow = window; _attachListeners(); if (useParent) { _callerWindow = parent; pub.up.callback(true); } else { apply(config, { props: { src: config.remote + "#" + config.channel + new Date(), name: IFRAME_PREFIX + config.channel + "_consumer" }, onLoad: function(){ pub.up.callback(true); } }); _callerWindow = createFrame(config); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.ReliableBehavior * This is a behavior that tries to make the underlying transport reliable by using acknowledgements. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. */ easyXDM.stack.ReliableBehavior = function(config){ var pub, // the public interface callback; // the callback to execute when we have a confirmed success/failure var idOut = 0, idIn = 0, currentMessage = ""; return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(","); message = message.substring(indexOf + 1); if (ack[0] == idOut) { currentMessage = ""; if (callback) { callback(true); } } if (message.length > 0) { pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin); if (idIn != ack[1]) { idIn = ack[1]; pub.up.incoming(message, origin); } } }, outgoing: function(message, origin, fn){ currentMessage = message; callback = fn; pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.QueueBehavior * This is a behavior that enables queueing of messages. <br/> * It will buffer incoming messages and dispach these as fast as the underlying transport allows. * This will also fragment/defragment messages so that the outgoing message is never bigger than the * set length. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. Optional. * @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation. */ easyXDM.stack.QueueBehavior = function(config){ var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false; function dispatch(){ if (config.remove && queue.length === 0) { removeFromStack(pub); return; } if (waiting || queue.length === 0 || destroying) { return; } waiting = true; var message = queue.shift(); pub.down.outgoing(message.data, message.origin, function(success){ waiting = false; if (message.callback) { setTimeout(function(){ message.callback(success); }, 0); } dispatch(); }); } return (pub = { init: function(){ if (undef(config)) { config = {}; } if (config.maxLength) { maxLength = config.maxLength; doFragment = true; } if (config.lazy) { lazy = true; } else { pub.down.init(); } }, callback: function(success){ waiting = false; var up = pub.up; // in case dispatch calls removeFromStack dispatch(); up.callback(success); }, incoming: function(message, origin){ if (doFragment) { var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10); incoming += message.substring(indexOf + 1); if (seq === 0) { if (config.encode) { incoming = decodeURIComponent(incoming); } pub.up.incoming(incoming, origin); incoming = ""; } } else { pub.up.incoming(message, origin); } }, outgoing: function(message, origin, fn){ if (config.encode) { message = encodeURIComponent(message); } var fragments = [], fragment; if (doFragment) { // fragment into chunks while (message.length !== 0) { fragment = message.substring(0, maxLength); message = message.substring(fragment.length); fragments.push(fragment); } // enqueue the chunks while ((fragment = fragments.shift())) { queue.push({ data: fragments.length + "_" + fragment, origin: origin, callback: fragments.length === 0 ? fn : null }); } } else { queue.push({ data: message, origin: origin, callback: fn }); } if (lazy) { pub.down.init(); } else { dispatch(); } }, destroy: function(){ destroying = true; pub.down.destroy(); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.VerifyBehavior * This behavior will verify that communication with the remote end is possible, and will also sign all outgoing, * and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. * @cfg {Boolean} initiate If the verification should be initiated from this end. */ easyXDM.stack.VerifyBehavior = function(config){ var pub, mySecret, theirSecret, verified = false; function startVerification(){ mySecret = Math.random().toString(16).substring(2); pub.down.outgoing(mySecret); } return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"); if (indexOf === -1) { if (message === mySecret) { pub.up.callback(true); } else if (!theirSecret) { theirSecret = message; if (!config.initiate) { startVerification(); } pub.down.outgoing(message); } } else { if (message.substring(0, indexOf) === theirSecret) { pub.up.incoming(message.substring(indexOf + 1), origin); } } }, outgoing: function(message, origin, fn){ pub.down.outgoing(mySecret + "_" + message, origin, fn); }, callback: function(success){ if (config.initiate) { startVerification(); } } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.RpcBehavior * This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/> * Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything. * @namespace easyXDM.stack * @constructor * @param {Object} proxy The object to apply the methods to. * @param {Object} config The definition of the local and remote interface to implement. * @cfg {Object} local The local interface to expose. * @cfg {Object} remote The remote methods to expose through the proxy. * @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON. */ easyXDM.stack.RpcBehavior = function(proxy, config){ var pub, serializer = config.serializer || getJSON(); var _callbackCounter = 0, _callbacks = {}; /** * Serializes and sends the message * @private * @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added. */ function _send(data){ data.jsonrpc = "2.0"; pub.down.outgoing(serializer.stringify(data)); } /** * Creates a method that implements the given definition * @private * @param {Object} The method configuration * @param {String} method The name of the method * @return {Function} A stub capable of proxying the requested method call */ function _createMethod(definition, method){ var slice = Array.prototype.slice; return function(){ var l = arguments.length, callback, message = { method: method }; if (l > 0 && typeof arguments[l - 1] === "function") { //with callback, procedure if (l > 1 && typeof arguments[l - 2] === "function") { // two callbacks, success and error callback = { success: arguments[l - 2], error: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 2); } else { // single callback, success callback = { success: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 1); } _callbacks["" + (++_callbackCounter)] = callback; message.id = _callbackCounter; } else { // no callbacks, a notification message.params = slice.call(arguments, 0); } if (definition.namedParams && message.params.length === 1) { message.params = message.params[0]; } // Send the method request _send(message); }; } /** * Executes the exposed method * @private * @param {String} method The name of the method * @param {Number} id The callback id to use * @param {Function} method The exposed implementation * @param {Array} params The parameters supplied by the remote end */ function _executeMethod(method, id, fn, params){ if (!fn) { if (id) { _send({ id: id, error: { code: -32601, message: "Procedure not found." } }); } return; } var success, error; if (id) { success = function(result){ success = emptyFn; _send({ id: id, result: result }); }; error = function(message, data){ error = emptyFn; var msg = { id: id, error: { code: -32099, message: message } }; if (data) { msg.error.data = data; } _send(msg); }; } else { success = error = emptyFn; } // Call local method if (!isArray(params)) { params = [params]; } try { var result = fn.method.apply(fn.scope, params.concat([success, error])); if (!undef(result)) { success(result); } } catch (ex1) { error(ex1.message); } } return (pub = { incoming: function(message, origin){ var data = serializer.parse(message); if (data.method) { // A method call from the remote end if (config.handle) { config.handle(data, _send); } else { _executeMethod(data.method, data.id, config.local[data.method], data.params); } } else { // A method response from the other end var callback = _callbacks[data.id]; if (data.error) { if (callback.error) { callback.error(data.error); } } else if (callback.success) { callback.success(data.result); } delete _callbacks[data.id]; } }, init: function(){ if (config.remote) { // Implement the remote sides exposed methods for (var method in config.remote) { if (config.remote.hasOwnProperty(method)) { proxy[method] = _createMethod(config.remote[method], method); } } } pub.down.init(); }, destroy: function(){ for (var method in config.remote) { if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) { delete proxy[method]; } } pub.down.destroy(); } }); }; global.easyXDM = easyXDM; })(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent); /*! * F2 v1.4.3 01-31-2018 * Copyright (c) 2014 Markit On Demand, Inc. http://www.openf2.org * * "F2" is 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. * * Please note that F2 ("Software") may contain third party material that Markit * On Demand Inc. has a license to use and include within the Software (the * "Third Party Material"). A list of the software comprising the Third Party Material * and the terms and conditions under which such Third Party Material is distributed * are reproduced in the ThirdPartyMaterial.md file available at: * * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md * * The inclusion of the Third Party Material in the Software does not grant, provide * nor result in you having acquiring any rights whatsoever, other than as stipulated * in the terms and conditions related to the specific Third Party Material, if any. * */ var F2; /** * Open F2 * @module f2 * @main f2 */ F2 = (function() { /** * Abosolutizes a relative URL * @method _absolutizeURI * @private * @param {e.g., location.href} base * @param {URL to absolutize} href * @returns {string} URL * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _absolutizeURI = function(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = _parseURI(href || ''); base = _parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; }; /** * Parses URI * @method _parseURI * @private * @param {The URL to parse} url * @returns {Parsed URL} string * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _parseURI = function(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); }; return { /** * A function to pass into F2.stringify which will prevent circular * reference errors when serializing objects * @method appConfigReplacer */ appConfigReplacer: function(key, value) { if (key == 'root' || key == 'ui' || key == 'height') { return undefined; } else { return value; } }, /** * The apps namespace is a place for app developers to put the javascript * class that is used to initialize their app. The javascript classes should * be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId. * It is recommended that the code be placed in a closure to help keep the * global namespace clean. * * If the class has an 'init' function, that function will be called * automatically by F2. * @property Apps * @type object * @example * F2.Apps["com_example_helloworld"] = (function() { * var App_Class = function(appConfig, appContent, root) { * this._app = appConfig; // the F2.AppConfig object * this._appContent = appContent // the F2.AppManifest.AppContent object * this.$root = $(root); // the root DOM Element that contains this app * } * * App_Class.prototype.init = function() { * // perform init actions * } * * return App_Class; * })(); * @example * F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) { * return { * init:function() { * // perform init actions * } * }; * }; * @for F2 */ Apps: {}, /** * Creates a namespace on F2 and copies the contents of an object into * that namespace optionally overwriting existing properties. * @method extend * @param {string} ns The namespace to create. Pass a falsy value to * add properties to the F2 namespace directly. * @param {object} obj The object to copy into the namespace. * @param {bool} overwrite True if object properties should be overwritten * @return {object} The created object */ extend: function (ns, obj, overwrite) { var isFunc = typeof obj === 'function'; var parts = ns ? ns.split('.') : []; var parent = this; obj = obj || {}; // ignore leading global if (parts[0] === 'F2') { parts = parts.slice(1); } // create namespaces for (var i = 0, len = parts.length; i < len; i++) { if (!parent[parts[i]]) { parent[parts[i]] = isFunc && i + 1 == len ? obj : {}; } parent = parent[parts[i]]; } // copy object into namespace if (!isFunc) { for (var prop in obj) { if (typeof parent[prop] === 'undefined' || overwrite) { parent[prop] = obj[prop]; } } } return parent; }, /** * Generates a somewhat random id * @method guid * @return {string} A random id * @for F2 */ guid: function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }, /** * Search for a value within an array. * @method inArray * @param {object} value The value to search for * @param {Array} array The array to search * @return {bool} True if the item is in the array */ inArray: function(value, array) { return jQuery.inArray(value, array) > -1; }, /** * Tests a URL to see if it's on the same domain (local) or not * @method isLocalRequest * @param {URL to test} url * @returns {bool} Whether the URL is local or not * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js */ isLocalRequest: function(url){ var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, urlLower = url.toLowerCase(), parts = rurl.exec( urlLower ), ajaxLocation, ajaxLocParts; try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement('a'); ajaxLocation.href = ''; ajaxLocation = ajaxLocation.href; } ajaxLocation = ajaxLocation.toLowerCase(); // uh oh, the url must be relative // make it fully qualified and re-regex url if (!parts){ urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); parts = rurl.exec( urlLower ); } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation ) || []; // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) var matched = !(parts && (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); return matched; }, /** * Utility method to determine whether or not the argument passed in is or is not a native dom node. * @method isNativeDOMNode * @param {object} testObject The object you want to check as native dom node. * @return {bool} Returns true if the object passed is a native dom node. */ isNativeDOMNode: function(testObject) { var bIsNode = ( typeof Node === 'object' ? testObject instanceof Node : testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' ); var bIsElement = ( typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' ); return (bIsNode || bIsElement); }, /** * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). * @method log * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). * @param {object} [obj2]* An object to be logged * @example //Pass any object (string, int, array, object, bool) to .log() F2.log('foo'); F2.log(myArray); //Use a console method name as the first argument. F2.log('error', err); F2.log('info', 'The session ID is ' + sessionId); * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) */ log: function() { var _log; var _logMethod = 'log'; var method; var noop = function () { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); var args; while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } //if first arg is a console function, use it. //defaults to console.log() if (arguments && arguments.length > 1 && arguments[0] == method){ _logMethod = method; //remove console func from args args = Array.prototype.slice.call(arguments, 1); } } if (Function.prototype.bind) { _log = Function.prototype.bind.call(console[_logMethod], console); } else { _log = function() { Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); }; } _log.apply(this, (args || arguments)); }, /** * Wrapper to convert a JSON string to an object * @method parse * @param {string} str The JSON string to convert * @return {object} The parsed object */ parse: function(str) { return JSON.parse(str); }, /** * Wrapper to convert an object to JSON * * **Note: When using F2.stringify on an F2.AppConfig object, it is * recommended to pass F2.appConfigReplacer as the replacer function in * order to prevent circular serialization errors.** * @method stringify * @param {object} value The object to convert * @param {function|Array} replacer An optional parameter that determines * how object values are stringified for objects. It can be a function or an * array of strings. * @param {int|string} space An optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will be * packed without extra whitespace. If it is a number, it will specify the * number of spaces to indent at each level. If it is a string (such as '\t' * or '&nbsp;'), it contains the characters used to indent at each level. * @return {string} The JSON string */ stringify: function(value, replacer, space) { return JSON.stringify(value, replacer, space); }, /** * Function to get the F2 version number * @method version * @return {string} F2 version number */ version: function() { return '1.4.3'; } }; })(); /** * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. * *<p class="alert alert-block alert-warning"> *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated&mdash;but not removed&mdash;in version 1.2. They will be permanently removed in a future version of F2. *</p> * *<p class="alert alert-block alert-info"> *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. *</p> * * ### Order of Execution * * **App Rendering** * * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. * * * **App Removal** * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. * * **Error Handling** * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. * * @class F2.AppHandlers */ F2.extend('AppHandlers', (function() { // the hidden token that we will check against every time someone tries to add, remove, fire handler var _ct = F2.guid(); var _f2t = F2.guid(); var _handlerCollection = { appManifestRequestFail: [], appCreateRoot: [], appRenderBefore: [], appDestroyBefore: [], appRenderAfter: [], appDestroyAfter: [], appRender: [], appDestroy: [], appScriptLoadFailed: [] }; var _defaultMethods = { appRender: function(appConfig, appHtml) { var $root = null; // if no app root is defined use the app's outer most node if(!F2.isNativeDOMNode(appConfig.root)) { appConfig.root = jQuery(appHtml).get(0); // get a handle on the root in jQuery $root = jQuery(appConfig.root); } else { // get a handle on the root in jQuery $root = jQuery(appConfig.root); // append the app html to the root $root.append(appHtml); } // append the root to the body by default. jQuery('body').append($root); }, appDestroy: function(appInstance) { // call the apps destroy method, if it has one if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') { appInstance.app.destroy(); } // warn the Container and App Developer that even though they have a destroy method it hasn't been else if(appInstance && appInstance.app && appInstance.app.destroy) { F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); } // fade out and remove the root jQuery(appInstance.config.root).fadeOut(500, function() { jQuery(this).remove(); }); } }; var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) { // will throw an exception and stop execution if the token is invalid _validateToken(token); // create handler structure. Not all arguments properties will be populated/used. var handler = { func: (typeof(func_or_element)) ? func_or_element : null, namespace: sNamespace, domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null }; if(!handler.func && !handler.domNode) { throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); } if(handler.domNode && !bDomNodeAppropriate) { throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); } return handler; }; var _validateToken = function(sToken) { // check token against F2 and container if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } }; var _removeHandler = function(sToken, eventKey, sNamespace) { // will throw an exception and stop execution if the token is invalid _validateToken(sToken); if(!sNamespace && !eventKey) { return; } // remove by event key else if(!sNamespace && eventKey) { _handlerCollection[eventKey] = []; } // remove by namespace only else if(sNamespace && !eventKey) { sNamespace = sNamespace.toLowerCase(); for(var currentEventKey in _handlerCollection) { var eventCollection = _handlerCollection[currentEventKey]; var newEvents = []; for(var i = 0, ec = eventCollection.length; i < ec; i++) { var currentEventHandler = eventCollection[i]; if(currentEventHandler) { if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) { newEvents.push(currentEventHandler); } } } eventCollection = newEvents; } } else if(sNamespace && _handlerCollection[eventKey]) { sNamespace = sNamespace.toLowerCase(); var newHandlerCollection = []; for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) { var currentHandler = _handlerCollection[eventKey][iCounter]; if(currentHandler) { if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) { newHandlerCollection.push(currentHandler); } } } _handlerCollection[eventKey] = newHandlerCollection; } }; return { /** * Allows Container Developer to retrieve a unique token which must be passed to * all `on` and `off` methods. This function will self destruct and can only be called * one time. Container Developers must store the return value inside of a closure. * @method getToken **/ getToken: function() { // delete this method for security that way only the container has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.getToken; // return the token, which we validate against. return _ct; }, /** * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} * and additional internal methods. * @method __f2GetToken * @private **/ __f2GetToken: function() { // delete this method for security that way only the F2 internally has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.__f2GetToken; // return the token, which we validate against. return _f2t; }, /** * Allows F2 to trigger specific events internally. * @method __trigger * @private * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. **/ __trigger: function(token, eventKey) // additional arguments will likely be passed { // will throw an exception and stop execution if the token is invalid if(token != _f2t) { throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); } if(_handlerCollection && _handlerCollection[eventKey]) { // create a collection of arguments that are safe to pass to the callback. var passableArgs = []; // populate that collection with all arguments except token and eventKey for(var i = 2, j = arguments.length; i < j; i++) { passableArgs.push(arguments[i]); } if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) { _defaultMethods[eventKey].apply(F2, passableArgs); return this; } else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) { return this; } // fire all event listeners in the order that they were added. for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) { var handler = _handlerCollection[eventKey][iCounter]; // appRender where root is already defined if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) { var $appRoot = jQuery(arguments[2].root).append(arguments[3]); jQuery(handler.domNode).append($appRoot); } else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) { // set the root to the actual HTML of the app arguments[2].root = jQuery(arguments[3]).get(0); // appends the root to the dom node specified jQuery(handler.domNode).append(arguments[2].root); } else { handler.func.apply(F2, passableArgs); } } } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {HTMLElement} element Specific DOM element to which app gets appended. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRender', * document.getElementById('my_app') * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRender.myNamespace', * document.getElementById('my_app') * ); **/ /** * Allows Container Developer to add listener method that will be triggered when a specific event occurs. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRenderBefore' * function() { F2.log('before app rendered!'); } * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRenderBefore.myNamespace', * function() { F2.log('before app rendered!'); } * ); **/ on: function(token, eventKey, func_or_element) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _handlerCollection[eventKey].push( _createHandler( token, sNamespace, func_or_element, (eventKey == 'appRender') ) ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to remove listener methods for specific events * @method off * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all * listeners for the specified event type will be removed. * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.off(_token,'appRenderBefore'); * **/ off: function(token, eventKey) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _removeHandler( token, eventKey, sNamespace ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; } }; })()); F2.extend('Constants', { /** * A convenient collection of all available appHandler events. * @class F2.Constants.AppHandlers **/ AppHandlers: (function() { return { /** * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_MANIFEST_REQUEST_FAIL * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_MANIFEST_REQUEST_FAIL, * function(appConfig) * { * You can use information from the appConfig to surface a custom error message in the dom * Or display some kind of default error placeholder element rather than having a blank spot in the dom * } * ); */ APP_MANIFEST_REQUEST_FAIL: 'appManifestRequestFail', /** * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_CREATE_ROOT * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_CREATE_ROOT, * function(appConfig) * { * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER * appConfig.root = jQuery('<section></section>').get(0); * } * ); */ APP_CREATE_ROOT: 'appCreateRoot', /** * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_BEFORE, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_BEFORE: 'appRenderBefore', /** * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) * @property APP_RENDER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER, * function(appConfig, appHtml) * { * var $root = null; * * // if no app root is defined use the app's outer most node * if(!F2.isNativeDOMNode(appConfig.root)) * { * appConfig.root = jQuery(appHtml).get(0); * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * } * else * { * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * * // append the app html to the root * $root.append(appHtml); * } * * // append the root to the body by default. * jQuery('body').append($root); * } * ); */ APP_RENDER: 'appRender', /** * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_AFTER, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_AFTER: 'appRenderAfter', /** * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_BEFORE: 'appDestroyBefore', /** * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY, * function(appInstance) * { * // call the apps destroy method, if it has one * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') * { * appInstance.app.destroy(); * } * else if(appInstance && appInstance.app && appInstance.app.destroy) * { * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); * } * * // fade out and remove the root * jQuery(appInstance.config.root).fadeOut(500, function() { * jQuery(this).remove(); * }); * } * ); */ APP_DESTROY: 'appDestroy', /** * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_AFTER, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_AFTER: 'appDestroyAfter', /** * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) * @property APP_SCRIPT_LOAD_FAILED * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, * function(appConfig, scriptInfo) * { * F2.log(appConfig.appId); * } * ); */ APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' }; })() }); /** * Class stubs for documentation purposes * @main F2 */ F2.extend('', { /** * The App Class is an optional class that can be namespaced onto the * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The * [F2 Docs](../../app-development.html#app-class) * has more information on the usage of the App Class. * @class F2.App * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent * object * @param {Element} root The root DOM Element for the app */ App: function(appConfig, appContent, root) { return { /** * An optional init function that will automatically be called when * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. * @method init * @optional */ init:function() {} }; }, /** * The AppConfig object represents an app's meta data * @class F2.AppConfig */ AppConfig: { /** * The unique ID of the app. More information can be found * [here](../../app-development.html#f2-appid) * @property appId * @type string * @required */ appId: '', /** * An object that represents the context of an app * @property context * @type object */ context: {}, /** * True if the app should be requested in a single request with other apps. * @property enableBatchRequests * @type bool * @default false */ enableBatchRequests: false, /** * The height of the app. The initial height will be pulled from * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later * modified by calling * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used * for secure apps to be able to set the initial height of the iframe. * @property height * @type int */ height: 0, /** * The unique runtime ID of the app. * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property instanceId * @type string */ instanceId: '', /** * True if the app will be loaded in an iframe. This property * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object * sets isSecure = true. It will also be true if the * [container](../../container-development.html) has made the decision to * run apps in iframes. * @property isSecure * @type bool * @default false */ isSecure: false, /** * The language and region specification for this container * represented as an IETF-defined standard language tag, * e.g. `"en-us"` or `"de-de"`. This is passed during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process. * * @property containerLocale * @type string * @default null * @since 1.4.0 */ containerLocale: null, /** * The languages and regions supported by this app represented * as an array of IETF-defined standard language tags, * e.g. `["en-us","de-de"]`. * * @property localeSupport * @type array * @default [] * @since 1.4.0 */ localeSupport: [], /** * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} * object. * @property manifestUrl * @type string * @required */ manifestUrl: '', /** * The recommended maximum width in pixels that this app should be run. * **It is up to the [container](../../container-development.html) to * implement the logic to prevent an app from being run when the maxWidth * requirements are not met.** * @property maxWidth * @type int */ maxWidth: 0, /** * The recommended minimum grid size that this app should be run. This * value corresponds to the 12-grid system that is used by the * [container](../../container-development.html). This property should be * set by apps that require a certain number of columns in their layout. * @property minGridSize * @type int * @default 4 */ minGridSize: 4, /** * The recommended minimum width in pixels that this app should be run. **It * is up to the [container](../../container-development.html) to implement * the logic to prevent an app from being run when the minWidth requirements * are not met. * @property minWidth * @type int * @default 300 */ minWidth: 300, /** * The name of the app * @property name * @type string * @required */ name: '', /** * The root DOM element that contains the app * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property root * @type Element */ root: undefined, /** * The instance of F2.UI providing easy access to F2.UI methods * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property ui * @type F2.UI */ ui: undefined, /** * The views that this app supports. Available views * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The * presence of a view can be checked via * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: * * F2.inArray(F2.Constants.Views.SETTINGS, app.views) * * @property views * @type Array */ views: [] }, /** * The assets needed to render an app on the page * @class F2.AppManifest */ AppManifest: { /** * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} * objects * @property apps * @type Array * @required */ apps: [], /** * Any inline javascript tha should initially be run * @property inlineScripts * @type Array * @optional */ inlineScripts: [], /** * Urls to javascript files required by the app * @property scripts * @type Array * @optional */ scripts: [], /** * Urls to CSS files required by the app * @property styles * @type Array * @optional */ styles: [] }, /** * The AppContent object * @class F2.AppManifest.AppContent **/ AppContent: { /** * Arbitrary data to be passed along with the app * @property data * @type object * @optional */ data: {}, /** * The string of HTML representing the app * @property html * @type string * @required */ html: '', /** * A status message * @property status * @type string * @optional */ status: '' }, /** * An object containing configuration information for the * [container](../../container-development.html) * @class F2.ContainerConfig */ ContainerConfig: { /** * Allows the [container](../../container-development.html) to override how * an app's html is inserted into the page. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html * @method afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app * @return {Element} The DOM Element surrounding the app */ afterAppRender: function(appConfig, html) {}, /** * Allows the [container](../../container-development.html) to wrap an app * in extra html. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html. The extra html can provide links to edit app settings and remove an * app from the container. See * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that * should be applied to elements. * @method appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app */ appRender: function(appConfig, html) {}, /** * Allows the container to render html for an app before the AppManifest for * an app has loaded. This can be useful if the design calls for loading * icons to appear for each app before each app is loaded and rendered to * the page. * @method beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ beforeAppRender: function(appConfig) {}, /** * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. * @property debugMode * @type bool * @default false */ debugMode: false, /** * The default language and region specification for this container * represented as an IETF-defined standard language tag, * e.g. `"en-us"` or `"de-de"`. This value is passed to each app * registered as `containerLocale`. * * @property locale * @type string * @default null * @since 1.4.0 */ locale: null, /** * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. * @property scriptErrorTimeout * @type milliseconds * @default 7000 (7 seconds) */ scriptErrorTimeout: 7000, /** * Tells the container that it is currently running within * a secure app page * @property isSecureAppPage * @type bool */ isSecureAppPage: false, /** * Allows the container to specify which page is used when * loading a secure app. The page must reside on a different domain than the * container * @property secureAppPagePath * @type string * @for F2.ContainerConfig */ secureAppPagePath: '', /** * Specifies what views a container will provide buttons * or links to. Generally, the views will be switched via buttons or links * in the app's header. * @property supportedViews * @type Array * @required */ supportedViews: [], /** * An object containing configuration defaults for F2.UI * @class F2.ContainerConfig.UI */ UI: { /** * An object containing configuration defaults for the * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. * @class F2.ContainerConfig.UI.Mask */ Mask: { /** * The backround color of the overlay * @property backgroundColor * @type string * @default #FFF */ backgroundColor: '#FFF', /** * The path to the loading icon * @property loadingIcon * @type string */ loadingIcon: '', /** * The opacity of the background overlay * @property opacity * @type int * @default 0.6 */ opacity: 0.6, /** * Do not use inline styles for mask functinality. Instead classes will * be applied to the elements and it is up to the container provider to * implement the class definitions. * @property useClasses * @type bool * @default false */ useClasses: false, /** * The z-index to use for the overlay * @property zIndex * @type int * @default 2 */ zIndex: 2 } }, /** * Allows the container to fully override how the AppManifest request is * made inside of F2. * * @method xhr * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {function} success The function to be called if the request * succeeds * @param {function} error The function to be called if the request fails * @param {function} complete The function to be called when the request * finishes (after success and error callbacks have been executed) * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has * an `abort` function (such as the jqXHR object in jQuery) to abort the * request) * * @example * F2.init({ * xhr: function(url, appConfigs, success, error, complete) { * $.ajax({ * url: url, * type: 'POST', * data: { * params: F2.stringify(appConfigs, F2.appConfigReplacer) * }, * jsonp: false, // do not put 'callback=' in the query string * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name * dataType: 'json', * success: function(appManifest) { * // custom success logic * success(appManifest); // fire success callback * }, * error: function() { * // custom error logic * error(); // fire error callback * }, * complete: function() { * // custom complete logic * complete(); // fire complete callback * } * }); * } * }); * * @for F2.ContainerConfig */ //xhr: function(url, appConfigs, success, error, complete) {}, /** * Allows the container to override individual parts of the AppManifest * request. See properties and methods with the `xhr.` prefix. * @property xhr * @type Object * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ xhr: { /** * Allows the container to override the request data type (JSON or JSONP) * that is used for the request * @method xhr.dataType * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request data type that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ dataType: function(url, appConfigs) {}, /** * Allows the container to override the request method that is used (just * like the `type` parameter to `jQuery.ajax()`. * @method xhr.type * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request method that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ type: function(url, appConfigs) {}, /** * Allows the container to override the url that is used to request an * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} * @method xhr.url * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The url that should be used for the request * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ url: function(url, appConfigs) {} }, /** * Allows the container to override the script loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadScripts * @type function * * @example * F2.init({ * loadScripts: function(scripts,inlines,callback){ * //load scripts using $.load() for each script or require(scripts) * callback(); * } * }); */ loadScripts: function(scripts,inlines,callback){}, /** * Allows the container to override the stylesheet loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadStyles * @type function * * @example * F2.init({ * loadStyles: function(styles,callback){ * //load styles using $.load() for each stylesheet or another method * callback(); * } * }); */ loadStyles: function(styles,callback){} } }); /** * Constants used throughout the Open Financial Framework * @class F2.Constants * @static */ F2.extend('Constants', { /** * CSS class constants * @class F2.Constants.Css */ Css: (function() { /** @private */ var _PREFIX = 'f2-'; return { /** * The APP class should be applied to the DOM Element that surrounds the * entire app, including any extra html that surrounds the APP\_CONTAINER * that is inserted by the container. See the * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. * @property APP * @type string * @static * @final */ APP: _PREFIX + 'app', /** * The APP\_CONTAINER class should be applied to the outermost DOM Element * of the app. * @property APP_CONTAINER * @type string * @static * @final */ APP_CONTAINER: _PREFIX + 'app-container', /** * The APP\_TITLE class should be applied to the DOM Element that contains * the title for an app. If this class is not present, then * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. * @property APP_TITLE * @type string * @static * @final */ APP_TITLE: _PREFIX + 'app-title', /** * The APP\_VIEW class should be applied to the DOM Element that contains * a view for an app. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. * @property APP_VIEW * @type string * @static * @final */ APP_VIEW: _PREFIX + 'app-view', /** * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that * trigger an * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE * event. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. * @property APP_VIEW_TRIGGER * @type string * @static * @final */ APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', /** * The MASK class is applied to the overlay element that is created * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is * fired. * @property MASK * @type string * @static * @final */ MASK: _PREFIX + 'mask', /** * The MASK_CONTAINER class is applied to the Element that is passed into * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. * @property MASK_CONTAINER * @type string * @static * @final */ MASK_CONTAINER: _PREFIX + 'mask-container' }; })(), /** * Events constants * @class F2.Constants.Events */ Events: (function() { /** @private */ var _APP_EVENT_PREFIX = 'App.'; /** @private */ var _CONTAINER_EVENT_PREFIX = 'Container.'; return { /** * The APP_SCRIPTS_LOADED event is fired when all the scripts defined in * the AppManifest have been loaded. * @property APP_SCRIPTS_LOADED * @type string * @static * @final */ APP_SCRIPTS_LOADED: _APP_EVENT_PREFIX + 'scriptsLoaded', /** * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an * app. It is up to the app developer to fire this event. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property APP_SYMBOL_CHANGE * @type string * @static * @final */ APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', /** * The APP\_WIDTH\_CHANGE event will be fired by the container when the * width of an app is changed. The app's instanceId should be concatenated * to this constant. * Returns an object with the gridSize and width in pixels: * * { gridSize:8, width:620 } * * @property APP_WIDTH_CHANGE * @type string * @static * @final */ APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', /** * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed * at the container level. This event should only be fired by the * container or container provider. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property CONTAINER_SYMBOL_CHANGE * @type string * @static * @final */ CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', /** * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when * the width of the container has changed. * @property CONTAINER_WIDTH_CHANGE * @type string * @static * @final */ CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange', /** * The CONTAINER\_LOCALE\_CHANGE event will be fired by the container when * the locale of the container has changed. This event should only be fired by the * container or container provider. * Returns an object with the updated locale (IETF-defined standard language tag): * * { locale: 'en-us' } * * @property CONTAINER_LOCALE_CHANGE * @type string * @static * @final */ CONTAINER_LOCALE_CHANGE: _CONTAINER_EVENT_PREFIX + 'localeChange', /** * The RESOURCE_FAILED_TO_LOAD event will be fired by the container when * it fails to load a script or style. * @property RESOURCE_FAILED_TO_LOAD * @depreciated since 1.4 * @type string * @static * @final */ RESOURCE_FAILED_TO_LOAD: _CONTAINER_EVENT_PREFIX + 'resourceFailedToLoad' }; })(), JSONP_CALLBACK: 'F2_jsonpCallback_', AppStatus: { ERROR: 'ERROR', SUCCESS: 'SUCCESS' }, /** * Constants for use with cross-domain sockets * @class F2.Constants.Sockets * @protected */ Sockets: { /** * The EVENT message is sent whenever * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired * @property EVENT * @type string * @static * @final */ EVENT: '__event__', /** * The LOAD message is sent when an iframe socket initially loads. * Returns a JSON string that represents: * * [ App, AppManifest] * * @property LOAD * @type string * @static * @final */ LOAD: '__socketLoad__', /** * The RPC message is sent when a method is passed up from within a secure * app page. * @property RPC * @type string * @static * @final */ RPC: '__rpc__', /** * The RPC\_CALLBACK message is sent when a call back from an RPC method is * fired. * @property RPC_CALLBACK * @type string * @static * @final */ RPC_CALLBACK: '__rpcCallback__', /** * The UI\_RPC message is sent when a UI method called. * @property UI_RPC * @type string * @static * @final */ UI_RPC: '__uiRpc__' }, /** * The available view types to apps. The view should be specified by applying * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the * Element as well which defines what view type is represented. * The `hide` class can be applied to views that should be hidden by default. * @class F2.Constants.Views */ Views: { /** * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the * view. * @property DATA_ATTRIBUTE * @type string * @static * @final */ DATA_ATTRIBUTE: 'data-f2-view', /** * The ABOUT view gives details about the app. * @property ABOUT * @type string * @static * @final */ ABOUT: 'about', /** * The HELP view provides users with help information for using an app. * @property HELP * @type string * @static * @final */ HELP: 'help', /** * The HOME view is the main view for an app. This view should always * be provided by an app. * @property HOME * @type string * @static * @final */ HOME: 'home', /** * The REMOVE view is a special view that handles the removal of an app * from the container. * @property REMOVE * @type string * @static * @final */ REMOVE: 'remove', /** * The SETTINGS view provides users the ability to modify advanced settings * for an app. * @property SETTINGS * @type string * @static * @final */ SETTINGS: 'settings' } }); /** * Handles [Context](../../app-development.html#context) passing from * containers to apps and apps to apps. * @class F2.Events */ F2.extend('Events', (function() { // init EventEmitter var _events = new EventEmitter2({ wildcard:true }); // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); return { /** * Same as F2.Events.emit except that it will not send the event * to all sockets. * @method _socketEmit * @private * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ _socketEmit: function() { return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Execute each of the listeners that may be listening for the specified * event name in order with the list of arguments. * @method emit * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ emit: function() { F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Adds a listener that will execute n times for the event before being * removed. The listener is invoked only the first time the event is * fired, after which it is removed. * @method many * @param {string} event The event name * @param {int} timesToListen The number of times to execute the event * before being removed * @param {function} listener The function to be fired when the event is * emitted */ many: function(event, timesToListen, listener) { return _events.many(event, timesToListen, listener); }, /** * Remove a listener for the specified event. * @method off * @param {string} event The event name * @param {function} listener The function that will be removed */ off: function(event, listener) { return _events.off(event, listener); }, /** * Adds a listener for the specified event * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ on: function(event, listener){ return _events.on(event, listener); }, /** * Adds a one time listener for the event. The listener is invoked only * the first time the event is fired, after which it is removed. * @method once * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ once: function(event, listener) { return _events.once(event, listener); } }; })()); /** * Handles socket communication between the container and secure apps * @class F2.Rpc */ F2.extend('Rpc', (function(){ var _callbacks = {}; var _secureAppPagePath = ''; var _apps = {}; var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); /** * Creates a socket connection from the app to the container using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createAppToContainerSocket * @private */ var _createAppToContainerSocket = function() { var appConfig; // socket closure var isLoaded = false; // its possible for messages to be received before the socket load event has // happened. We'll save off these messages and replay them once the socket // is ready var messagePlayback = []; var socket = new easyXDM.Socket({ onMessage: function(message, origin){ // handle Socket Load if (!isLoaded && _rSocketLoad.test(message)) { message = message.replace(_rSocketLoad, ''); var appParts = F2.parse(message); // make sure we have the AppConfig and AppManifest if (appParts.length == 2) { appConfig = appParts[0]; // save socket _apps[appConfig.instanceId] = { config:appConfig, socket:socket }; // register app F2.registerApps([appConfig], [appParts[1]]); // socket message playback jQuery.each(messagePlayback, function(i, e) { _onMessage(appConfig, message, origin); }); isLoaded = true; } } else if (isLoaded) { // pass everyting else to _onMessage _onMessage(appConfig, message, origin); } else { //F2.log('socket not ready, queuing message', message); messagePlayback.push(message); } } }); }; /** * Creates a socket connection from the container to the app using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createContainerToAppSocket * @private * @param {appConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The F2.AppManifest object */ var _createContainerToAppSocket = function(appConfig, appManifest) { var container = jQuery(appConfig.root); if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { container.find('.' + F2.Constants.Css.APP_CONTAINER); } if (!container.length) { F2.log('Unable to locate app in order to establish secure connection.'); return; } var iframeProps = { scrolling:'no', style:{ width:'100%' } }; if (appConfig.height) { iframeProps.style.height = appConfig.height + 'px'; } var socket = new easyXDM.Socket({ remote: _secureAppPagePath, container: container.get(0), props:iframeProps, onMessage: function(message, origin) { // pass everything to _onMessage _onMessage(appConfig, message, origin); }, onReady: function() { socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); } }); return socket; }; /** * @method _createRpcCallback * @private * @param {string} instanceId The app's Instance ID * @param {function} callbackId The callback ID * @return {function} A function to make the RPC call */ var _createRpcCallback = function(instanceId, callbackId) { return function() { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC_CALLBACK, callbackId, [].slice.call(arguments).slice(2) ); }; }; /** * Handles messages that come across the sockets * @method _onMessage * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} message The socket message * @param {string} origin The originator */ var _onMessage = function(appConfig, message, origin) { var obj, func; function parseFunction(parent, functionName) { var path = String(functionName).split('.'); for (var i = 0; i < path.length; i++) { if (parent[path[i]] === undefined) { parent = undefined; break; } parent = parent[path[i]]; } return parent; } function parseMessage(regEx, message, instanceId) { var o = F2.parse(message.replace(regEx, '')); // if obj.callbacks // for each callback // for each params // if callback matches param // replace param with _createRpcCallback(app.instanceId, callback) if (o.params && o.params.length && o.callbacks && o.callbacks.length) { jQuery.each(o.callbacks, function(i, c) { jQuery.each(o.params, function(i, p) { if (c == p) { o.params[i] = _createRpcCallback(instanceId, c); } }); }); } return o; } // handle UI Call if (_rUiCall.test(message)) { obj = parseMessage(_rUiCall, message, appConfig.instanceId); func = parseFunction(appConfig.ui, obj.functionName); // if we found the function, call it if (func !== undefined) { func.apply(appConfig.ui, obj.params); } else { F2.log('Unable to locate UI RPC function: ' + obj.functionName); } // handle RPC } else if (_rRpc.test(message)) { obj = parseMessage(_rRpc, message, appConfig.instanceId); func = parseFunction(window, obj.functionName); if (func !== undefined) { func.apply(func, obj.params); } else { F2.log('Unable to locate RPC function: ' + obj.functionName); } // handle RPC Callback } else if (_rRpcCallback.test(message)) { obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); if (_callbacks[obj.functionName] !== undefined) { _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); delete _callbacks[obj.functionName]; } // handle Events } else if (_rEvents.test(message)) { obj = parseMessage(_rEvents, message, appConfig.instanceId); F2.Events._socketEmit.apply(F2.Events, obj); } }; /** * Registers a callback function * @method _registerCallback * @private * @param {function} callback The callback function * @return {string} The callback ID */ var _registerCallback = function(callback) { var callbackId = F2.guid(); _callbacks[callbackId] = callback; return callbackId; }; return { /** * Broadcast an RPC function to all sockets * @method broadcast * @param {string} messageType The message type * @param {Array} params The parameters to broadcast */ broadcast: function(messageType, params) { // check valid messageType var message = messageType + F2.stringify(params); jQuery.each(_apps, function(i, a) { a.socket.postMessage(message); }); }, /** * Calls a remote function * @method call * @param {string} instanceId The app's Instance ID * @param {string} messageType The message type * @param {string} functionName The name of the remote function * @param {Array} params An array of parameters to pass to the remote * function. Any functions found within the params will be treated as a * callback function. */ call: function(instanceId, messageType, functionName, params) { // loop through params and find functions and convert them to callbacks var callbacks = []; jQuery.each(params, function(i, e) { if (typeof e === 'function') { var cid = _registerCallback(e); params[i] = cid; callbacks.push(cid); } }); // check valid messageType _apps[instanceId].socket.postMessage( messageType + F2.stringify({ functionName:functionName, params:params, callbacks:callbacks }) ); }, /** * Init function which tells F2.Rpc whether it is running at the container- * level or the app-level. This method is generally called by * F2.{{#crossLink "F2/init"}}{{/crossLink}} * @method init * @param {string} [secureAppPagePath] The * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath * property */ init: function(secureAppPagePath) { _secureAppPagePath = secureAppPagePath; if (!_secureAppPagePath) { _createAppToContainerSocket(); } }, /** * Determines whether the Instance ID is considered to be 'remote'. This is * determined by checking if 1) the app has an open socket and 2) whether * F2.Rpc is running inside of an iframe * @method isRemote * @param {string} instanceId The Instance ID * @return {bool} True if there is an open socket */ isRemote: function(instanceId) { return ( // we have an app _apps[instanceId] !== undefined && // the app is secure _apps[instanceId].config.isSecure && // we can't access the iframe jQuery(_apps[instanceId].config.root).find('iframe').length === 0 ); }, /** * Creates a container-to-app or app-to-container socket for communication * @method register * @param {F2.AppConfig} [appConfig] The F2.AppConfig object * @param {F2.AppManifest} [appManifest] The F2.AppManifest object */ register: function(appConfig, appManifest) { if (!!appConfig && !!appManifest) { _apps[appConfig.instanceId] = { config:appConfig, socket:_createContainerToAppSocket(appConfig, appManifest) }; } else { F2.log('Unable to register socket connection. Please check container configuration.'); } } }; })()); F2.extend('UI', (function(){ var _containerConfig; /** * UI helper methods * @class F2.UI * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object */ var UI_Class = function(appConfig) { var _appConfig = appConfig; var $root = jQuery(appConfig.root); var _updateHeight = function(height) { height = height || jQuery(_appConfig.root).outerHeight(); if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'updateHeight', [ height ] ); } else { _appConfig.height = height; $root.find('iframe').height(_appConfig.height); } }; //http://getbootstrap.com/javascript/#modals var _modalHtml = function(type,message,showCancel){ return [ '<div class="modal">', '<div class="modal-dialog">', '<div class="modal-content">', '<div class="modal-header">', '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>', '<h4 class="modal-title">',type,'</h4>', '</div>', '<div class="modal-body"><p>', message, '</p></div>', '<div class="modal-footer">', ((showCancel) ? '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' : ''), '<button type="button" class="btn btn-primary btn-ok">OK</button>', '</div>', '</div>', '</div>', '</div>' ].join(''); }; return { /** * Removes a overlay from an Element on the page * @method hideMask * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader */ hideMask: function(selector) { F2.UI.hideMask(_appConfig.instanceId, selector); }, /** * Helper methods for creating and using Modals * @class F2.UI.Modals * @for F2.UI */ Modals: (function(){ var _renderAlert = function(message) { return _modalHtml('Alert',message); }; var _renderConfirm = function(message) { return _modalHtml('Confirm',message,true); }; return { /** * Display an alert message on the page * @method alert * @param {string} message The message to be displayed * @param {function} [callback] The callback to be fired when the user * closes the dialog * @for F2.UI.Modals */ alert: function(message, callback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.alert()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.alert', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderAlert(message)) .on('show.bs.modal', function() { var modal = this; jQuery(modal).find('.btn-primary').on('click', function() { jQuery(modal).modal('hide').remove(); (callback || jQuery.noop)(); }); }) .modal({backdrop:true}); } }, /** * Display a confirm message on the page * @method confirm * @param {string} message The message to be displayed * @param {function} okCallback The function that will be called when the OK * button is pressed * @param {function} cancelCallback The function that will be called when * the Cancel button is pressed * @for F2.UI.Modals */ confirm: function(message, okCallback, cancelCallback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.confirm', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderConfirm(message)) .on('show.bs.modal', function() { var modal = this; jQuery(modal).find('.btn-ok').on('click', function() { jQuery(modal).modal('hide').remove(); (okCallback || jQuery.noop)(); }); jQuery(modal).find('.btn-cancel').on('click', function() { jQuery(modal).modal('hide').remove(); (cancelCallback || jQuery.noop)(); }); }) .modal({backdrop:true}); } } }; })(), /** * Sets the title of the app as shown in the browser. Depending on the * container HTML, this method may do nothing if the container has not been * configured properly or else the container provider does not allow Title's * to be set. * @method setTitle * @params {string} title The title of the app * @for F2.UI */ setTitle: function(title) { if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'setTitle', [ title ] ); } else { jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); } }, /** * Display an ovarlay over an Element on the page * @method showMask * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ showMask: function(selector, showLoader) { F2.UI.showMask(_appConfig.instanceId, selector, showLoader); }, /** * For secure apps, this method updates the size of the iframe that * contains the app. **Note: It is recommended that app developers call * this method anytime Elements are added or removed from the DOM** * @method updateHeight * @params {int} height The height of the app */ updateHeight: _updateHeight, /** * Helper methods for creating and using Views * @class F2.UI.Views * @for F2.UI */ Views: (function(){ var _events = new EventEmitter2(); var _rValidEvents = /change/i; // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); var _isValid = function(eventName) { if (_rValidEvents.test(eventName)) { return true; } else { F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); return false; } }; return { /** * Change the current view for the app or add an event listener * @method change * @param {string|function} [input] If a string is passed in, the view * will be changed for the app. If a function is passed in, a change * event listener will be added. * @for F2.UI.Views */ change: function(input) { if (typeof input === 'function') { this.on('change', input); } else if (typeof input === 'string') { if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Views.change', [].slice.call(arguments) ); } else if (F2.inArray(input, _appConfig.views)) { jQuery('.' + F2.Constants.Css.APP_VIEW, $root) .addClass('hide') .filter('[data-f2-view="' + input + '"]', $root) .removeClass('hide'); _updateHeight(); _events.emit('change', input); } } }, /** * Removes a view event listener * @method off * @param {string} event The event name * @param {function} listener The function that will be removed * @for F2.UI.Views */ off: function(event, listener) { if (_isValid(event)) { _events.off(event, listener); } }, /** * Adds a view event listener * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted * @for F2.UI.Views */ on: function(event, listener) { if (_isValid(event)) { _events.on(event, listener); } } }; })() }; }; /** * Removes a overlay from an Element on the page * @method hideMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader * @for F2.UI */ UI_Class.hideMask = function(instanceId, selector) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.hideMask()'); return; } if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.hideMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector ] ); } else { var container = jQuery(selector); container.find('> .' + F2.Constants.Css.MASK).remove(); container.removeClass(F2.Constants.Css.MASK_CONTAINER); // if the element contains this data property, we need to reset static // position if (container.data(F2.Constants.Css.MASK_CONTAINER)) { container.css({'position':'static'}); } } }; /** * * @method init * @static * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ UI_Class.init = function(containerConfig) { _containerConfig = containerConfig; // set defaults _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); }; /** * Display an ovarlay over an Element on the page * @method showMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ UI_Class.showMask = function(instanceId, selector, showLoading) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.showMask()'); return; } if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.showMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector, showLoading ] ); } else { if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); } var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); var mask = jQuery('<div>') .height('100%' /*container.outerHeight()*/) .width('100%' /*container.outerWidth()*/) .addClass(F2.Constants.Css.MASK); // set inline styles if useClasses is false if (!_containerConfig.UI.Mask.useClasses) { mask.css({ 'background-color':_containerConfig.UI.Mask.backgroundColor, 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', 'background-position':'50% 50%', 'background-repeat':'no-repeat', 'display':'block', 'left':0, 'min-height':30, 'padding':0, 'position':'absolute', 'top':0, 'z-index':_containerConfig.UI.Mask.zIndex, 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', 'opacity':_containerConfig.UI.Mask.opacity }); } // only set the position if the container is currently static if (container.css('position') === 'static') { container.css({'position':'relative'}); // setting this data property tells hideMask to set the position // back to static container.data(F2.Constants.Css.MASK_CONTAINER, true); } // add the mask to the container container.append(mask); } }; return UI_Class; })()); /** * Root namespace of the F2 SDK * @module f2 * @class F2 */ F2.extend('', (function() { var _apps = {}; var _config = false; var _bUsesAppHandlers = false; var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); var _loadingScripts = {}; /** * Appends the app's html to the DOM * @method _afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html * @return {Element} The DOM Element that contains the app */ var _afterAppRender = function(appConfig, html) { var handler = _config.afterAppRender || function(appConfig, html) { return jQuery(html).appendTo('body'); }; var appContainer = handler(appConfig, html); if ( !! _config.afterAppRender && !appContainer) { F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); return; } else { // apply APP class jQuery(appContainer).addClass(F2.Constants.Css.APP); return appContainer.get(0); } }; /** * Renders the html for an app. * @method _appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html */ var _appRender = function(appConfig, html) { // apply APP_CONTAINER class and AppID html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); // optionally apply wrapper html if (_config.appRender) { html = _config.appRender(appConfig, html); } return _outerHtml(html); }; /** * Rendering hook to allow containers to render some html prior to an app * loading * @method _beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ var _beforeAppRender = function(appConfig) { var handler = _config.beforeAppRender || jQuery.noop; return handler(appConfig); }; /** * Handler to inform the container that a script failed to load * @method _onScriptLoadFailure * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param scriptInfo The path of the script that failed to load or the exception info * for the inline script that failed to execute */ var _appScriptLoadFailed = function(appConfig, scriptInfo) { var handler = _config.appScriptLoadFailed || jQuery.noop; return handler(appConfig, scriptInfo); }; /** * Adds properties to the AppConfig object * @method _createAppConfig * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with * necessary properties */ var _createAppConfig = function(appConfig) { // make a copy of the app config to ensure that the original is not modified appConfig = jQuery.extend(true, {}, appConfig); // create the instanceId for the app appConfig.instanceId = appConfig.instanceId || F2.guid(); // default the views if not provided appConfig.views = appConfig.views || []; if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { appConfig.views.push(F2.Constants.Views.HOME); } //pass container-defined locale to each app if (F2.ContainerConfig.locale){ appConfig.containerLocale = F2.ContainerConfig.locale; } return appConfig; }; /** * Generate an AppConfig from the element's attributes * @method _getAppConfigFromElement * @private * @param {Element} node The DOM node from which to generate the F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object */ var _getAppConfigFromElement = function(node) { var appConfig; if (node) { var appId = node.getAttribute('data-f2-appid'); var manifestUrl = node.getAttribute('data-f2-manifesturl'); if (appId && manifestUrl) { appConfig = { appId: appId, enableBatchRequests: node.hasAttribute('data-f2-enablebatchrequests'), isSecure: node.hasAttribute('data-f2-issecure'), manifestUrl: manifestUrl, root: node }; // See if the user passed in a block of serialized json var contextJson = node.getAttribute('data-f2-context'); if (contextJson) { try { appConfig.context = F2.parse(contextJson); } catch (e) { console.warn('F2: "data-f2-context" of node is not valid JSON', '"' + e + '"'); } } } } return appConfig; }; /** * Returns true if the DOM node has children that are not text nodes * @method _hasNonTextChildNodes * @private * @param {Element} node The DOM node * @return {bool} True if there are non-text children */ var _hasNonTextChildNodes = function(node) { var hasNodes = false; if (node.hasChildNodes()) { for (var i = 0, len = node.childNodes.length; i < len; i++) { if (node.childNodes[i].nodeType === 1) { hasNodes = true; break; } } } return hasNodes; }; /** * Adds properties to the ContainerConfig object to take advantage of defaults * @method _hydrateContainerConfig * @private * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ var _hydrateContainerConfig = function(containerConfig) { if (!containerConfig.scriptErrorTimeout) { containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; } if (containerConfig.debugMode !== true) { containerConfig.debugMode = F2.ContainerConfig.debugMode; } if (containerConfig.locale && typeof containerConfig.locale == 'string'){ F2.ContainerConfig.locale = containerConfig.locale; } }; /** * Attach app events * @method _initAppEvents * @private */ var _initAppEvents = function(appConfig) { jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { event.preventDefault(); var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); // handle the special REMOVE view if (view == F2.Constants.Views.REMOVE) { F2.removeApp(appConfig.instanceId); } else { appConfig.ui.Views.change(view); } }); }; /** * Attach container Events * @method _initContainerEvents * @private */ var _initContainerEvents = function() { var resizeTimeout; var resizeHandler = function() { F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); }; jQuery(window).on('resize', function() { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(resizeHandler, 100); }); //listen for container-broadcasted locale changes F2.Events.on(F2.Constants.Events.CONTAINER_LOCALE_CHANGE,function(data){ if (data.locale && typeof data.locale == 'string'){ F2.ContainerConfig.locale = data.locale; } }); }; /** * Checks if an element is a placeholder element * @method _isPlaceholderElement * @private * @param {Element} node The DOM element to check * @return {bool} True if the element is a placeholder */ var _isPlaceholderElement = function(node) { return ( F2.isNativeDOMNode(node) && !_hasNonTextChildNodes(node) && !!node.getAttribute('data-f2-appid') && !!node.getAttribute('data-f2-manifesturl') ); }; /** * Has the container been init? * @method _isInit * @private * @return {bool} True if the container has been init */ var _isInit = function() { return !!_config; }; /** * Instantiates each app from it's appConfig and stores that in a local private collection * @method _createAppInstance * @private * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects */ var _createAppInstance = function(appConfig, appContent) { // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // instantiate F2.App if (F2.Apps[appConfig.appId] !== undefined) { if (typeof F2.Apps[appConfig.appId] === 'function') { // IE setTimeout(function() { _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); if (_apps[appConfig.instanceId].app['init'] !== undefined) { _apps[appConfig.instanceId].app.init(); } }, 0); } else { F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); } } }; /** * Loads the app's html/css/javascript * @method loadApp * @private * @param {Array} appConfigs An array of * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects * @param {F2.AppManifest} [appManifest] The AppManifest object */ var _loadApps = function(appConfigs, appManifest) { appConfigs = [].concat(appConfigs); // check for secure app if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { _loadSecureApp(appConfigs[0], appManifest); return; } // check that the number of apps in manifest matches the number requested if (appConfigs.length != appManifest.apps.length) { F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); return; } var _findExistingScripts = function() { return jQuery('script[src]').map(function(i, tag) { return tag.src; }); }; var _findExistingStyles = function() { return jQuery('link[href]').map(function(i, tag) { return tag.href; }); }; // Fn for loading manifest Styles var _loadStyles = function(styles, cb) { // Reduce the list to styles that haven't been loaded var existingStyles = _findExistingStyles(); styles = jQuery.grep(styles, function(url) { return url && jQuery.inArray(url, existingStyles) === -1; }); // Attempt to use the user provided method if (_config.loadStyles) { return _config.loadStyles(styles, cb); } // load styles, see #101 var stylesFragment = null, useCreateStyleSheet = !!document.createStyleSheet; jQuery.each(styles, function(i, resourceUrl) { if (useCreateStyleSheet) { document.createStyleSheet(resourceUrl); } else { stylesFragment = stylesFragment || []; stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + resourceUrl + '"/>'); } }); if (stylesFragment) { jQuery('head').append(stylesFragment.join('')); } cb(); }; // For loading AppManifest.scripts // Parts derived from curljs, headjs, requirejs, dojo var _loadScripts = function(scripts, cb) { // Reduce the list to scripts that haven't been loaded var existingScripts = _findExistingScripts(); var loadingScripts = Object.keys(_loadingScripts); scripts = jQuery.grep(scripts, function(url) { return url && (jQuery.inArray(url, existingScripts) === -1 || jQuery.inArray(url, loadingScripts) !== -1); }); // Attempt to use the user provided method if (_config.loadScripts) { return _config.loadScripts(scripts, cb); } if (!scripts.length) { return cb(); } var doc = window.document; var scriptCount = scripts.length; var scriptsLoaded = 0; //http://caniuse.com/#feat=script-async // var supportsAsync = 'async' in doc.createElement('script') || 'MozAppearance' in doc.documentElement.style || window.opera; var head = doc && (doc['head'] || doc.getElementsByTagName('head')[0]); // to keep IE from crying, we need to put scripts before any // <base> elements, but after any <meta>. this should do it: var insertBeforeEl = head && head.getElementsByTagName('base')[0] || null; // Check for IE10+ so that we don't rely on onreadystatechange, readyStates for IE6-9 var readyStates = 'addEventListener' in window ? {} : { 'loaded': true, 'complete': true }; // Log and emit event for the failed (400,500) scripts var _error = function(e) { setTimeout(function() { var evtData = { src: e.target.src, appId: appConfigs[0].appId }; // Send error to console F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); // TODO: deprecate, see #222 F2.Events.emit(F2.Constants.Events.RESOURCE_FAILED_TO_LOAD, evtData); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], evtData.src); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], evtData.src ); } }, _config.scriptErrorTimeout); // Defaults to 7000 }; var _checkComplete = function() { // Are we done loading all scripts for this app? if (++scriptsLoaded === scriptCount) { // success cb(); } }; var _emptyWaitlist = function(resourceKey, errorEvt) { var waiting, waitlist = _loadingScripts[resourceKey]; if (!waitlist) { return; } for (var i=0; i<waitlist.length; i++) { waiting = waitlist [i]; if (errorEvt) { waiting.error(errorEvt); } else { waiting.success(); } } _loadingScripts[resourceKey] = null; }; // Load scripts and eval inlines once complete jQuery.each(scripts, function(i, e) { var script = doc.createElement('script'), resourceUrl = e, resourceKey = resourceUrl.toLowerCase(); // this script is actively loading, add this app to the wait list if (_loadingScripts[resourceKey]) { _loadingScripts[resourceKey].push({ success: _checkComplete, error: _error }); return; } // create the waitlist _loadingScripts[resourceKey] = []; // If in debugMode, add cache buster to each script URL if (_config.debugMode) { resourceUrl += '?cachebuster=' + new Date().getTime(); } // Scripts are loaded asynchronously and executed in order // in supported browsers: http://caniuse.com/#feat=script-async script.async = false; script.type = 'text/javascript'; script.charset = 'utf-8'; script.onerror = function(e) { _error(e); _emptyWaitlist(resourceKey, e); }; // Use a closure for the load event so that we can dereference the original script script.onload = script.onreadystatechange = function(e) { e = e || window.event; // For older IE // detect when it's done loading // ev.type == 'load' is for all browsers except IE6-9 // IE6-9 need to use onreadystatechange and look for // el.readyState in {loaded, complete} (yes, we need both) if (e.type == 'load' || readyStates[script.readyState]) { // Done, cleanup script.onload = script.onreadystatechange = script.onerror = ''; // increment and check if scripts are done _checkComplete(); // empty wait list _emptyWaitlist(resourceKey); // Dereference script script = null; } }; //set the src, start loading script.src = resourceUrl; //<head> really is the best head.insertBefore(script, insertBeforeEl); }); }; var _loadInlineScripts = function(inlines, cb) { // Attempt to use the user provided method if (_config.loadInlineScripts) { _config.loadInlineScripts(inlines, cb); } else { for (var i = 0, len = inlines.length; i < len; i++) { try { eval(inlines[i]); } catch (exception) { F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]); // Emit events F2.Events.emit('RESOURCE_FAILED_TO_LOAD', { appId:appConfigs[0].appId, src: inlines[i], err: exception }); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], exception); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], exception ); } } } cb(); } }; // Determine whether an element has been added to the page var elementInDocument = function(element) { if (element) { while (element.parentNode) { element = element.parentNode; if (element === document) { return true; } } } return false; }; // Fn for loading manifest app html var _loadHtml = function(apps) { jQuery.each(apps, function(i, a) { if (_isPlaceholderElement(appConfigs[i].root)) { jQuery(appConfigs[i].root) .addClass(F2.Constants.Css.APP) .append(jQuery(a.html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfigs[i].appId)); } else if (!_bUsesAppHandlers) { // load html and save the root node appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfigs[i], // the app config _outerHtml(jQuery(a.html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfigs[i].appId)) ); var appId = appConfigs[i].appId, root = appConfigs[i].root; if (!root) { throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); } if (!elementInDocument(root)) { throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfigs[i] // the app config ); if (!F2.isNativeDOMNode(root)) { throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); } } // init events _initAppEvents(appConfigs[i]); }); }; // Pull out the manifest data var scripts = appManifest.scripts || []; var styles = appManifest.styles || []; var inlines = appManifest.inlineScripts || []; var apps = appManifest.apps || []; // Finally, load the styles, html, and scripts _loadStyles(styles, function() { // Put the html on the page _loadHtml(apps); // Add the script content to the page _loadScripts(scripts, function() { // emit event we're done with scripts if (appConfigs[0]){ F2.Events.emit('APP_SCRIPTS_LOADED', { appId:appConfigs[0].appId, scripts:scripts }); } // Load any inline scripts _loadInlineScripts(inlines, function() { // Create the apps jQuery.each(appConfigs, function(i, a) { _createAppInstance(a, appManifest.apps[i]); }); }); }); }); }; /** * Loads the app's html/css/javascript into an iframe * @method loadSecureApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the * page. */ var _loadSecureApp = function(appConfig, appManifest) { // make sure the container is configured for secure apps if (_config.secureAppPagePath) { if (_isPlaceholderElement(appConfig.root)) { jQuery(appConfig.root) .addClass(F2.Constants.Css.APP) .append(jQuery('<div></div>').addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); } else if (!_bUsesAppHandlers) { // create the html container for the iframe appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>')); } else { var $root = jQuery(appConfig.root); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfig, // the app config _outerHtml(jQuery(appManifest.html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)) ); if ($root.parents('body:first').length === 0) { throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfig // the app config ); if (!appConfig.root) { throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } if (!F2.isNativeDOMNode(appConfig.root)) { throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } } // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // init events _initAppEvents(appConfig); // create RPC socket F2.Rpc.register(appConfig, appManifest); } else { F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); } }; var _outerHtml = function(html) { return jQuery('<div></div>').append(html).html(); }; /** * Checks if the app is valid * @method _validateApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @returns {bool} True if the app is valid */ var _validateApp = function(appConfig) { // check for valid app configurations if (!appConfig.appId) { F2.log('"appId" missing from app object'); return false; } else if (!appConfig.root && !appConfig.manifestUrl) { F2.log('"manifestUrl" missing from app object'); return false; } return true; }; /** * Checks if the ContainerConfig is valid * @method _validateContainerConfig * @private * @returns {bool} True if the config is valid */ var _validateContainerConfig = function() { if (_config) { if (_config.xhr) { if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { throw ('ContainerConfig.xhr should be a function or an object'); } if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { throw ('ContainerConfig.xhr.dataType should be a function'); } if (_config.xhr.type && typeof _config.xhr.type !== 'function') { throw ('ContainerConfig.xhr.type should be a function'); } if (_config.xhr.url && typeof _config.xhr.url !== 'function') { throw ('ContainerConfig.xhr.url should be a function'); } } } return true; }; return { /** * Gets the current list of apps in the container * @method getContainerState * @returns {Array} An array of objects containing the appId */ getContainerState: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerState()'); return; } return jQuery.map(_apps, function(app) { return { appId: app.config.appId }; }); }, /** * Gets the current locale defined by the container * @method getContainerLocale * @returns {String} IETF-defined standard language tag */ getContainerLocale: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerLocale()'); return; } return F2.ContainerConfig.locale; }, /** * Initializes the container. This method must be called before performing * any other actions in the container. * @method init * @param {F2.ContainerConfig} config The configuration object */ init: function(config) { _config = config || {}; _validateContainerConfig(); _hydrateContainerConfig(_config); // dictates whether we use the old logic or the new logic. // TODO: Remove in v2.0 _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); // only establish RPC connection if the container supports the secure app page if ( !! _config.secureAppPagePath || _config.isSecureAppPage) { F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false); } F2.UI.init(_config); if (!_config.isSecureAppPage) { _initContainerEvents(); } }, /** * Has the container been init? * @method isInit * @return {bool} True if the container has been init */ isInit: _isInit, /** * Automatically load apps that are already defined in the DOM. Elements will * be rendered into the location of the placeholder DOM element. Any AppHandlers * that are defined will be bypassed. * @method loadPlaceholders * @param {Element} parentNode The element to search for placeholder apps */ loadPlaceholders: function(parentNode) { var elements = [], appConfigs = [], add = function(e) { if (!e) { return; } elements.push(e); }, addAll = function(els) { if (!els) { return; } for (var i = 0, len = els.length; i < len; i++) { add(els[i]); } }; if (!!parentNode && !F2.isNativeDOMNode(parentNode)) { throw ('"parentNode" must be null or a DOM node'); } // if the passed in element has a data-f2-appid attribute add // it to the list of elements but to not search within that // element for other placeholders if (parentNode && parentNode.hasAttribute('data-f2-appid')) { add(parentNode); } else { // find placeholders within the parentNode only if // querySelectorAll exists parentNode = parentNode || document; if (parentNode.querySelectorAll) { addAll(parentNode.querySelectorAll('[data-f2-appid]')); } } for (var i = 0, len = elements.length; i < len; i++) { var appConfig = _getAppConfigFromElement(elements[i]); appConfigs.push(appConfig); } if (appConfigs.length) { F2.registerApps(appConfigs); } }, /** * Begins the loading process for all apps and/or initialization process for pre-loaded apps. * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will * contain the app's unique instanceId within the container. If the * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered * to be a pre-loaded app and will be handled accordingly. Optionally, the * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those * assets will be used instead of making a request. * @method registerApps * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {Array} [appManifests] An array of * {{#crossLink "F2.AppManifest"}}{{/crossLink}} * objects. This array must be the same length as the apps array that is * objects. This array must be the same length as the apps array that is * passed in. This can be useful if apps are loaded on the server-side and * passed down to the client. * @example * Traditional App requests. * * // Traditional f2 app configs * var arConfigs = [ * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app2', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Pre-loaded and tradition apps mixed. * * // Pre-loaded apps and traditional f2 app configs * // you can preload the same app multiple times as long as you have a unique root for each * var arConfigs = [ * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-1', * manifestUrl: '' * }, * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-2', * manifestUrl: '' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Apps with predefined manifests. * * // Traditional f2 app configs * var arConfigs = [ * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app2', context: {}} * ]; * * // Pre requested manifest responses * var arManifests = [ * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App 2!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/App2Class.js'], * styles: ['http://www.domain.com/css/App2Styles.css'] * } * ]; * * F2.init(); * F2.registerApps(arConfigs, arManifests); */ registerApps: function(appConfigs, appManifests) { if (!_isInit()) { F2.log('F2.init() must be called before F2.registerApps()'); return; } else if (!appConfigs) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; } var appStack = []; var batches = {}; var callbackStack = {}; var haveManifests = false; appConfigs = [].concat(appConfigs); appManifests = [].concat(appManifests || []); haveManifests = !! appManifests.length; // appConfigs must have a length if (!appConfigs.length) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; // ensure that the array of apps and manifests are qual } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { F2.log('The length of "apps" does not equal the length of "appManifests"'); return; } // validate each app and assign it an instanceId // then determine which apps can be batched together jQuery.each(appConfigs, function(i, a) { // add properties and methods a = _createAppConfig(a); // Will set to itself, for preloaded apps, or set to null for apps that aren't already // on the page. a.root = a.root || null; // we validate the app after setting the root property because pre-load apps do no require // manifest url if (!_validateApp(a)) { return; // move to the next app } // save app _apps[a.instanceId] = { config: a }; // If the root property is defined then this app is considered to be preloaded and we will // run it through that logic. if (a.root && !_isPlaceholderElement(a.root)) { if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) { F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); F2.log('AppConfig instance:', a); throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); } else if (jQuery(a.root).length != 1) { F2.log('AppConfig invalid for pre-load, root not unique'); F2.log('AppConfig instance:', a); F2.log('Number of dom node instances:', jQuery(a.root).length); throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); } // instantiate F2.App _createAppInstance(a, { preloaded: true, status: F2.Constants.AppStatus.SUCCESS }); // init events _initAppEvents(a); // Continue on in the .each loop, no need to continue because the app is on the page // the js in initialized, and it is ready to role. return; // equivalent to continue in .each } if (!_isPlaceholderElement(a.root)) { if (!_bUsesAppHandlers) { // fire beforeAppRender a.root = _beforeAppRender(a); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_CREATE_ROOT, a // the app config ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_BEFORE, a // the app config ); } } // if we have the manifest, go ahead and load the app if (haveManifests) { _loadApps(a, appManifests[i]); } else { // check if this app can be batched if (a.enableBatchRequests && !a.isSecure) { batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; batches[a.manifestUrl.toLowerCase()].push(a); } else { appStack.push({ apps: [a], url: a.manifestUrl }); } } }); // we don't have the manifests, go ahead and load them if (!haveManifests) { // add the batches to the appStack jQuery.each(batches, function(i, b) { appStack.push({ url: i, apps: b }); }); // if an app is being loaded more than once on the page, there is the // potential that the jsonp callback will be clobbered if the request // for the AppManifest for the app comes back at the same time as // another request for the same app. We'll create a callbackStack // that will ensure that requests for the same app are loaded in order // rather than at the same time jQuery.each(appStack, function(i, req) { // define the callback function based on the first app's App ID var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; // push the request onto the callback stack callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; callbackStack[jsonpCallback].push(req); }); // loop through each item in the callback stack and make the request // for the AppManifest. When the request is complete, pop the next // request off the stack and make the request. jQuery.each(callbackStack, function(i, requests) { var manifestRequest = function(jsonpCallback, req) { if (!req) { return; } // setup defaults and callbacks var url = req.url, type = 'GET', dataType = 'jsonp', completeFunc = function() { manifestRequest(i, requests.pop()); }, errorFunc = function() { jQuery.each(req.apps, function(idx, item) { item.name = item.name || item.appId; F2.log('Removed failed ' + item.name + ' app', item); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_MANIFEST_REQUEST_FAIL, item // the app config ); F2.removeApp(item.instanceId); }); }, successFunc = function(appManifest) { _loadApps(req.apps, appManifest); }; // optionally fire xhr overrides if (_config.xhr && _config.xhr.dataType) { dataType = _config.xhr.dataType(req.url, req.apps); if (typeof dataType !== 'string') { throw ('ContainerConfig.xhr.dataType should return a string'); } } if (_config.xhr && _config.xhr.type) { type = _config.xhr.type(req.url, req.apps); if (typeof type !== 'string') { throw ('ContainerConfig.xhr.type should return a string'); } } if (_config.xhr && _config.xhr.url) { url = _config.xhr.url(req.url, req.apps); if (typeof url !== 'string') { throw ('ContainerConfig.xhr.url should return a string'); } } // setup the default request function if an override is not present var requestFunc = _config.xhr; if (typeof requestFunc !== 'function') { requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { jQuery.ajax({ url: url, type: type, data: { params: F2.stringify(req.apps, F2.appConfigReplacer) }, jsonp: false, // do not put 'callback=' in the query string jsonpCallback: jsonpCallback, // Unique function name dataType: dataType, success: successCallback, error: function(jqxhr, settings, exception) { F2.log('Failed to load app(s)', exception.toString(), req.apps); errorCallback(); }, complete: completeCallback }); }; } requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); }; manifestRequest(i, requests.pop()); }); } }, /** * Removes all apps from the container * @method removeAllApps */ removeAllApps: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeAllApps()'); return; } jQuery.each(_apps, function(i, a) { F2.removeApp(a.config.instanceId); }); }, /** * Removes an app from the container * @method removeApp * @param {string} instanceId The app's instanceId */ removeApp: function(instanceId) { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeApp()'); return; } if (_apps[instanceId]) { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_BEFORE, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_AFTER, _apps[instanceId] // the app instance ); delete _apps[instanceId]; } } }; })()); jQuery(function() { var autoloadEls = [], add = function(e) { if (!e) { return; } autoloadEls.push(e); }, addAll = function(els) { if (!els) { return; } for (var i = 0, len = els.length; i < len; i++) { add(els[i]); } }; // support id-based autoload add(document.getElementById('f2-autoload')); // support class/attribute based autoload if (document.querySelectorAll) { addAll(document.querySelectorAll('[data-f2-autoload]')); addAll(document.querySelectorAll('.f2-autoload')); } // if elements were found, auto-init F2 and load any placeholders if (autoloadEls.length) { F2.init(); for (var i = 0, len = autoloadEls.length; i < len; i++) { F2.loadPlaceholders(autoloadEls[i]); } } }); exports.F2 = F2; if (typeof define !== 'undefined' && define.amd) { define(function() { return F2; }); } })(typeof exports !== 'undefined' ? exports : window);
mit
chickensmitten/ffcrm
spec/controllers/entities/campaigns_controller_spec.rb
24853
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe CampaignsController do def get_data_for_sidebar @status = Setting.campaign_status.dup end before(:each) do require_user set_current_tab(:campaigns) end # GET /campaigns # GET /campaigns.xml #---------------------------------------------------------------------------- describe "responding to GET index" do before(:each) do get_data_for_sidebar end it "should expose all campaigns as @campaigns and render [index] template" do @campaigns = [ FactoryGirl.create(:campaign, :user => current_user) ] get :index assigns[:campaigns].should == @campaigns response.should render_template("campaigns/index") end it "should collect the data for the opportunities sidebar" do @campaigns = [ FactoryGirl.create(:campaign, :user => current_user) ] get :index (assigns[:campaign_status_total].keys.map(&:to_sym) - (@status << :all << :other)).should == [] end it "should filter out campaigns by status" do controller.session[:campaigns_filter] = "planned,started" @campaigns = [ FactoryGirl.create(:campaign, :user => current_user, :status => "started"), FactoryGirl.create(:campaign, :user => current_user, :status => "planned") ] # This one should be filtered out. FactoryGirl.create(:campaign, :user => current_user, :status => "completed") get :index # Note: can't compare campaigns directly because of BigDecimal objects. assigns[:campaigns].size.should == 2 assigns[:campaigns].map(&:status).sort.should == %w(planned started) end it "should perform lookup using query string" do @first = FactoryGirl.create(:campaign, :user => current_user, :name => "Hello, world!") @second = FactoryGirl.create(:campaign, :user => current_user, :name => "Hello again") get :index, :query => "again" assigns[:campaigns].should == [ @second ] assigns[:current_query].should == "again" session[:campaigns_current_query].should == "again" end describe "AJAX pagination" do it "should pick up page number from params" do @campaigns = [ FactoryGirl.create(:campaign, :user => current_user) ] xhr :get, :index, :page => 42 assigns[:current_page].to_i.should == 42 assigns[:campaigns].should == [] # page #42 should be empty if there's only one campaign ;-) session[:campaigns_current_page].to_i.should == 42 response.should render_template("campaigns/index") end it "should pick up saved page number from session" do session[:campaigns_current_page] = 42 @campaigns = [ FactoryGirl.create(:campaign, :user => current_user) ] xhr :get, :index assigns[:current_page].should == 42 assigns[:campaigns].should == [] response.should render_template("campaigns/index") end it "should reset current_page when query is altered" do session[:campaigns_current_page] = 42 session[:campaigns_current_query] = "bill" @campaigns = [ FactoryGirl.create(:campaign, :user => current_user) ] xhr :get, :index assigns[:current_page].should == 1 assigns[:campaigns].should == @campaigns response.should render_template("campaigns/index") end end describe "with mime type of JSON" do it "should render all campaigns as JSON" do @controller.should_receive(:get_campaigns).and_return(@campaigns = []) @campaigns.should_receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :index response.body.should == "generated JSON" end end describe "with mime type of XML" do it "should render all campaigns as xml" do @controller.should_receive(:get_campaigns).and_return(@campaigns = []) @campaigns.should_receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :index response.body.should == "generated XML" end end end # GET /campaigns/1 # GET /campaigns/1.xml HTML #---------------------------------------------------------------------------- describe "responding to GET show" do describe "with mime type of HTML" do before(:each) do @campaign = FactoryGirl.create(:campaign, :id => 42, :user => current_user) @stage = Setting.unroll(:opportunity_stage) @comment = Comment.new end it "should expose the requested campaign as @campaign and render [show] template" do get :show, :id => 42 assigns[:campaign].should == @campaign assigns[:stage].should == @stage assigns[:comment].attributes.should == @comment.attributes response.should render_template("campaigns/show") end it "should update an activity when viewing the campaign" do get :show, :id => @campaign.id @campaign.versions.last.event.should == 'view' end end describe "with mime type of JSON" do it "should render the requested campaign as JSON" do @campaign = FactoryGirl.create(:campaign, :id => 42, :user => current_user) Campaign.should_receive(:find).and_return(@campaign) @campaign.should_receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :show, :id => 42 response.body.should == "generated JSON" end end describe "with mime type of XML" do it "should render the requested campaign as XML" do @campaign = FactoryGirl.create(:campaign, :id => 42, :user => current_user) Campaign.should_receive(:find).and_return(@campaign) @campaign.should_receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :show, :id => 42 response.body.should == "generated XML" end end describe "campaign got deleted or otherwise unavailable" do it "should redirect to campaign index if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy get :show, :id => @campaign.id flash[:warning].should_not == nil response.should redirect_to(campaigns_path) end it "should redirect to campaign index if the campaign is protected" do @campaign = FactoryGirl.create(:campaign, :user => FactoryGirl.create(:user), :access => "Private") get :show, :id => @campaign.id flash[:warning].should_not == nil response.should redirect_to(campaigns_path) end it "should return 404 (Not Found) JSON error" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy request.env["HTTP_ACCEPT"] = "application/json" get :show, :id => @campaign.id response.code.should == "404" # :not_found end it "should return 404 (Not Found) XML error" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy request.env["HTTP_ACCEPT"] = "application/xml" get :show, :id => @campaign.id response.code.should == "404" # :not_found end end end # GET /campaigns/new # GET /campaigns/new.xml AJAX #---------------------------------------------------------------------------- describe "responding to GET new" do it "should expose a new campaign as @campaign" do @campaign = Campaign.new(:user => current_user, :access => Setting.default_access) xhr :get, :new assigns[:campaign].attributes.should == @campaign.attributes response.should render_template("campaigns/new") end it "should create related object when necessary" do @lead = FactoryGirl.create(:lead, :id => 42) xhr :get, :new, :related => "lead_42" assigns[:lead].should == @lead end end # GET /campaigns/1/edit AJAX #---------------------------------------------------------------------------- describe "responding to GET edit" do it "should expose the requested campaign as @campaign and render [edit] template" do @campaign = FactoryGirl.create(:campaign, :id => 42, :user => current_user) xhr :get, :edit, :id => 42 assigns[:campaign].should == @campaign response.should render_template("campaigns/edit") end it "should find previous campaign as necessary" do @campaign = FactoryGirl.create(:campaign, :id => 42) @previous = FactoryGirl.create(:campaign, :id => 99) xhr :get, :edit, :id => 42, :previous => 99 assigns[:campaign].should == @campaign assigns[:previous].should == @previous end describe "(campaign got deleted or is otherwise unavailable)" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy xhr :get, :edit, :id => @campaign.id flash[:warning].should_not == nil response.body.should == "window.location.reload();" end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, :user => FactoryGirl.create(:user), :access => "Private") xhr :get, :edit, :id => @private.id flash[:warning].should_not == nil response.body.should == "window.location.reload();" end end describe "(previous campaign got deleted or is otherwise unavailable)" do before(:each) do @campaign = FactoryGirl.create(:campaign, :user => current_user) @previous = FactoryGirl.create(:campaign, :user => FactoryGirl.create(:user)) end it "should notify the view if previous campaign got deleted" do @previous.destroy xhr :get, :edit, :id => @campaign.id, :previous => @previous.id flash[:warning].should == nil # no warning, just silently remove the div assigns[:previous].should == @previous.id response.should render_template("campaigns/edit") end it "should notify the view if previous campaign got protected" do @previous.update_attribute(:access, "Private") xhr :get, :edit, :id => @campaign.id, :previous => @previous.id flash[:warning].should == nil assigns[:previous].should == @previous.id response.should render_template("campaigns/edit") end end end # POST /campaigns # POST /campaigns.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST create" do describe "with valid params" do it "should expose a newly created campaign as @campaign and render [create] template" do @campaign = FactoryGirl.build(:campaign, :name => "Hello", :user => current_user) Campaign.stub(:new).and_return(@campaign) xhr :post, :create, :campaign => { :name => "Hello" } assigns(:campaign).should == @campaign response.should render_template("campaigns/create") end it "should get data to update campaign sidebar" do @campaign = FactoryGirl.build(:campaign, :name => "Hello", :user => current_user) Campaign.stub(:new).and_return(@campaign) xhr :post, :create, :campaign => { :name => "Hello" } assigns[:campaign_status_total].should be_instance_of(HashWithIndifferentAccess) end it "should reload campaigns to update pagination" do @campaign = FactoryGirl.build(:campaign, :user => current_user) Campaign.stub(:new).and_return(@campaign) xhr :post, :create, :campaign => { :name => "Hello" } assigns[:campaigns].should == [ @campaign ] end it "should add a new comment to the newly created campaign when specified" do @campaign = FactoryGirl.build(:campaign, :name => "Hello world", :user => current_user) Campaign.stub(:new).and_return(@campaign) xhr :post, :create, :campaign => { :name => "Hello world" }, :comment_body => "Awesome comment is awesome" @campaign.reload.comments.map(&:comment).should include("Awesome comment is awesome") end end describe "with invalid params" do it "should expose a newly created but unsaved campaign as @campaign and still render [create] template" do @campaign = FactoryGirl.build(:campaign, :id => nil, :name => nil, :user => current_user) Campaign.stub(:new).and_return(@campaign) xhr :post, :create, :campaign => nil assigns(:campaign).should == @campaign response.should render_template("campaigns/create") end end end # PUT /campaigns/1 # PUT /campaigns/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT update" do describe "with valid params" do it "should update the requested campaign and render [update] template" do @campaign = FactoryGirl.create(:campaign, :id => 42, :name => "Bye") xhr :put, :update, :id => 42, :campaign => { :name => "Hello" } @campaign.reload.name.should == "Hello" assigns(:campaign).should == @campaign response.should render_template("campaigns/update") end it "should get data for campaigns sidebar when called from Campaigns index" do @campaign = FactoryGirl.create(:campaign, :id => 42) request.env["HTTP_REFERER"] = "http://localhost/campaigns" xhr :put, :update, :id => 42, :campaign => { :name => "Hello" } assigns(:campaign).should == @campaign assigns[:campaign_status_total].should be_instance_of(HashWithIndifferentAccess) end it "should update campaign permissions when sharing with specific users" do @campaign = FactoryGirl.create(:campaign, :id => 42, :access => "Public") he = FactoryGirl.create(:user, :id => 7) she = FactoryGirl.create(:user, :id => 8) xhr :put, :update, :id => 42, :campaign => { :name => "Hello", :access => "Shared", :user_ids => %w(7 8) } assigns[:campaign].access.should == "Shared" assigns[:campaign].user_ids.sort.should == [ 7, 8 ] end describe "campaign got deleted or otherwise unavailable" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy xhr :put, :update, :id => @campaign.id flash[:warning].should_not == nil response.body.should == "window.location.reload();" end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, :user => FactoryGirl.create(:user), :access => "Private") xhr :put, :update, :id => @private.id flash[:warning].should_not == nil response.body.should == "window.location.reload();" end end end describe "with invalid params" do it "should not update the requested campaign, but still expose it as @campaign and still render [update] template" do @campaign = FactoryGirl.create(:campaign, :id => 42, :name => "Hello", :user => current_user) xhr :put, :update, :id => 42, :campaign => { :name => nil } @campaign.reload.name.should == "Hello" assigns(:campaign).should == @campaign response.should render_template("campaigns/update") end end end # DELETE /campaigns/1 # DELETE /campaigns/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to DELETE destroy" do before(:each) do @campaign = FactoryGirl.create(:campaign, :user => current_user) end describe "AJAX request" do it "should destroy the requested campaign and render [destroy] template" do @another_campaign = FactoryGirl.create(:campaign, :user => current_user) xhr :delete, :destroy, :id => @campaign.id assigns[:campaigns].should == [ @another_campaign ] lambda { Campaign.find(@campaign) }.should raise_error(ActiveRecord::RecordNotFound) response.should render_template("campaigns/destroy") end it "should get data for campaigns sidebar" do xhr :delete, :destroy, :id => @campaign.id assigns[:campaign_status_total].should be_instance_of(HashWithIndifferentAccess) end it "should try previous page and render index action if current page has no campaigns" do session[:campaigns_current_page] = 42 xhr :delete, :destroy, :id => @campaign.id session[:campaigns_current_page].should == 41 response.should render_template("campaigns/index") end it "should render index action when deleting last campaign" do session[:campaigns_current_page] = 1 xhr :delete, :destroy, :id => @campaign.id session[:campaigns_current_page].should == 1 response.should render_template("campaigns/index") end describe "campaign got deleted or otherwise unavailable" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy xhr :delete, :destroy, :id => @campaign.id flash[:warning].should_not == nil response.body.should == "window.location.reload();" end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, :user => FactoryGirl.create(:user), :access => "Private") xhr :delete, :destroy, :id => @private.id flash[:warning].should_not == nil response.body.should == "window.location.reload();" end end end describe "HTML request" do it "should redirect to Campaigns index when a campaign gets deleted from its landing page" do delete :destroy, :id => @campaign.id flash[:notice].should_not == nil response.should redirect_to(campaigns_path) end it "should redirect to campaign index with the flash message is the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, :user => current_user) @campaign.destroy delete :destroy, :id => @campaign.id flash[:warning].should_not == nil response.should redirect_to(campaigns_path) end it "should redirect to campaign index with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, :user => FactoryGirl.create(:user), :access => "Private") delete :destroy, :id => @private.id flash[:warning].should_not == nil response.should redirect_to(campaigns_path) end end end # PUT /campaigns/1/attach # PUT /campaigns/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, :asset => nil) end it_should_behave_like("attach") end describe "leads" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:lead, :campaign => nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:opportunity, :campaign => nil) end it_should_behave_like("attach") end end # PUT /campaigns/1/attach # PUT /campaigns/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, :asset => nil) end it_should_behave_like("attach") end describe "leads" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:lead, :campaign => nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:opportunity, :campaign => nil) end it_should_behave_like("attach") end end # POST /campaigns/1/discard # POST /campaigns/1/discard.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST discard" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, :asset => @model) end it_should_behave_like("discard") end describe "leads" do before do @attachment = FactoryGirl.create(:lead) @model = FactoryGirl.create(:campaign) @model.leads << @attachment end it_should_behave_like("discard") end describe "opportunities" do before do @attachment = FactoryGirl.create(:opportunity) @model = FactoryGirl.create(:campaign) @model.opportunities << @attachment end it_should_behave_like("discard") end end # POST /campaigns/auto_complete/query AJAX #---------------------------------------------------------------------------- describe "responding to POST auto_complete" do before(:each) do @auto_complete_matches = [ FactoryGirl.create(:campaign, :name => "Hello World", :user => current_user) ] end it_should_behave_like("auto complete") end # GET /campaigns/redraw AJAX #---------------------------------------------------------------------------- describe "responding to GET redraw" do it "should save user selected campaign preference" do xhr :get, :redraw, :per_page => 42, :view => "brief", :sort_by => "name" current_user.preference[:campaigns_per_page].should == "42" current_user.preference[:campaigns_index_view].should == "brief" current_user.preference[:campaigns_sort_by].should == "campaigns.name ASC" end it "should reset current page to 1" do xhr :get, :redraw, :per_page => 42, :view => "brief", :sort_by => "name" session[:campaigns_current_page].should == 1 end it "should select @campaigns and render [index] template" do @campaigns = [ FactoryGirl.create(:campaign, :name => "A", :user => current_user), FactoryGirl.create(:campaign, :name => "B", :user => current_user) ] xhr :get, :redraw, :per_page => 1, :sort_by => "name" assigns(:campaigns).should == [ @campaigns.first ] response.should render_template("campaigns/index") end end # POST /campaigns/filter AJAX #---------------------------------------------------------------------------- describe "responding to POST filter" do it "should expose filtered campaigns as @campaigns and render [index] template" do session[:campaigns_filter] = "planned,started" @campaigns = [ FactoryGirl.create(:campaign, :status => "completed", :user => current_user) ] xhr :post, :filter, :status => "completed" assigns(:campaigns).should == @campaigns response.should render_template("campaigns/index") end it "should reset current page to 1" do @campaigns = [] xhr :post, :filter, :status => "completed" session[:campaigns_current_page].should == 1 end end end
mit
Skyscanner/kong
spec/integration/admin_api/route_helpers_spec.lua
785
local route_helpers = require "kong.api.route_helpers" describe("Route Helpers", function() it("should return the hostname", function() assert.truthy(route_helpers.get_hostname()) end) it("should return parse the nginx status", function() local status = "Active connections: 33 \nserver accepts handled requests\n 3 5 7 \nReading: 314 Writing: 1 Waiting: 2 \n" local res = route_helpers.parse_status(status) assert.are.equal(33, res.connections_active) assert.are.equal(3, res.connections_accepted) assert.are.equal(5, res.connections_handled) assert.are.equal(7, res.total_requests) assert.are.equal(314, res.connections_reading) assert.are.equal(1, res.connections_writing) assert.are.equal(2, res.connections_waiting) end) end)
mit
conceptofproof/z3
src/api/dotnet/AST.cs
8180
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: AST.cs Abstract: Z3 Managed API: ASTs Author: Christoph Wintersteiger (cwinter) 2012-03-16 Notes: --*/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace Microsoft.Z3 { /// <summary> /// The abstract syntax tree (AST) class. /// </summary> [ContractVerification(true)] public class AST : Z3Object, IComparable { /// <summary> /// Comparison operator. /// </summary> /// <param name="a">An AST</param> /// <param name="b">An AST</param> /// <returns>True if <paramref name="a"/> and <paramref name="b"/> are from the same context /// and represent the same sort; false otherwise.</returns> public static bool operator ==(AST a, AST b) { return Object.ReferenceEquals(a, b) || (!Object.ReferenceEquals(a, null) && !Object.ReferenceEquals(b, null) && a.Context.nCtx == b.Context.nCtx && Native.Z3_is_eq_ast(a.Context.nCtx, a.NativeObject, b.NativeObject) != 0); } /// <summary> /// Comparison operator. /// </summary> /// <param name="a">An AST</param> /// <param name="b">An AST</param> /// <returns>True if <paramref name="a"/> and <paramref name="b"/> are not from the same context /// or represent different sorts; false otherwise.</returns> public static bool operator !=(AST a, AST b) { return !(a == b); } /// <summary> /// Object comparison. /// </summary> public override bool Equals(object o) { AST casted = o as AST; if (casted == null) return false; return this == casted; } /// <summary> /// Object Comparison. /// </summary> /// <param name="other">Another AST</param> /// <returns>Negative if the object should be sorted before <paramref name="other"/>, positive if after else zero.</returns> public virtual int CompareTo(object other) { if (other == null) return 1; AST oAST = other as AST; if (oAST == null) return 1; else { if (Id < oAST.Id) return -1; else if (Id > oAST.Id) return +1; else return 0; } } /// <summary> /// The AST's hash code. /// </summary> /// <returns>A hash code</returns> public override int GetHashCode() { return (int)Native.Z3_get_ast_hash(Context.nCtx, NativeObject); } /// <summary> /// A unique identifier for the AST (unique among all ASTs). /// </summary> public uint Id { get { return Native.Z3_get_ast_id(Context.nCtx, NativeObject); } } /// <summary> /// Translates (copies) the AST to the Context <paramref name="ctx"/>. /// </summary> /// <param name="ctx">A context</param> /// <returns>A copy of the AST which is associated with <paramref name="ctx"/></returns> public AST Translate(Context ctx) { Contract.Requires(ctx != null); Contract.Ensures(Contract.Result<AST>() != null); if (ReferenceEquals(Context, ctx)) return this; else return new AST(ctx, Native.Z3_translate(Context.nCtx, NativeObject, ctx.nCtx)); } /// <summary> /// The kind of the AST. /// </summary> public Z3_ast_kind ASTKind { get { return (Z3_ast_kind)Native.Z3_get_ast_kind(Context.nCtx, NativeObject); } } /// <summary> /// Indicates whether the AST is an Expr /// </summary> public bool IsExpr { get { switch (ASTKind) { case Z3_ast_kind.Z3_APP_AST: case Z3_ast_kind.Z3_NUMERAL_AST: case Z3_ast_kind.Z3_QUANTIFIER_AST: case Z3_ast_kind.Z3_VAR_AST: return true; default: return false; } } } /// <summary> /// Indicates whether the AST is an application /// </summary> public bool IsApp { get { return this.ASTKind == Z3_ast_kind.Z3_APP_AST; } } /// <summary> /// Indicates whether the AST is a BoundVariable /// </summary> public bool IsVar { get { return this.ASTKind == Z3_ast_kind.Z3_VAR_AST; } } /// <summary> /// Indicates whether the AST is a Quantifier /// </summary> public bool IsQuantifier { get { return this.ASTKind == Z3_ast_kind.Z3_QUANTIFIER_AST; } } /// <summary> /// Indicates whether the AST is a Sort /// </summary> public bool IsSort { get { return this.ASTKind == Z3_ast_kind.Z3_SORT_AST; } } /// <summary> /// Indicates whether the AST is a FunctionDeclaration /// </summary> public bool IsFuncDecl { get { return this.ASTKind == Z3_ast_kind.Z3_FUNC_DECL_AST; } } /// <summary> /// A string representation of the AST. /// </summary> public override string ToString() { return Native.Z3_ast_to_string(Context.nCtx, NativeObject); } /// <summary> /// A string representation of the AST in s-expression notation. /// </summary> public string SExpr() { Contract.Ensures(Contract.Result<string>() != null); return Native.Z3_ast_to_string(Context.nCtx, NativeObject); } #region Internal internal AST(Context ctx) : base(ctx) { Contract.Requires(ctx != null); } internal AST(Context ctx, IntPtr obj) : base(ctx, obj) { Contract.Requires(ctx != null); } internal class DecRefQueue : IDecRefQueue { public DecRefQueue() : base() { } public DecRefQueue(uint move_limit) : base(move_limit) { } internal override void IncRef(Context ctx, IntPtr obj) { Native.Z3_inc_ref(ctx.nCtx, obj); } internal override void DecRef(Context ctx, IntPtr obj) { Native.Z3_dec_ref(ctx.nCtx, obj); } }; internal override void IncRef(IntPtr o) { // Console.WriteLine("AST IncRef()"); if (Context == null || o == IntPtr.Zero) return; Context.AST_DRQ.IncAndClear(Context, o); base.IncRef(o); } internal override void DecRef(IntPtr o) { // Console.WriteLine("AST DecRef()"); if (Context == null || o == IntPtr.Zero) return; Context.AST_DRQ.Add(o); base.DecRef(o); } internal static AST Create(Context ctx, IntPtr obj) { Contract.Requires(ctx != null); Contract.Ensures(Contract.Result<AST>() != null); switch ((Z3_ast_kind)Native.Z3_get_ast_kind(ctx.nCtx, obj)) { case Z3_ast_kind.Z3_FUNC_DECL_AST: return new FuncDecl(ctx, obj); case Z3_ast_kind.Z3_QUANTIFIER_AST: return new Quantifier(ctx, obj); case Z3_ast_kind.Z3_SORT_AST: return Sort.Create(ctx, obj); case Z3_ast_kind.Z3_APP_AST: case Z3_ast_kind.Z3_NUMERAL_AST: case Z3_ast_kind.Z3_VAR_AST: return Expr.Create(ctx, obj); default: throw new Z3Exception("Unknown AST kind"); } } #endregion } }
mit
opdss/dokuWiki
inc/fetch.functions.php
5322
<?php /** * Functions used by lib/exe/fetch.php * (not included by other parts of dokuwiki) */ /** * Set headers and send the file to the client * * The $cache parameter influences how long files may be kept in caches, the $public parameter * influences if this caching may happen in public proxis or in the browser cache only FS#2734 * * This function will abort the current script when a 304 is sent or file sending is handled * through x-sendfile * * @author Andreas Gohr <andi@splitbrain.org> * @author Ben Coburn <btcoburn@silicodon.net> * @author Gerry Weissbach <dokuwiki@gammaproduction.de> * @param string $file local file to send * @param string $mime mime type of the file * @param bool $dl set to true to force a browser download * @param int $cache remaining cache time in seconds (-1 for $conf['cache'], 0 for no-cache) * @param bool $public is this a public ressource or a private one? * @param string $orig original file to send - the file name will be used for the Content-Disposition */ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null) { global $conf; // send mime headers header("Content-Type: $mime"); // calculate cache times if($cache == -1) { $maxage = max($conf['cachetime'], 3600); // cachetime or one hour $expires = time() + $maxage; } else if($cache > 0) { $maxage = $cache; // given time $expires = time() + $maxage; } else { // $cache == 0 $maxage = 0; $expires = 0; // 1970-01-01 } // smart http caching headers if($maxage) { if($public) { // cache publically header('Expires: '.gmdate("D, d M Y H:i:s", $expires).' GMT'); header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.$maxage); header('Pragma: public'); } else { // cache in browser header('Expires: '.gmdate("D, d M Y H:i:s", $expires).' GMT'); header('Cache-Control: private, no-transform, max-age='.$maxage); header('Pragma: no-cache'); } } else { // no cache at all header('Expires: Thu, 01 Jan 1970 00:00:00 GMT'); header('Cache-Control: no-cache, no-transform'); header('Pragma: no-cache'); } //send important headers first, script stops here if '304 Not Modified' response $fmtime = @filemtime($file); http_conditionalRequest($fmtime); // Use the current $file if is $orig is not set. if ( $orig == null ) { $orig = $file; } //download or display? if($dl) { header('Content-Disposition: attachment; filename="'.utf8_basename($orig).'";'); } else { header('Content-Disposition: inline; filename="'.utf8_basename($orig).'";'); } //use x-sendfile header to pass the delivery to compatible webservers http_sendfile($file); // send file contents $fp = @fopen($file, "rb"); if($fp) { http_rangeRequest($fp, filesize($file), $mime); } else { http_status(500); print "Could not read $file - bad permissions?"; } } /** * Check for media for preconditions and return correct status code * * READ: MEDIA, MIME, EXT, CACHE * WRITE: MEDIA, FILE, array( STATUS, STATUSMESSAGE ) * * @author Gerry Weissbach <gerry.w@gammaproduction.de> * @param string $media reference to the media id * @param string $file reference to the file variable * @param string $rev * @param int $width * @param int $height * @return array(STATUS, STATUSMESSAGE) */ function checkFileStatus(&$media, &$file, $rev = '', $width=0, $height=0) { global $MIME, $EXT, $CACHE, $INPUT; //media to local file if(media_isexternal($media)) { //check token for external image and additional for resized and cached images if(media_get_token($media, $width, $height) !== $INPUT->str('tok')) { return array(412, 'Precondition Failed'); } //handle external images if(strncmp($MIME, 'image/', 6) == 0) $file = media_get_from_URL($media, $EXT, $CACHE); if(!$file) { //download failed - redirect to original URL return array(302, $media); } } else { $media = cleanID($media); if(empty($media)) { return array(400, 'Bad request'); } // check token for resized images if (($width || $height) && media_get_token($media, $width, $height) !== $INPUT->str('tok')) { return array(412, 'Precondition Failed'); } //check permissions (namespace only) if(auth_quickaclcheck(getNS($media).':X') < AUTH_READ) { return array(403, 'Forbidden'); } $file = mediaFN($media, $rev); } //check file existance if(!@file_exists($file)) { return array(404, 'Not Found'); } return array(200, null); } /** * Returns the wanted cachetime in seconds * * Resolves named constants * * @author Andreas Gohr <andi@splitbrain.org> */ function calc_cache($cache) { global $conf; if(strtolower($cache) == 'nocache') return 0; //never cache if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache return -1; //cache endless }
gpl-2.0
kosmosby/medicine-prof
components/com_openfire/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/geocoding/data/en/1717.php
6485
<?php /** * This file is automatically @generated by {@link GeneratePhonePrefixData}. * Please don't modify it directly. */ return array ( 1717 => 'Pennsylvania', 1717207 => 'Lancaster, PA', 1717217 => 'Chambersburg, PA', 1717218 => 'Carlisle, PA', 1717221 => 'Harrisburg, PA', 1717225 => 'Spring Grove, PA', 1717228 => 'Lebanon, PA', 1717230 => 'Harrisburg, PA', 1717231 => 'Harrisburg, PA', 1717232 => 'Harrisburg, PA', 1717233 => 'Harrisburg, PA', 1717234 => 'Harrisburg, PA', 1717236 => 'Harrisburg, PA', 1717237 => 'Harrisburg, PA', 1717238 => 'Harrisburg, PA', 1717240 => 'Carlisle, PA', 1717241 => 'Carlisle, PA', 1717242 => 'Lewistown, PA', 1717243 => 'Carlisle, PA', 1717244 => 'Red Lion, PA', 1717245 => 'Carlisle, PA', 1717246 => 'Red Lion, PA', 1717248 => 'Lewistown, PA', 1717249 => 'Carlisle, PA', 1717252 => 'Wrightsville, PA', 1717255 => 'Harrisburg, PA', 1717258 => 'Carlisle, PA', 1717259 => 'East Berlin, PA', 1717260 => 'Harrisburg, PA', 1717261 => 'Chambersburg, PA', 1717262 => 'Chambersburg, PA', 1717263 => 'Chambersburg, PA', 1717264 => 'Chambersburg, PA', 1717267 => 'Chambersburg, PA', 1717270 => 'Lebanon, PA', 1717272 => 'Lebanon, PA', 1717273 => 'Lebanon, PA', 1717274 => 'Lebanon, PA', 1717279 => 'Lebanon, PA', 1717290 => 'Lancaster, PA', 1717291 => 'Lancaster, PA', 1717292 => 'Dover, PA', 1717293 => 'Lancaster, PA', 1717295 => 'Lancaster, PA', 1717299 => 'Lancaster, PA', 1717328 => 'Mercersburg, PA', 1717334 => 'Gettysburg, PA', 1717335 => 'Denver, PA', 1717337 => 'Gettysburg, PA', 1717338 => 'Gettysburg, PA', 1717339 => 'Gettysburg, PA', 1717352 => 'Fayetteville, PA', 1717354 => 'New Holland, PA', 1717355 => 'New Holland, PA', 1717359 => 'Littlestown, PA', 1717361 => 'Elizabethtown, PA', 1717362 => 'Elizabethville, PA', 1717367 => 'Elizabethtown, PA', 1717375 => 'Chambersburg, PA', 1717390 => 'Lancaster, PA', 1717391 => 'Lancaster, PA', 1717392 => 'Lancaster, PA', 1717393 => 'Lancaster, PA', 1717394 => 'Lancaster, PA', 1717396 => 'Lancaster, PA', 1717397 => 'Lancaster, PA', 1717399 => 'Lancaster, PA', 1717412 => 'Harrisburg, PA', 1717423 => 'Newburg, PA', 1717426 => 'Marietta, PA', 1717431 => 'Lancaster, PA', 1717432 => 'Dillsburg, PA', 1717435 => 'Lancaster, PA', 1717436 => 'Mifflintown, PA', 1717441 => 'Harrisburg, PA', 1717442 => 'Gap, PA', 1717444 => 'Liverpool, PA', 1717456 => 'Delta, PA', 1717458 => 'Mechanicsburg, PA', 1717463 => 'McAlisterville, PA', 1717464 => 'Willow Street, PA', 1717469 => 'Grantville, PA', 1717477 => 'Shippensburg, PA', 1717485 => 'McConnellsburg, PA', 1717486 => 'Mount Holly Springs, PA', 1717492 => 'Mount Joy, PA', 1717502 => 'Dillsburg, PA', 1717509 => 'Lancaster, PA', 1717517 => 'Lancaster, PA', 1717519 => 'Lancaster, PA', 1717520 => 'Hershey, PA', 1717525 => 'Harrisburg, PA', 1717526 => 'Harrisburg, PA', 1717528 => 'York Springs, PA', 1717530 => 'Shippensburg, PA', 1717531 => 'Hershey, PA', 1717532 => 'Shippensburg, PA', 1717533 => 'Hershey, PA', 1717534 => 'Hershey, PA', 1717540 => 'Harrisburg, PA', 1717541 => 'Harrisburg, PA', 1717544 => 'Lancaster, PA', 1717545 => 'Harrisburg, PA', 1717548 => 'Peach Bottom, PA', 1717558 => 'Harrisburg, PA', 1717560 => 'Lancaster, PA', 1717561 => 'Harrisburg, PA', 1717564 => 'Harrisburg, PA', 1717566 => 'Hummelstown, PA', 1717567 => 'Newport, PA', 1717569 => 'Lancaster, PA', 1717581 => 'Lancaster, PA', 1717582 => 'New Bloomfield, PA', 1717589 => 'Millerstown, PA', 1717591 => 'Mechanicsburg, PA', 1717597 => 'Greencastle, PA', 1717600 => 'York, PA', 1717624 => 'New Oxford, PA', 1717625 => 'Lititz, PA', 1717626 => 'Lititz, PA', 1717627 => 'Lititz, PA', 1717630 => 'Hanover, PA', 1717632 => 'Hanover, PA', 1717633 => 'Hanover, PA', 1717635 => 'Harrisburg, PA', 1717637 => 'Hanover, PA', 1717642 => 'Fairfield, PA', 1717646 => 'Hanover, PA', 1717647 => 'Tower City, PA', 1717650 => 'York, PA', 1717651 => 'Harrisburg, PA', 1717652 => 'Harrisburg, PA', 1717653 => 'Mount Joy, PA', 1717656 => 'Leola, PA', 1717657 => 'Harrisburg, PA', 1717664 => 'Manheim, PA', 1717665 => 'Manheim, PA', 1717667 => 'Reedsville, PA', 1717671 => 'Harrisburg, PA', 1717677 => 'Biglerville, PA', 1717684 => 'Columbia, PA', 1717691 => 'Mechanicsburg, PA', 1717692 => 'Millersburg, PA', 1717695 => 'Harrisburg, PA', 1717697 => 'Mechanicsburg, PA', 1717699 => 'York, PA', 1717709 => 'Chambersburg, PA', 1717718 => 'York, PA', 1717721 => 'Ephrata, PA', 1717724 => 'Harrisburg, PA', 1717728 => 'Enola, PA', 1717732 => 'Enola, PA', 1717733 => 'Ephrata, PA', 1717735 => 'Lancaster, PA', 1717737 => 'Camp Hill, PA', 1717738 => 'Ephrata, PA', 1717741 => 'York, PA', 1717747 => 'York, PA', 1717749 => 'Waynesboro, PA', 1717751 => 'York, PA', 1717755 => 'York, PA', 1717757 => 'York, PA', 1717761 => 'Camp Hill, PA', 1717762 => 'Waynesboro, PA', 1717763 => 'Camp Hill, PA', 1717764 => 'York, PA', 1717765 => 'Waynesboro, PA', 1717766 => 'Mechanicsburg, PA', 1717767 => 'York, PA', 1717771 => 'York, PA', 1717774 => 'New Cumberland, PA', 1717776 => 'Newville, PA', 1717782 => 'Harrisburg, PA', 1717786 => 'Quarryville, PA', 1717787 => 'Harrisburg, PA', 1717789 => 'Loysville, PA', 1717790 => 'Mechanicsburg, PA', 1717791 => 'Mechanicsburg, PA', 1717792 => 'York, PA', 1717793 => 'York, PA', 1717795 => 'Mechanicsburg, PA', 1717796 => 'Mechanicsburg, PA', 1717812 => 'York, PA', 1717832 => 'Palmyra, PA', 1717834 => 'Duncannon, PA', 1717838 => 'Palmyra, PA', 1717840 => 'York, PA', 1717843 => 'York, PA', 1717845 => 'York, PA', 1717846 => 'York, PA', 1717848 => 'York, PA', 1717849 => 'York, PA', 1717851 => 'York, PA', 1717852 => 'York, PA', 1717854 => 'York, PA', 1717866 => 'Myerstown, PA', 1717867 => 'Annville, PA', 1717896 => 'Halifax, PA', 1717899 => 'McVeytown, PA', 1717901 => 'Harrisburg, PA', 1717909 => 'Harrisburg, PA', 1717920 => 'Harrisburg, PA', 1717921 => 'Dauphin, PA', 1717927 => 'Brogue, PA', 1717935 => 'Belleville, PA', 1717944 => 'Middletown, PA', 1717945 => 'Lancaster, PA', 1717948 => 'Middletown, PA', 1717957 => 'Marysville, PA', 1717964 => 'Mount Gretna, PA', 1717975 => 'Camp Hill, PA', 1717993 => 'Stewartstown, PA', );
gpl-2.0
UstadMobile/eXePUB
twisted/protocols/imap4.py
270
from twisted.python import util util.moduleMovedForSplit('twisted.protocols.imap4', 'twisted.mail.imap4', 'IMAP4 protocol support', 'Mail', 'http://twistedmatrix.com/projects/mail', globals())
gpl-2.0
gripped/xbmc
xbmc/peripherals/bus/linux/PeripheralBusUSBLibUdev.cpp
6612
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "PeripheralBusUSBLibUdev.h" #include "peripherals/Peripherals.h" extern "C" { #include <libudev.h> } #include <poll.h> #include "utils/log.h" #ifndef USB_CLASS_PER_INTERFACE #define USB_CLASS_PER_INTERFACE 0 #endif #ifndef USB_CLASS_AUDIO #define USB_CLASS_AUDIO 1 #endif #ifndef USB_CLASS_COMM #define USB_CLASS_COMM 2 #endif #ifndef USB_CLASS_HID #define USB_CLASS_HID 3 #endif #ifndef USB_CLASS_PHYSICAL #define USB_CLASS_PHYSICAL 5 #endif #ifndef USB_CLASS_PTP #define USB_CLASS_PTP 6 #endif #ifndef USB_CLASS_PRINTER #define USB_CLASS_PRINTER 7 #endif #ifndef USB_CLASS_MASS_STORAGE #define USB_CLASS_MASS_STORAGE 8 #endif #ifndef USB_CLASS_HUB #define USB_CLASS_HUB 9 #endif #ifndef USB_CLASS_DATA #define USB_CLASS_DATA 10 #endif #ifndef USB_CLASS_APP_SPEC #define USB_CLASS_APP_SPEC 0xfe #endif #ifndef USB_CLASS_VENDOR_SPEC #define USB_CLASS_VENDOR_SPEC 0xff #endif using namespace PERIPHERALS; CPeripheralBusUSB::CPeripheralBusUSB(CPeripherals *manager) : CPeripheralBus("PeripBusUSBUdev", manager, PERIPHERAL_BUS_USB) { /* the Process() method in this class overrides the one in CPeripheralBus, so leave this set to true */ m_bNeedsPolling = true; m_udev = NULL; m_udevMon = NULL; if (!(m_udev = udev_new())) { CLog::Log(LOGERROR, "%s - failed to allocate udev context", __FUNCTION__); return; } /* set up a devices monitor that listen for any device change */ m_udevMon = udev_monitor_new_from_netlink(m_udev, "udev"); udev_monitor_enable_receiving(m_udevMon); CLog::Log(LOGDEBUG, "%s - initialised udev monitor", __FUNCTION__); } CPeripheralBusUSB::~CPeripheralBusUSB(void) { StopThread(true); udev_monitor_unref(m_udevMon); udev_unref(m_udev); } bool CPeripheralBusUSB::PerformDeviceScan(PeripheralScanResults &results) { struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device *dev(NULL), *parent(NULL); enumerate = udev_enumerate_new(m_udev); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); bool bContinue(true); CStdString strPath, strClass; udev_list_entry_foreach(dev_list_entry, devices) { strPath = udev_list_entry_get_name(dev_list_entry); if (strPath.empty()) bContinue = false; if (bContinue) { if (!(parent = udev_device_new_from_syspath(m_udev, strPath))) bContinue = false; } if (bContinue) { dev = udev_device_get_parent(udev_device_get_parent(parent)); if (!dev || !udev_device_get_sysattr_value(dev,"idVendor") || !udev_device_get_sysattr_value(dev, "idProduct")) bContinue = false; } if (bContinue) { strClass = udev_device_get_sysattr_value(dev, "bDeviceClass"); if (strClass.empty()) bContinue = false; } if (bContinue) { int iClass = PeripheralTypeTranslator::HexStringToInt(strClass.c_str()); if (iClass == USB_CLASS_PER_INTERFACE) { //TODO just assume this is a HID device for now, since the only devices that we're currently // interested in are HID devices iClass = USB_CLASS_HID; } PeripheralScanResult result(m_type); result.m_iVendorId = PeripheralTypeTranslator::HexStringToInt(udev_device_get_sysattr_value(dev, "idVendor")); result.m_iProductId = PeripheralTypeTranslator::HexStringToInt(udev_device_get_sysattr_value(dev, "idProduct")); result.m_type = GetType(iClass); result.m_strLocation = udev_device_get_syspath(dev); result.m_iSequence = GetNumberOfPeripheralsWithId(result.m_iVendorId, result.m_iProductId); if (!results.ContainsResult(result)) results.m_results.push_back(result); } bContinue = true; if (parent) { /* unref the _parent_ device */ udev_device_unref(parent); parent = NULL; } } /* Free the enumerator object */ udev_enumerate_unref(enumerate); return true; } const PeripheralType CPeripheralBusUSB::GetType(int iDeviceClass) { switch (iDeviceClass) { case USB_CLASS_HID: return PERIPHERAL_HID; case USB_CLASS_COMM: return PERIPHERAL_NIC; case USB_CLASS_MASS_STORAGE: return PERIPHERAL_DISK; case USB_CLASS_PER_INTERFACE: case USB_CLASS_AUDIO: case USB_CLASS_PRINTER: case USB_CLASS_PTP: case USB_CLASS_HUB: case USB_CLASS_DATA: case USB_CLASS_VENDOR_SPEC: default: return PERIPHERAL_UNKNOWN; } } void CPeripheralBusUSB::Process(void) { bool bUpdated(false); ScanForDevices(); while (!m_bStop) { bUpdated = WaitForUpdate(); if (bUpdated && !m_bStop) ScanForDevices(); } m_bIsStarted = false; } void CPeripheralBusUSB::Clear(void) { StopThread(false); CPeripheralBus::Clear(); } bool CPeripheralBusUSB::WaitForUpdate() { int udevFd = udev_monitor_get_fd(m_udevMon); if (udevFd < 0) { CLog::Log(LOGERROR, "%s - get udev monitor", __FUNCTION__); return false; } /* poll for udev changes */ struct pollfd pollFd; pollFd.fd = udevFd; pollFd.events = POLLIN; int iPollResult; while (!m_bStop && ((iPollResult = poll(&pollFd, 1, 100)) <= 0)) if (errno != EINTR && iPollResult != 0) break; /* the thread is being stopped, so just return false */ if (m_bStop) return false; /* we have to read the message from the queue, even though we're not actually using it */ struct udev_device *dev = udev_monitor_receive_device(m_udevMon); if (dev) udev_device_unref(dev); else { CLog::Log(LOGERROR, "%s - failed to get device from udev_monitor_receive_device()", __FUNCTION__); Clear(); return false; } return true; }
gpl-2.0
nose1980/ACE3
addons/scopes/RscTitles.hpp
2846
class RscText; class RscTitles { class ACE_Scopes_Zeroing { idd = -1; movingEnable = 0; enableSimulation = 1; enableDisplay = 1; onLoad = QUOTE(uiNamespace setVariable [ARR_2(QUOTE(QGVAR(ZeroingDisplay)),_this select 0)];); duration = 1e+011; fadein = 0; fadeout = 0; name = QGVAR(Zeroing); class RscPicture; class RscText; class controls { class ACE_Scopes_Zeroing_BG : RscPicture { idc = 11; type = 0; text = PATHTOF(UI\scopes_bg.paa); style = 48 + 0x800; scale = 1; sizeEx = 1; font = "PuristaMedium"; colorText[] = { 1, 1, 1, 1 }; colorBackground[] = { 1, 1, 1, 1 }; shadow = 1; x = (0.5 - 0.4 / 2) * safezoneW + safezoneX; y = 0 * safezoneH + safezoneY; w = 0.4 * safezoneW; h = 0.3 * safezoneH; }; class ACE_Scopes_Zeroing_Vertical : RscText { idc = 12; type = 0; style = 2; sizeEx = 0.04; lineSpacing = 1; font = "PuristaMedium"; text = ""; colorText[] = { 1, 1, 1, 0.9 }; colorBackground[] = { 1, 0, 0, 0 }; shadow = 0; x = (0.5 - 0.4 / 2 + 0.45*0.4) * safezoneW + safezoneX; y = (0 + 0.19*0.3) * safezoneH + safezoneY; w = 0.04 * safezoneW; h = 0.025 * safezoneH; }; class ACE_Scopes_Zeroing_Horizontal : RscText { idc = 13; type = 0; style = 0; sizeEx = 0.04; lineSpacing = 1; font = "PuristaMedium"; text = ""; colorText[] = { 1, 1, 1, 0.9 }; colorBackground[] = { 1, 0, 0, 0 }; shadow = 0; x = (0.5 - 0.4 / 2 + 0.6*0.4) * safezoneW + safezoneX; y = (0 + 0.47*0.3) * safezoneH + safezoneY; w = 0.04 * safezoneW; h = 0.025 * safezoneH; }; }; }; }; /* class RscInGameUI { class RscUnitInfo; class RscWeaponZeroing : RscUnitInfo { onLoad = QUOTE([ARR_4('onLoad',_this,'RscUnitInfo','IGUI')] call compile preprocessfilelinenumbers 'A3\ui_f\scripts\initDisplay.sqf'; uiNamespace setVariable [ARR_2('ACE_dlgWeaponZeroing', _this select 0)]; ); //onLoad = "[""onLoad"",_this,""RscUnitInfo"",'IGUI'] call compile preprocessfilelinenumbers ""A3\ui_f\scripts\initDisplay.sqf""; uiNamespace setVariable ['ACE_dlgWeaponZeroing', _this select 0];"; }; }; */
gpl-2.0
IBCCW/Replicating-DeepMind
Hybrid/libraries/ale/src/games/supported/Asteroids.cpp
2587
/* ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #include "Asteroids.hpp" #include "../RomUtils.hpp" AsteroidsSettings::AsteroidsSettings() { reset(); } /* create a new instance of the rom */ RomSettings* AsteroidsSettings::clone() const { RomSettings* rval = new AsteroidsSettings(); *rval = *this; return rval; } /* process the latest information from ALE */ void AsteroidsSettings::step(const System& system) { // update the reward reward_t score = getDecimalScore(62, 61, &system); score *= 10; m_reward = score - m_score; m_score = score; // update terminal status int byte = readRam(&system, 60); byte = (byte - (byte & 15)) >> 4; m_terminal = byte < 1; } /* is end of game */ bool AsteroidsSettings::isTerminal() const { return m_terminal; }; /* get the most recently observed reward */ reward_t AsteroidsSettings::getReward() const { return m_reward; } /* is an action part of the minimal set? */ bool AsteroidsSettings::isMinimal(const Action &a) const { switch (a) { case PLAYER_A_NOOP: case PLAYER_A_FIRE: case PLAYER_A_UP: case PLAYER_A_RIGHT: case PLAYER_A_LEFT: case PLAYER_A_DOWN: case PLAYER_A_UPRIGHT: case PLAYER_A_UPLEFT: case PLAYER_A_UPFIRE: case PLAYER_A_RIGHTFIRE: case PLAYER_A_LEFTFIRE: case PLAYER_A_DOWNFIRE: case PLAYER_A_UPRIGHTFIRE: case PLAYER_A_UPLEFTFIRE: return true; default: return false; } } /* reset the state of the game */ void AsteroidsSettings::reset() { m_reward = 0; m_score = 0; m_terminal = false; } /* saves the state of the rom settings */ void AsteroidsSettings::saveState(Serializer & ser) { ser.putInt(m_reward); ser.putInt(m_score); ser.putBool(m_terminal); } // loads the state of the rom settings void AsteroidsSettings::loadState(Deserializer & ser) { m_reward = ser.getInt(); m_score = ser.getInt(); m_terminal = ser.getBool(); }
gpl-3.0
Cerfoglg/cattle
code/framework/object/src/main/java/io/cattle/platform/object/meta/impl/MapRelationshipImpl.java
1490
package io.cattle.platform.object.meta.impl; import io.cattle.platform.object.meta.MapRelationship; import io.cattle.platform.object.meta.Relationship; public class MapRelationshipImpl implements MapRelationship { String name; Class<?> mappingType; Class<?> objectType; Relationship selfRelationship; Relationship otherRelationship; public MapRelationshipImpl(String name, Class<?> mappingType, Class<?> objectType, Relationship selfRelationship, Relationship otherRelationship) { super(); this.name = name; this.mappingType = mappingType; this.objectType = objectType; this.selfRelationship = selfRelationship; this.otherRelationship = otherRelationship; } @Override public boolean isListResult() { return true; } @Override public RelationshipType getRelationshipType() { return RelationshipType.MAP; } @Override public String getName() { return name; } @Override public String getPropertyName() { return selfRelationship.getPropertyName(); } @Override public Class<?> getObjectType() { return objectType; } @Override public Class<?> getMappingType() { return mappingType; } @Override public Relationship getSelfRelationship() { return selfRelationship; } @Override public Relationship getOtherRelationship() { return otherRelationship; } }
apache-2.0
habibiefaried/ryu
ryu/tests/unit/test_utils.py
2450
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import logging import six from nose.tools import eq_ from ryu import utils LOG = logging.getLogger(__name__) class Test_utils(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_hex_array_string(self): """ Test hex_array() with str type. """ expected_result = '0x01 0x02 0x03 0x04' data = b'\x01\x02\x03\x04' eq_(expected_result, utils.hex_array(data)) def test_hex_array_bytearray(self): """ Test hex_array() with bytearray type. """ expected_result = '0x01 0x02 0x03 0x04' data = bytearray(b'\x01\x02\x03\x04') eq_(expected_result, utils.hex_array(data)) def test_hex_array_bytes(self): """ Test hex_array() with bytes type. (Python3 only) """ if six.PY2: return expected_result = '0x01 0x02 0x03 0x04' data = bytes(b'\x01\x02\x03\x04') eq_(expected_result, utils.hex_array(data)) def test_binary_str_string(self): """ Test binary_str() with str type. """ expected_result = '\\x01\\x02\\x03\\x04' data = b'\x01\x02\x03\x04' eq_(expected_result, utils.binary_str(data)) def test_binary_str_bytearray(self): """ Test binary_str() with bytearray type. """ expected_result = '\\x01\\x02\\x03\\x04' data = bytearray(b'\x01\x02\x03\x04') eq_(expected_result, utils.binary_str(data)) def test_binary_str_bytes(self): """ Test binary_str() with bytes type. (Python3 only) """ if six.PY2: return expected_result = '\\x01\\x02\\x03\\x04' data = bytes(b'\x01\x02\x03\x04') eq_(expected_result, utils.binary_str(data))
apache-2.0
SerCeMan/intellij-community
platform/vcs-log/graph-api/src/com/intellij/vcs/log/graph/SimplePrintElement.java
839
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.graph; import org.jetbrains.annotations.NotNull; /** */ public interface SimplePrintElement extends PrintElement { @NotNull Type getType(); enum Type { NODE, UP_ARROW, DOWN_ARROW } }
apache-2.0
liangly/hadoop-common
src/test/system/java/org/apache/hadoop/hdfs/test/system/DNClient.java
2754
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.test.system; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.test.system.process.RemoteProcess; /** * Datanode client for system tests. Assumption of the class is that the * configuration key is set for the configuration key : {@code * DFSConfigKeys.DFS_DATANODE_IPC_ADDRESS_KEY} is set, only the port portion of * the address is used. */ public class DNClient extends HDFSDaemonClient<DNProtocol> { DNProtocol proxy; public DNClient(Configuration conf, RemoteProcess process) throws IOException { super(conf, process); } @Override public void connect() throws IOException { if (isConnected()) { return; } String sockAddrStr = getConf().get(DFSConfigKeys.DFS_DATANODE_IPC_ADDRESS_KEY); if (sockAddrStr == null) { throw new IllegalArgumentException("Datenode IPC address is not set." + "Check if " + DFSConfigKeys.DFS_DATANODE_IPC_ADDRESS_KEY + " is configured."); } String[] splits = sockAddrStr.split(":"); if (splits.length != 2) { throw new IllegalArgumentException( "Datanode IPC address is not correctly configured"); } String port = splits[1]; String sockAddr = getHostName() + ":" + port; InetSocketAddress bindAddr = NetUtils.createSocketAddr(sockAddr); proxy = (DNProtocol) RPC.getProxy(DNProtocol.class, DNProtocol.versionID, bindAddr, getConf()); setConnected(true); } @Override public void disconnect() throws IOException { RPC.stopProxy(proxy); setConnected(false); } @Override protected DNProtocol getProxy() { return proxy; } public Configuration getDatanodeConfig() throws IOException { return getProxy().getDaemonConf(); } }
apache-2.0
fengshao0907/nutz
src/org/nutz/ioc/aop/Aop.java
799
package org.nutz.ioc.aop; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 将一个方法关联到一个或几个切片。 * <p> * 或者说,让一组拦截器控制这个方法。 * <p> * 这个注解接受一组值,每个值,就是一个容器内对象的名称,在 Ioc 容器中,<br> * 你可以任意声明这个对象,只要这个对象实现了 MethodInterceptor 接口 * * @author zozoh(zozohtnt@gmail.com) * * @see org.nutz.aop.MethodInterceptor */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) @Documented public @interface Aop { String[] value(); }
apache-2.0
zdary/intellij-community
python/testData/intentions/PyAnnotateVariableTypeIntentionTest/typeCommentInstanceAttributeClassLevelAssignment_after.py
109
class MyClass: attr = 0 # type: [int] def __init___(self): self.attr = 42 self.attr
apache-2.0
LiveAsynchronousVisualizedArchitecture/lava
TblMaker/fltk/FL/Fl_PNG_Image.H
1252
// // "$Id: Fl_PNG_Image.H 8864 2011-07-19 04:49:30Z greg.ercolano $" // // PNG image header file for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2010 by Bill Spitzak and others. // // This library is free software. Distribution and use rights are outlined in // the file "COPYING" which should have been included with this file. If this // file is missing or damaged, see the license at: // // http://www.fltk.org/COPYING.php // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // /* \file Fl_PNG_Image class . */ #ifndef Fl_PNG_Image_H #define Fl_PNG_Image_H # include "Fl_Image.H" /** The Fl_PNG_Image class supports loading, caching, and drawing of Portable Network Graphics (PNG) image files. The class loads colormapped and full-color images and handles color- and alpha-based transparency. */ class FL_EXPORT Fl_PNG_Image : public Fl_RGB_Image { public: Fl_PNG_Image(const char* filename); Fl_PNG_Image (const char *name_png, const unsigned char *buffer, int datasize); private: void load_png_(const char *name_png, const unsigned char *buffer_png, int datasize); }; #endif // // End of "$Id: Fl_PNG_Image.H 8864 2011-07-19 04:49:30Z greg.ercolano $". //
apache-2.0
bdhess/homebrew-cask
Casks/lazpaint.rb
455
cask 'lazpaint' do version '6.2' sha256 '44f48aee359337f8d5a9fd3b3786f71251dc6b961486b30938a308197e28498e' url "https://downloads.sourceforge.net/lazpaint/lazpaint#{version}_osx32.zip" appcast 'https://sourceforge.net/projects/lazpaint/rss', checkpoint: 'd52c7f467dc51331ce7ad24785f9e4eb3d7e386bf17e98ecfd8454ec0ca68a0a' name 'LazPaint' homepage 'https://sourceforge.net/projects/lazpaint/' license :gpl app 'LazPaint.app' end
bsd-2-clause
was4444/chromium.src
remoting/android/java/src/org/chromium/chromoting/AnimationJob.java
1147
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chromoting; /** * This interface represents an animation job. * The client of AnimationJob is supposed to: * <ul> * <li>Create AnimationJob instances at initialization stage and keep them alive for the whole * life cycle.</li> * <li>Call methods like startAnimation() to start animation. This method is not defined in the * interface since start methods may vary.</li> * <li>In its repaint/animation cycle, call processAnimation() to execute the animation job, and * exit the animation cycle when all animations are finished.</li> * <li>Call abortAnimation() when the animation need to be interrupted.</li> * </ul> */ interface AnimationJob { /** * Processes the animation when it is still active/not finished * @return true if the animation is not finished yet */ boolean processAnimation(); /** * Abort current animation. The animation will be marked as finished */ void abortAnimation(); }
bsd-3-clause
vadimtk/chrome4sdp
third_party/WebKit/Source/modules/crypto/CryptoHistograms.cpp
5396
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "modules/crypto/CryptoHistograms.h" #include "core/frame/UseCounter.h" #include "public/platform/Platform.h" #include "public/platform/WebCryptoAlgorithm.h" #include "public/platform/WebCryptoAlgorithmParams.h" #include "public/platform/WebCryptoKeyAlgorithm.h" namespace blink { static UseCounter::Feature algorithmIdToFeature(WebCryptoAlgorithmId id) { switch (id) { case WebCryptoAlgorithmIdAesCbc: return UseCounter::CryptoAlgorithmAesCbc; case WebCryptoAlgorithmIdHmac: return UseCounter::CryptoAlgorithmHmac; case WebCryptoAlgorithmIdRsaSsaPkcs1v1_5: return UseCounter::CryptoAlgorithmRsaSsaPkcs1v1_5; case WebCryptoAlgorithmIdSha1: return UseCounter::CryptoAlgorithmSha1; case WebCryptoAlgorithmIdSha256: return UseCounter::CryptoAlgorithmSha256; case WebCryptoAlgorithmIdSha384: return UseCounter::CryptoAlgorithmSha384; case WebCryptoAlgorithmIdSha512: return UseCounter::CryptoAlgorithmSha512; case WebCryptoAlgorithmIdAesGcm: return UseCounter::CryptoAlgorithmAesGcm; case WebCryptoAlgorithmIdRsaOaep: return UseCounter::CryptoAlgorithmRsaOaep; case WebCryptoAlgorithmIdAesCtr: return UseCounter::CryptoAlgorithmAesCtr; case WebCryptoAlgorithmIdAesKw: return UseCounter::CryptoAlgorithmAesKw; case WebCryptoAlgorithmIdRsaPss: return UseCounter::CryptoAlgorithmRsaPss; case WebCryptoAlgorithmIdEcdsa: return UseCounter::CryptoAlgorithmEcdsa; case WebCryptoAlgorithmIdEcdh: return UseCounter::CryptoAlgorithmEcdh; case WebCryptoAlgorithmIdHkdf: return UseCounter::CryptoAlgorithmHkdf; case WebCryptoAlgorithmIdPbkdf2: return UseCounter::CryptoAlgorithmPbkdf2; } ASSERT_NOT_REACHED(); return static_cast<UseCounter::Feature>(0); } static void histogramAlgorithmId(ExecutionContext* context, WebCryptoAlgorithmId algorithmId) { UseCounter::Feature feature = algorithmIdToFeature(algorithmId); if (feature) UseCounter::count(context, feature); } void histogramAlgorithm(ExecutionContext* context, const WebCryptoAlgorithm& algorithm) { histogramAlgorithmId(context, algorithm.id()); // Histogram any interesting parameters for the algorithm. For instance // the inner hash for algorithms which include one (HMAC, RSA-PSS, etc) switch (algorithm.paramsType()) { case WebCryptoAlgorithmParamsTypeHmacImportParams: histogramAlgorithm(context, algorithm.hmacImportParams()->hash()); break; case WebCryptoAlgorithmParamsTypeHmacKeyGenParams: histogramAlgorithm(context, algorithm.hmacKeyGenParams()->hash()); break; case WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams: histogramAlgorithm(context, algorithm.rsaHashedKeyGenParams()->hash()); break; case WebCryptoAlgorithmParamsTypeRsaHashedImportParams: histogramAlgorithm(context, algorithm.rsaHashedImportParams()->hash()); break; case WebCryptoAlgorithmParamsTypeEcdsaParams: histogramAlgorithm(context, algorithm.ecdsaParams()->hash()); break; case WebCryptoAlgorithmParamsTypeHkdfParams: histogramAlgorithm(context, algorithm.hkdfParams()->hash()); break; case WebCryptoAlgorithmParamsTypePbkdf2Params: histogramAlgorithm(context, algorithm.pbkdf2Params()->hash()); break; case WebCryptoAlgorithmParamsTypeEcdhKeyDeriveParams: case WebCryptoAlgorithmParamsTypeNone: case WebCryptoAlgorithmParamsTypeAesCbcParams: case WebCryptoAlgorithmParamsTypeAesGcmParams: case WebCryptoAlgorithmParamsTypeAesKeyGenParams: case WebCryptoAlgorithmParamsTypeRsaOaepParams: case WebCryptoAlgorithmParamsTypeAesCtrParams: case WebCryptoAlgorithmParamsTypeRsaPssParams: case WebCryptoAlgorithmParamsTypeEcKeyGenParams: case WebCryptoAlgorithmParamsTypeEcKeyImportParams: case WebCryptoAlgorithmParamsTypeAesDerivedKeyParams: break; } } void histogramKey(ExecutionContext* context, const WebCryptoKey& key) { const WebCryptoKeyAlgorithm& algorithm = key.algorithm(); histogramAlgorithmId(context, algorithm.id()); // Histogram any interesting parameters that are attached to the key. For // instance the inner hash being used for HMAC. switch (algorithm.paramsType()) { case WebCryptoKeyAlgorithmParamsTypeHmac: histogramAlgorithm(context, algorithm.hmacParams()->hash()); break; case WebCryptoKeyAlgorithmParamsTypeRsaHashed: histogramAlgorithm(context, algorithm.rsaHashedParams()->hash()); break; case WebCryptoKeyAlgorithmParamsTypeNone: case WebCryptoKeyAlgorithmParamsTypeAes: case WebCryptoKeyAlgorithmParamsTypeEc: break; } } void histogramAlgorithmAndKey(ExecutionContext* context, const WebCryptoAlgorithm& algorithm, const WebCryptoKey& key) { // Note that the algorithm ID for |algorithm| and |key| will usually be the // same. This is OK because UseCounter only increments things once per the // context. histogramAlgorithm(context, algorithm); histogramKey(context, key); } } // namespace blink
bsd-3-clause
2947721120/cdnjs
ajax/libs/dojo/1.7.5/cldr/nls/zh-tw/currency.js
457
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/cldr/nls/zh-tw/currency",{"USD_symbol":"$","EUR_displayName":"歐元","HKD_displayName":"港幣","CAD_displayName":"加幣","JPY_displayName":"日圓","GBP_displayName":"英鎊","AUD_displayName":"澳幣","CNY_displayName":"人民幣"});
mit
blmlove409/angularjs-up-and-running
chapter11/ng-include/app.js
574
// File: chapter11/ng-include/app.js angular.module('stockMarketApp', []) .controller('MainCtrl', [function() { var self = this; self.stocks = [ {name: 'First Stock', price: 100, previous: 220}, {name: 'Second Stock', price: 140, previous: 120}, {name: 'Third Stock', price: 110, previous: 110}, {name: 'Fourth Stock', price: 400, previous: 420} ]; self.stockTemplate = 'stock.html'; self.getChange = function(stock) { return Math.ceil(((stock.price - stock.previous) / stock.previous) * 100); }; }]);
mit
siyisiyi/ss-panel-v3-mod
vendor/symfony/polyfill/src/Intl/Grapheme/bootstrap.php
1535
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Intl\Grapheme as p; if (!function_exists('grapheme_strlen')) { define('GRAPHEME_EXTR_COUNT', 0); define('GRAPHEME_EXTR_MAXBYTES', 1); define('GRAPHEME_EXTR_MAXCHARS', 2); function grapheme_extract($s, $size, $type = 0, $start = 0, &$next = 0) { return p\Grapheme::grapheme_extract($s, $size, $type, $start, $next); } function grapheme_stripos($s, $needle, $offset = 0) { return p\Grapheme::grapheme_stripos($s, $needle, $offset); } function grapheme_stristr($s, $needle, $beforeNeedle = false) { return p\Grapheme::grapheme_stristr($s, $needle, $beforeNeedle); } function grapheme_strlen($s) { return p\Grapheme::grapheme_strlen($s); } function grapheme_strpos($s, $needle, $offset = 0) { return p\Grapheme::grapheme_strpos($s, $needle, $offset); } function grapheme_strripos($s, $needle, $offset = 0) { return p\Grapheme::grapheme_strripos($s, $needle, $offset); } function grapheme_strrpos($s, $needle, $offset = 0) { return p\Grapheme::grapheme_strrpos($s, $needle, $offset); } function grapheme_strstr($s, $needle, $beforeNeedle = false) { return p\Grapheme::grapheme_strstr($s, $needle, $beforeNeedle); } function grapheme_substr($s, $start, $len = 2147483647) { return p\Grapheme::grapheme_substr($s, $start, $len); } }
mit
tgxworld/rails
activerecord/lib/active_record/connection_adapters/postgresql/oid/interval.rb
1313
# frozen_string_literal: true require "active_support/duration" module ActiveRecord module ConnectionAdapters module PostgreSQL module OID # :nodoc: class Interval < Type::Value # :nodoc: def type :interval end def cast_value(value) case value when ::ActiveSupport::Duration value when ::String begin ::ActiveSupport::Duration.parse(value) rescue ::ActiveSupport::Duration::ISO8601Parser::ParsingError nil end else super end end def serialize(value) case value when ::ActiveSupport::Duration value.iso8601(precision: self.precision) when ::Numeric # Sometimes operations on Times returns just float number of seconds so we need to handle that. # Example: Time.current - (Time.current + 1.hour) # => -3600.000001776 (Float) value.seconds.iso8601(precision: self.precision) else super end end def type_cast_for_schema(value) serialize(value).inspect end end end end end end
mit
seogi1004/cdnjs
ajax/libs/ag-grid/9.0.0/lib/functions.js
948
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v9.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("./utils"); function defaultGroupComparator(valueA, valueB, nodeA, nodeB) { var nodeAIsGroup = utils_1.Utils.exists(nodeA) && nodeA.group; var nodeBIsGroup = utils_1.Utils.exists(nodeB) && nodeB.group; var bothAreGroups = nodeAIsGroup && nodeBIsGroup; var bothAreNormal = !nodeAIsGroup && !nodeBIsGroup; if (bothAreGroups) { return utils_1.Utils.defaultComparator(nodeA.key, nodeB.key); } else if (bothAreNormal) { return utils_1.Utils.defaultComparator(valueA, valueB); } else if (nodeAIsGroup) { return 1; } else { return -1; } } exports.defaultGroupComparator = defaultGroupComparator;
mit
cemalkilic/che
ide/commons-gwt/src/main/java/org/eclipse/che/ide/util/browser/UserAgentRuntimeProperties.java
6903
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eclipse.che.ide.util.browser; import org.eclipse.che.ide.util.Box; import com.google.gwt.core.client.GWT; /** Class to contain run-time checks of a user-agent's capabilities. */ public class UserAgentRuntimeProperties { private static final UserAgentRuntimeProperties INSTANCE = createInstance(); private static UserAgentRuntimeProperties createInstance() { return GWT.isScript() ? new UserAgentRuntimeProperties(getNativeUserAgent()) : new UserAgentRuntimeProperties(""); } public static UserAgentRuntimeProperties get() { return INSTANCE; } private final String userAgent; private final int version; private final boolean isMac; private final boolean isWin; private final boolean isLinux; private final boolean isIe7; private final boolean isIe8; private final boolean isChrome; public UserAgentRuntimeProperties(String userAgent) { this.userAgent = userAgent; this.version = calculateVersion(userAgent); this.isMac = calculateIsMac(userAgent); this.isWin = calculateIsWin(userAgent); this.isLinux = calculateIsLinux(userAgent); this.isIe7 = calculateIe7(userAgent); this.isIe8 = calculateIe8(userAgent); this.isChrome = calculateIsChrome(userAgent); } public String getUserAgent() { return userAgent; } public boolean isMac() { return isMac; } public boolean isWin() { return isWin; } public boolean isLinux() { return isLinux; } public boolean isIe7() { return isIe7; } public boolean isIe8() { return isIe8; } public boolean isChrome() { return isChrome; } /** * @return whether the current user agent version is at least the one given by * the method parameters. */ public boolean isAtLeastVersion(int major, int minor) { return version >= (major * 1000 + minor); } /** * Do not use this for program logic - for debugging only. For program logic, * instead use {@link #isAtLeastVersion(int, int)} */ public int getMajorVer() { return version / 1000; } /** * Do not use this for program logic - for debugging only. For program logic, * instead use {@link #isAtLeastVersion(int, int)} */ public int getMinorVer() { return version % 1000; } private static native String getNativeUserAgent() /*-{ return navigator.userAgent; }-*/; private static boolean calculateIe7(String userAgent) { return userAgent.indexOf(" MSIE 7.") != -1; } private static boolean calculateIe8(String userAgent) { return userAgent.indexOf(" MSIE 8.") != -1; } private static boolean calculateIsMac(String userAgent) { return userAgent.indexOf("Mac") != -1; } private static boolean calculateIsWin(String userAgent) { return userAgent.indexOf("Windows") != -1; } private static boolean calculateIsLinux(String userAgent) { return userAgent.indexOf("Linux") != -1; } private static boolean calculateIsChrome(String userAgent) { return userAgent.indexOf("Chrome") != -1; } private static int calculateVersion(String userAgent) { if (userAgent == null || userAgent.isEmpty()) { return -1; } // TODO(user): Make this work after regex deps are fixed and don't break static rendering // // String regexps[] = {"firefox.([0-9]+).([0-9]+)", // "webkit.([0-9]+).([0-9]+)", // "msie.([0-9]+).([0-9]+)", // "minefield.([0-9]+).([0-9]+)"}; // TODO(user): Don't use "firefox" and "minefield", check Gecko rv. String names[] = {"firefox", "webkit", "msie", "minefield"}; for (String name : names) { int v = calculateVersion(name, userAgent); if (v >= 0) { return v; } } return -1; } // /** // * Matches a browser-specific regular expression against the user agent to // * obtain a version number. // * // * @param regexp The browser-specific regular expression to use // * @param userAgent The user agent string to check // * @return A version number or -1 if unknown // */ /** * Matches a browser-specific name against the user agent to obtain a version * number. * * @param name * The browser-specific name to use * @param userAgent * The user agent string to check * @return A version number or -1 if unknown */ private static int calculateVersion(String name, String userAgent) { int index = userAgent.toLowerCase().indexOf(name); if (index == -1) { return -1; } Box<Integer> output = Box.create(); index += name.length() + 1; if ((index = consumeDigit(index, userAgent, output)) == -1) { return -1; } int major = output.boxed; index++; if ((index = consumeDigit(index, userAgent, output)) == -1) { return -1; } int minor = output.boxed; return major * 1000 + minor; // TODO(user): Make this work after regex deps are fixed and don't break static rendering // // RegExp pattern = RegExp.compile(regexp); // MatchResult result = pattern.exec(userAgent.toLowerCase()); // if (result != null && result.getGroupCount() == 3) { // int major = Integer.parseInt(result.getGroup(1)); // int minor = Integer.parseInt(result.getGroup(2)); // return major * 1000 + minor; // } // return -1; } private static int consumeDigit(int index, String str, Box<Integer> output) { StringBuilder nb = new StringBuilder(); char c; while (index < str.length() && Character.isDigit((c = str.charAt(index)))) { nb.append(c); index++; } if (nb.length() == 0) { return -1; } try { output.boxed = Integer.parseInt(nb.toString()); return index; } catch (NumberFormatException e) { return -1; } } }
epl-1.0
R3nPi2/Drupal-8-Skeleton
core/tests/Drupal/FunctionalTests/Rest/EntityFormDisplayXmlAnonTest.php
590
<?php namespace Drupal\FunctionalTests\Rest; use Drupal\Tests\rest\Functional\AnonResourceTestTrait; use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait; /** * @group rest */ class EntityFormDisplayXmlAnonTest extends EntityFormDisplayResourceTestBase { use AnonResourceTestTrait; use XmlEntityNormalizationQuirksTrait; /** * {@inheritdoc} */ protected static $format = 'xml'; /** * {@inheritdoc} */ protected static $mimeType = 'text/xml; charset=UTF-8'; /** * {@inheritdoc} */ protected $defaultTheme = 'stark'; }
gpl-2.0
zhujianfeng/osTicket-1.8
include/staff/emails.inc.php
6800
<?php if(!defined('OSTADMININC') || !$thisstaff->isAdmin()) die('Access Denied'); $qs = array(); $sql='SELECT email.*,dept.dept_name as department,priority_desc as priority '. ' FROM '.EMAIL_TABLE.' email '. ' LEFT JOIN '.DEPT_TABLE.' dept ON (dept.dept_id=email.dept_id) '. ' LEFT JOIN '.TICKET_PRIORITY_TABLE.' pri ON (pri.priority_id=email.priority_id) '; $sql.=' WHERE 1'; $sortOptions=array('email'=>'email.email','dept'=>'department','priority'=>'priority','created'=>'email.created','updated'=>'email.updated'); $orderWays=array('DESC'=>'DESC','ASC'=>'ASC'); $sort=($_REQUEST['sort'] && $sortOptions[strtolower($_REQUEST['sort'])])?strtolower($_REQUEST['sort']):'email'; //Sorting options... if($sort && $sortOptions[$sort]) { $order_column =$sortOptions[$sort]; } $order_column=$order_column?$order_column:'email.email'; if($_REQUEST['order'] && $orderWays[strtoupper($_REQUEST['order'])]) { $order=$orderWays[strtoupper($_REQUEST['order'])]; } $order=$order?$order:'ASC'; if($order_column && strpos($order_column,',')){ $order_column=str_replace(','," $order,",$order_column); } $x=$sort.'_sort'; $$x=' class="'.strtolower($order).'" '; $order_by="$order_column $order "; $total=db_count('SELECT count(*) FROM '.EMAIL_TABLE.' email '); $page=($_GET['p'] && is_numeric($_GET['p']))?$_GET['p']:1; $pageNav=new Pagenate($total, $page, PAGE_LIMIT); $qs += array('sort' => $_REQUEST['sort'], 'order' => $_REQUEST['order']); $pageNav->setURL('emails.php', $qs); $qstr = '&amp;order='.($order=='DESC' ? 'ASC' : 'DESC'); $query="$sql GROUP BY email.email_id ORDER BY $order_by LIMIT ".$pageNav->getStart().",".$pageNav->getLimit(); $res=db_query($query); if($res && ($num=db_num_rows($res))) $showing=$pageNav->showing().' '.__('emails'); else $showing=__('No emails found!'); $def_dept_id = $cfg->getDefaultDeptId(); $def_dept_name = $cfg->getDefaultDept()->getName(); $def_priority = $cfg->getDefaultPriority()->getDesc(); ?> <div class="pull-left" style="width:700px;padding-top:5px;"> <h2><?php echo __('Email Addresses');?></h2> </div> <div class="pull-right flush-right" style="padding-top:5px;padding-right:5px;"> <b><a href="emails.php?a=add" class="Icon newEmail"><?php echo __('Add New Email');?></a></b></div> <div class="clear"></div> <form action="emails.php" method="POST" name="emails"> <?php csrf_token(); ?> <input type="hidden" name="do" value="mass_process" > <input type="hidden" id="action" name="a" value="" > <table class="list" border="0" cellspacing="1" cellpadding="0" width="940"> <caption><?php echo $showing; ?></caption> <thead> <tr> <th width="7">&nbsp;</th> <th width="400"><a <?php echo $email_sort; ?> href="emails.php?<?php echo $qstr; ?>&sort=email"><?php echo __('Email');?></a></th> <th width="120"><a <?php echo $priority_sort; ?> href="emails.php?<?php echo $qstr; ?>&sort=priority"><?php echo __('Priority');?></a></th> <th width="250"><a <?php echo $dept_sort; ?> href="emails.php?<?php echo $qstr; ?>&sort=dept"><?php echo __('Department');?></a></th> <th width="110" nowrap><a <?php echo $created_sort; ?>href="emails.php?<?php echo $qstr; ?>&sort=created"><?php echo __('Created');?></a></th> <th width="150" nowrap><a <?php echo $updated_sort; ?>href="emails.php?<?php echo $qstr; ?>&sort=updated"><?php echo __('Last Updated');?></a></th> </tr> </thead> <tbody> <?php $total=0; $ids=($errors && is_array($_POST['ids']))?$_POST['ids']:null; if($res && db_num_rows($res)): $defaultId=$cfg->getDefaultEmailId(); while ($row = db_fetch_array($res)) { $sel=false; if($ids && in_array($row['email_id'],$ids)) $sel=true; $default=($row['email_id']==$defaultId); $email=$row['email']; if($row['name']) $email=$row['name'].' <'.$row['email'].'>'; ?> <tr id="<?php echo $row['email_id']; ?>"> <td width=7px> <input type="checkbox" class="ckb" name="ids[]" value="<?php echo $row['email_id']; ?>" <?php echo $sel?'checked="checked"':''; ?> <?php echo $default?'disabled="disabled"':''; ?>> </td> <td><span class="ltr"><a href="emails.php?id=<?php echo $row['email_id']; ?>"><?php echo Format::htmlchars($email); ?></a></span></td> <td><?php echo $row['priority'] ?: $def_priority; ?></td> <td><a href="departments.php?id=<?php $row['dept_id'] ?: $def_dept_id; ?>"><?php echo $row['department'] ?: $def_dept_name; ?></a></td> <td>&nbsp;<?php echo Format::db_date($row['created']); ?></td> <td>&nbsp;<?php echo Format::db_datetime($row['updated']); ?></td> </tr> <?php } //end of while. endif; ?> <tfoot> <tr> <td colspan="6"> <?php if($res && $num){ ?> <?php echo __('Select');?>:&nbsp; <a id="selectAll" href="#ckb"><?php echo __('All');?></a>&nbsp;&nbsp; <a id="selectNone" href="#ckb"><?php echo __('None');?></a>&nbsp;&nbsp; <a id="selectToggle" href="#ckb"><?php echo __('Toggle');?></a>&nbsp;&nbsp; <?php }else{ echo __('No help emails found'); } ?> </td> </tr> </tfoot> </table> <?php if($res && $num): //Show options.. echo '<div>&nbsp;'.__('Page').':'.$pageNav->getPageLinks().'&nbsp;</div>'; ?> <p class="centered" id="actions"> <input class="button" type="submit" name="delete" value="<?php echo __('Delete Email(s)');?>" > </p> <?php endif; ?> </form> <div style="display:none;" class="dialog" id="confirm-action"> <h3><?php echo __('Please Confirm');?></h3> <a class="close" href=""><i class="icon-remove-circle"></i></a> <hr/> <p class="confirm-action" style="display:none;" id="delete-confirm"> <font color="red"><strong><?php echo sprintf(__('Are you sure you want to DELETE %s?'), _N('selected email', 'selected emails', 2)) ;?></strong></font> <br><br><?php echo __('Deleted data CANNOT be recovered.');?> </p> <div><?php echo __('Please confirm to continue.');?></div> <hr style="margin-top:1em"/> <p class="full-width"> <span class="buttons pull-left"> <input type="button" value="<?php echo __('No, Cancel');?>" class="close"> </span> <span class="buttons pull-right"> <input type="button" value="<?php echo __('Yes, Do it!');?>" class="confirm"> </span> </p> <div class="clear"></div> </div>
gpl-2.0
dmlloyd/openjdk-modules
jdk/src/java.desktop/share/classes/javax/imageio/ImageReader.java
114935
/* * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.imageio; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.event.IIOReadWarningListener; import javax.imageio.event.IIOReadProgressListener; import javax.imageio.event.IIOReadUpdateListener; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataFormatImpl; import javax.imageio.stream.ImageInputStream; /** * An abstract superclass for parsing and decoding of images. This * class must be subclassed by classes that read in images in the * context of the Java Image I/O framework. * * <p> {@code ImageReader} objects are normally instantiated by * the service provider interface (SPI) class for the specific format. * Service provider classes (e.g., instances of * {@code ImageReaderSpi}) are registered with the * {@code IIORegistry}, which uses them for format recognition * and presentation of available format readers and writers. * * <p> When an input source is set (using the {@code setInput} * method), it may be marked as "seek forward only". This setting * means that images contained within the input source will only be * read in order, possibly allowing the reader to avoid caching * portions of the input containing data associated with images that * have been read previously. * * @see ImageWriter * @see javax.imageio.spi.IIORegistry * @see javax.imageio.spi.ImageReaderSpi * */ public abstract class ImageReader { /** * The {@code ImageReaderSpi} that instantiated this object, * or {@code null} if its identity is not known or none * exists. By default it is initialized to {@code null}. */ protected ImageReaderSpi originatingProvider; /** * The {@code ImageInputStream} or other * {@code Object} by {@code setInput} and retrieved * by {@code getInput}. By default it is initialized to * {@code null}. */ protected Object input = null; /** * {@code true} if the current input source has been marked * as allowing only forward seeking by {@code setInput}. By * default, the value is {@code false}. * * @see #minIndex * @see #setInput */ protected boolean seekForwardOnly = false; /** * {@code true} if the current input source has been marked * as allowing metadata to be ignored by {@code setInput}. * By default, the value is {@code false}. * * @see #setInput */ protected boolean ignoreMetadata = false; /** * The smallest valid index for reading, initially 0. When * {@code seekForwardOnly} is {@code true}, various methods * may throw an {@code IndexOutOfBoundsException} on an * attempt to access data associate with an image having a lower * index. * * @see #seekForwardOnly * @see #setInput */ protected int minIndex = 0; /** * An array of {@code Locale}s which may be used to localize * warning messages, or {@code null} if localization is not * supported. */ protected Locale[] availableLocales = null; /** * The current {@code Locale} to be used for localization, or * {@code null} if none has been set. */ protected Locale locale = null; /** * A {@code List} of currently registered * {@code IIOReadWarningListener}s, initialized by default to * {@code null}, which is synonymous with an empty * {@code List}. */ protected List<IIOReadWarningListener> warningListeners = null; /** * A {@code List} of the {@code Locale}s associated with * each currently registered {@code IIOReadWarningListener}, * initialized by default to {@code null}, which is * synonymous with an empty {@code List}. */ protected List<Locale> warningLocales = null; /** * A {@code List} of currently registered * {@code IIOReadProgressListener}s, initialized by default * to {@code null}, which is synonymous with an empty * {@code List}. */ protected List<IIOReadProgressListener> progressListeners = null; /** * A {@code List} of currently registered * {@code IIOReadUpdateListener}s, initialized by default to * {@code null}, which is synonymous with an empty * {@code List}. */ protected List<IIOReadUpdateListener> updateListeners = null; /** * If {@code true}, the current read operation should be * aborted. */ private boolean abortFlag = false; /** * Constructs an {@code ImageReader} and sets its * {@code originatingProvider} field to the supplied value. * * <p> Subclasses that make use of extensions should provide a * constructor with signature {@code (ImageReaderSpi,Object)} * in order to retrieve the extension object. If * the extension object is unsuitable, an * {@code IllegalArgumentException} should be thrown. * * @param originatingProvider the {@code ImageReaderSpi} that is * invoking this constructor, or {@code null}. */ protected ImageReader(ImageReaderSpi originatingProvider) { this.originatingProvider = originatingProvider; } /** * Returns a {@code String} identifying the format of the * input source. * * <p> The default implementation returns * {@code originatingProvider.getFormatNames()[0]}. * Implementations that may not have an originating service * provider, or which desire a different naming policy should * override this method. * * @exception IOException if an error occurs reading the * information from the input source. * * @return the format name, as a {@code String}. */ public String getFormatName() throws IOException { return originatingProvider.getFormatNames()[0]; } /** * Returns the {@code ImageReaderSpi} that was passed in on * the constructor. Note that this value may be {@code null}. * * @return an {@code ImageReaderSpi}, or {@code null}. * * @see ImageReaderSpi */ public ImageReaderSpi getOriginatingProvider() { return originatingProvider; } /** * Sets the input source to use to the given * {@code ImageInputStream} or other {@code Object}. * The input source must be set before any of the query or read * methods are used. If {@code input} is {@code null}, * any currently set input source will be removed. In any case, * the value of {@code minIndex} will be initialized to 0. * * <p> The {@code seekForwardOnly} parameter controls whether * the value returned by {@code getMinIndex} will be * increased as each image (or thumbnail, or image metadata) is * read. If {@code seekForwardOnly} is true, then a call to * {@code read(index)} will throw an * {@code IndexOutOfBoundsException} if {@code index < this.minIndex}; * otherwise, the value of * {@code minIndex} will be set to {@code index}. If * {@code seekForwardOnly} is {@code false}, the value of * {@code minIndex} will remain 0 regardless of any read * operations. * * <p> The {@code ignoreMetadata} parameter, if set to * {@code true}, allows the reader to disregard any metadata * encountered during the read. Subsequent calls to the * {@code getStreamMetadata} and * {@code getImageMetadata} methods may return * {@code null}, and an {@code IIOImage} returned from * {@code readAll} may return {@code null} from their * {@code getMetadata} method. Setting this parameter may * allow the reader to work more efficiently. The reader may * choose to disregard this setting and return metadata normally. * * <p> Subclasses should take care to remove any cached * information based on the previous stream, such as header * information or partially decoded image data. * * <p> Use of a general {@code Object} other than an * {@code ImageInputStream} is intended for readers that * interact directly with a capture device or imaging protocol. * The set of legal classes is advertised by the reader's service * provider's {@code getInputTypes} method; most readers * will return a single-element array containing only * {@code ImageInputStream.class} to indicate that they * accept only an {@code ImageInputStream}. * * <p> The default implementation checks the {@code input} * argument against the list returned by * {@code originatingProvider.getInputTypes()} and fails * if the argument is not an instance of one of the classes * in the list. If the originating provider is set to * {@code null}, the input is accepted only if it is an * {@code ImageInputStream}. * * @param input the {@code ImageInputStream} or other * {@code Object} to use for future decoding. * @param seekForwardOnly if {@code true}, images and metadata * may only be read in ascending order from this input source. * @param ignoreMetadata if {@code true}, metadata * may be ignored during reads. * * @exception IllegalArgumentException if {@code input} is * not an instance of one of the classes returned by the * originating service provider's {@code getInputTypes} * method, or is not an {@code ImageInputStream}. * * @see ImageInputStream * @see #getInput * @see javax.imageio.spi.ImageReaderSpi#getInputTypes */ public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) { if (input != null) { boolean found = false; if (originatingProvider != null) { Class<?>[] classes = originatingProvider.getInputTypes(); for (int i = 0; i < classes.length; i++) { if (classes[i].isInstance(input)) { found = true; break; } } } else { if (input instanceof ImageInputStream) { found = true; } } if (!found) { throw new IllegalArgumentException("Incorrect input type!"); } this.seekForwardOnly = seekForwardOnly; this.ignoreMetadata = ignoreMetadata; this.minIndex = 0; } this.input = input; } /** * Sets the input source to use to the given * {@code ImageInputStream} or other {@code Object}. * The input source must be set before any of the query or read * methods are used. If {@code input} is {@code null}, * any currently set input source will be removed. In any case, * the value of {@code minIndex} will be initialized to 0. * * <p> The {@code seekForwardOnly} parameter controls whether * the value returned by {@code getMinIndex} will be * increased as each image (or thumbnail, or image metadata) is * read. If {@code seekForwardOnly} is true, then a call to * {@code read(index)} will throw an * {@code IndexOutOfBoundsException} if {@code index < this.minIndex}; * otherwise, the value of * {@code minIndex} will be set to {@code index}. If * {@code seekForwardOnly} is {@code false}, the value of * {@code minIndex} will remain 0 regardless of any read * operations. * * <p> This method is equivalent to * {@code setInput(input, seekForwardOnly, false)}. * * @param input the {@code ImageInputStream} or other * {@code Object} to use for future decoding. * @param seekForwardOnly if {@code true}, images and metadata * may only be read in ascending order from this input source. * * @exception IllegalArgumentException if {@code input} is * not an instance of one of the classes returned by the * originating service provider's {@code getInputTypes} * method, or is not an {@code ImageInputStream}. * * @see #getInput */ public void setInput(Object input, boolean seekForwardOnly) { setInput(input, seekForwardOnly, false); } /** * Sets the input source to use to the given * {@code ImageInputStream} or other {@code Object}. * The input source must be set before any of the query or read * methods are used. If {@code input} is {@code null}, * any currently set input source will be removed. In any case, * the value of {@code minIndex} will be initialized to 0. * * <p> This method is equivalent to * {@code setInput(input, false, false)}. * * @param input the {@code ImageInputStream} or other * {@code Object} to use for future decoding. * * @exception IllegalArgumentException if {@code input} is * not an instance of one of the classes returned by the * originating service provider's {@code getInputTypes} * method, or is not an {@code ImageInputStream}. * * @see #getInput */ public void setInput(Object input) { setInput(input, false, false); } /** * Returns the {@code ImageInputStream} or other * {@code Object} previously set as the input source. If the * input source has not been set, {@code null} is returned. * * @return the {@code Object} that will be used for future * decoding, or {@code null}. * * @see ImageInputStream * @see #setInput */ public Object getInput() { return input; } /** * Returns {@code true} if the current input source has been * marked as seek forward only by passing {@code true} as the * {@code seekForwardOnly} argument to the * {@code setInput} method. * * @return {@code true} if the input source is seek forward * only. * * @see #setInput */ public boolean isSeekForwardOnly() { return seekForwardOnly; } /** * Returns {@code true} if the current input source has been * marked as allowing metadata to be ignored by passing * {@code true} as the {@code ignoreMetadata} argument * to the {@code setInput} method. * * @return {@code true} if the metadata may be ignored. * * @see #setInput */ public boolean isIgnoringMetadata() { return ignoreMetadata; } /** * Returns the lowest valid index for reading an image, thumbnail, * or image metadata. If {@code seekForwardOnly()} is * {@code false}, this value will typically remain 0, * indicating that random access is possible. Otherwise, it will * contain the value of the most recently accessed index, and * increase in a monotonic fashion. * * @return the minimum legal index for reading. */ public int getMinIndex() { return minIndex; } // Localization /** * Returns an array of {@code Locale}s that may be used to * localize warning listeners and compression settings. A return * value of {@code null} indicates that localization is not * supported. * * <p> The default implementation returns a clone of the * {@code availableLocales} instance variable if it is * non-{@code null}, or else returns {@code null}. * * @return an array of {@code Locale}s that may be used as * arguments to {@code setLocale}, or {@code null}. */ public Locale[] getAvailableLocales() { if (availableLocales == null) { return null; } else { return availableLocales.clone(); } } /** * Sets the current {@code Locale} of this * {@code ImageReader} to the given value. A value of * {@code null} removes any previous setting, and indicates * that the reader should localize as it sees fit. * * @param locale the desired {@code Locale}, or * {@code null}. * * @exception IllegalArgumentException if {@code locale} is * non-{@code null} but is not one of the values returned by * {@code getAvailableLocales}. * * @see #getLocale */ public void setLocale(Locale locale) { if (locale != null) { Locale[] locales = getAvailableLocales(); boolean found = false; if (locales != null) { for (int i = 0; i < locales.length; i++) { if (locale.equals(locales[i])) { found = true; break; } } } if (!found) { throw new IllegalArgumentException("Invalid locale!"); } } this.locale = locale; } /** * Returns the currently set {@code Locale}, or * {@code null} if none has been set. * * @return the current {@code Locale}, or {@code null}. * * @see #setLocale */ public Locale getLocale() { return locale; } // Image queries /** * Returns the number of images, not including thumbnails, available * from the current input source. * * <p> Note that some image formats (such as animated GIF) do not * specify how many images are present in the stream. Thus * determining the number of images will require the entire stream * to be scanned and may require memory for buffering. If images * are to be processed in order, it may be more efficient to * simply call {@code read} with increasing indices until an * {@code IndexOutOfBoundsException} is thrown to indicate * that no more images are available. The * {@code allowSearch} parameter may be set to * {@code false} to indicate that an exhaustive search is not * desired; the return value will be {@code -1} to indicate * that a search is necessary. If the input has been specified * with {@code seekForwardOnly} set to {@code true}, * this method throws an {@code IllegalStateException} if * {@code allowSearch} is set to {@code true}. * * @param allowSearch if {@code true}, the true number of * images will be returned even if a search is required. If * {@code false}, the reader may return {@code -1} * without performing the search. * * @return the number of images, as an {@code int}, or * {@code -1} if {@code allowSearch} is * {@code false} and a search would be required. * * @exception IllegalStateException if the input source has not been set, * or if the input has been specified with {@code seekForwardOnly} * set to {@code true}. * @exception IOException if an error occurs reading the * information from the input source. * * @see #setInput */ public abstract int getNumImages(boolean allowSearch) throws IOException; /** * Returns the width in pixels of the given image within the input * source. * * <p> If the image can be rendered to a user-specified size, then * this method returns the default width. * * @param imageIndex the index of the image to be queried. * * @return the width of the image, as an {@code int}. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs reading the width * information from the input source. */ public abstract int getWidth(int imageIndex) throws IOException; /** * Returns the height in pixels of the given image within the * input source. * * <p> If the image can be rendered to a user-specified size, then * this method returns the default height. * * @param imageIndex the index of the image to be queried. * * @return the height of the image, as an {@code int}. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs reading the height * information from the input source. */ public abstract int getHeight(int imageIndex) throws IOException; /** * Returns {@code true} if the storage format of the given * image places no inherent impediment on random access to pixels. * For most compressed formats, such as JPEG, this method should * return {@code false}, as a large section of the image in * addition to the region of interest may need to be decoded. * * <p> This is merely a hint for programs that wish to be * efficient; all readers must be able to read arbitrary regions * as specified in an {@code ImageReadParam}. * * <p> Note that formats that return {@code false} from * this method may nonetheless allow tiling (<i>e.g.</i> Restart * Markers in JPEG), and random access will likely be reasonably * efficient on tiles. See {@link #isImageTiled isImageTiled}. * * <p> A reader for which all images are guaranteed to support * easy random access, or are guaranteed not to support easy * random access, may return {@code true} or * {@code false} respectively without accessing any image * data. In such cases, it is not necessary to throw an exception * even if no input source has been set or the image index is out * of bounds. * * <p> The default implementation returns {@code false}. * * @param imageIndex the index of the image to be queried. * * @return {@code true} if reading a region of interest of * the given image is likely to be efficient. * * @exception IllegalStateException if an input source is required * to determine the return value, but none has been set. * @exception IndexOutOfBoundsException if an image must be * accessed to determine the return value, but the supplied index * is out of bounds. * @exception IOException if an error occurs during reading. */ public boolean isRandomAccessEasy(int imageIndex) throws IOException { return false; } /** * Returns the aspect ratio of the given image (that is, its width * divided by its height) as a {@code float}. For images * that are inherently resizable, this method provides a way to * determine the appropriate width given a desired height, or vice * versa. For non-resizable images, the true width and height * are used. * * <p> The default implementation simply returns * {@code (float)getWidth(imageIndex)/getHeight(imageIndex)}. * * @param imageIndex the index of the image to be queried. * * @return a {@code float} indicating the aspect ratio of the * given image. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs during reading. */ public float getAspectRatio(int imageIndex) throws IOException { return (float)getWidth(imageIndex)/getHeight(imageIndex); } /** * Returns an <code>ImageTypeSpecifier</code> indicating the * <code>SampleModel</code> and <code>ColorModel</code> which most * closely represents the "raw" internal format of the image. If * there is no close match then a type which preserves the most * information from the image should be returned. The returned value * should also be included in the list of values returned by * {@code getImageTypes}. * * <p> The default implementation simply returns the first entry * from the list provided by {@code getImageType}. * * @param imageIndex the index of the image to be queried. * * @return an {@code ImageTypeSpecifier}. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs reading the format * information from the input source. */ public ImageTypeSpecifier getRawImageType(int imageIndex) throws IOException { return getImageTypes(imageIndex).next(); } /** * Returns an {@code Iterator} containing possible image * types to which the given image may be decoded, in the form of * {@code ImageTypeSpecifiers}s. At least one legal image * type will be returned. * * <p> The first element of the iterator should be the most * "natural" type for decoding the image with as little loss as * possible. For example, for a JPEG image the first entry should * be an RGB image, even though the image data is stored * internally in a YCbCr color space. * * @param imageIndex the index of the image to be * {@code retrieved}. * * @return an {@code Iterator} containing at least one * {@code ImageTypeSpecifier} representing suggested image * types for decoding the current given image. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs reading the format * information from the input source. * * @see ImageReadParam#setDestination(BufferedImage) * @see ImageReadParam#setDestinationType(ImageTypeSpecifier) */ public abstract Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException; /** * Returns a default {@code ImageReadParam} object * appropriate for this format. All subclasses should define a * set of default values for all parameters and return them with * this call. This method may be called before the input source * is set. * * <p> The default implementation constructs and returns a new * {@code ImageReadParam} object that does not allow source * scaling (<i>i.e.</i>, it returns * {@code new ImageReadParam()}. * * @return an {@code ImageReadParam} object which may be used * to control the decoding process using a set of default settings. */ public ImageReadParam getDefaultReadParam() { return new ImageReadParam(); } /** * Returns an {@code IIOMetadata} object representing the * metadata associated with the input source as a whole (i.e., not * associated with any particular image), or {@code null} if * the reader does not support reading metadata, is set to ignore * metadata, or if no metadata is available. * * @return an {@code IIOMetadata} object, or {@code null}. * * @exception IOException if an error occurs during reading. */ public abstract IIOMetadata getStreamMetadata() throws IOException; /** * Returns an {@code IIOMetadata} object representing the * metadata associated with the input source as a whole (i.e., * not associated with any particular image). If no such data * exists, {@code null} is returned. * * <p> The resulting metadata object is only responsible for * returning documents in the format named by * {@code formatName}. Within any documents that are * returned, only nodes whose names are members of * {@code nodeNames} are required to be returned. In this * way, the amount of metadata processing done by the reader may * be kept to a minimum, based on what information is actually * needed. * * <p> If {@code formatName} is not the name of a supported * metadata format, {@code null} is returned. * * <p> In all cases, it is legal to return a more capable metadata * object than strictly necessary. The format name and node names * are merely hints that may be used to reduce the reader's * workload. * * <p> The default implementation simply returns the result of * calling {@code getStreamMetadata()}, after checking that * the format name is supported. If it is not, * {@code null} is returned. * * @param formatName a metadata format name that may be used to retrieve * a document from the returned {@code IIOMetadata} object. * @param nodeNames a {@code Set} containing the names of * nodes that may be contained in a retrieved document. * * @return an {@code IIOMetadata} object, or {@code null}. * * @exception IllegalArgumentException if {@code formatName} * is {@code null}. * @exception IllegalArgumentException if {@code nodeNames} * is {@code null}. * @exception IOException if an error occurs during reading. */ public IIOMetadata getStreamMetadata(String formatName, Set<String> nodeNames) throws IOException { return getMetadata(formatName, nodeNames, true, 0); } private IIOMetadata getMetadata(String formatName, Set<String> nodeNames, boolean wantStream, int imageIndex) throws IOException { if (formatName == null) { throw new IllegalArgumentException("formatName == null!"); } if (nodeNames == null) { throw new IllegalArgumentException("nodeNames == null!"); } IIOMetadata metadata = wantStream ? getStreamMetadata() : getImageMetadata(imageIndex); if (metadata != null) { if (metadata.isStandardMetadataFormatSupported() && formatName.equals (IIOMetadataFormatImpl.standardMetadataFormatName)) { return metadata; } String nativeName = metadata.getNativeMetadataFormatName(); if (nativeName != null && formatName.equals(nativeName)) { return metadata; } String[] extraNames = metadata.getExtraMetadataFormatNames(); if (extraNames != null) { for (int i = 0; i < extraNames.length; i++) { if (formatName.equals(extraNames[i])) { return metadata; } } } } return null; } /** * Returns an {@code IIOMetadata} object containing metadata * associated with the given image, or {@code null} if the * reader does not support reading metadata, is set to ignore * metadata, or if no metadata is available. * * @param imageIndex the index of the image whose metadata is to * be retrieved. * * @return an {@code IIOMetadata} object, or * {@code null}. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs during reading. */ public abstract IIOMetadata getImageMetadata(int imageIndex) throws IOException; /** * Returns an {@code IIOMetadata} object representing the * metadata associated with the given image, or {@code null} * if the reader does not support reading metadata or none * is available. * * <p> The resulting metadata object is only responsible for * returning documents in the format named by * {@code formatName}. Within any documents that are * returned, only nodes whose names are members of * {@code nodeNames} are required to be returned. In this * way, the amount of metadata processing done by the reader may * be kept to a minimum, based on what information is actually * needed. * * <p> If {@code formatName} is not the name of a supported * metadata format, {@code null} may be returned. * * <p> In all cases, it is legal to return a more capable metadata * object than strictly necessary. The format name and node names * are merely hints that may be used to reduce the reader's * workload. * * <p> The default implementation simply returns the result of * calling {@code getImageMetadata(imageIndex)}, after * checking that the format name is supported. If it is not, * {@code null} is returned. * * @param imageIndex the index of the image whose metadata is to * be retrieved. * @param formatName a metadata format name that may be used to retrieve * a document from the returned {@code IIOMetadata} object. * @param nodeNames a {@code Set} containing the names of * nodes that may be contained in a retrieved document. * * @return an {@code IIOMetadata} object, or {@code null}. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IllegalArgumentException if {@code formatName} * is {@code null}. * @exception IllegalArgumentException if {@code nodeNames} * is {@code null}. * @exception IOException if an error occurs during reading. */ public IIOMetadata getImageMetadata(int imageIndex, String formatName, Set<String> nodeNames) throws IOException { return getMetadata(formatName, nodeNames, false, imageIndex); } /** * Reads the image indexed by {@code imageIndex} and returns * it as a complete {@code BufferedImage}, using a default * {@code ImageReadParam}. This is a convenience method * that calls {@code read(imageIndex, null)}. * * <p> The image returned will be formatted according to the first * {@code ImageTypeSpecifier} returned from * {@code getImageTypes}. * * <p> Any registered {@code IIOReadProgressListener} objects * will be notified by calling their {@code imageStarted} * method, followed by calls to their {@code imageProgress} * method as the read progresses. Finally their * {@code imageComplete} method will be called. * {@code IIOReadUpdateListener} objects may be updated at * other times during the read as pixels are decoded. Finally, * {@code IIOReadWarningListener} objects will receive * notification of any non-fatal warnings that occur during * decoding. * * @param imageIndex the index of the image to be retrieved. * * @return the desired portion of the image as a * {@code BufferedImage}. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs during reading. */ public BufferedImage read(int imageIndex) throws IOException { return read(imageIndex, null); } /** * Reads the image indexed by {@code imageIndex} and returns * it as a complete {@code BufferedImage}, using a supplied * {@code ImageReadParam}. * * <p> The actual {@code BufferedImage} returned will be * chosen using the algorithm defined by the * {@code getDestination} method. * * <p> Any registered {@code IIOReadProgressListener} objects * will be notified by calling their {@code imageStarted} * method, followed by calls to their {@code imageProgress} * method as the read progresses. Finally their * {@code imageComplete} method will be called. * {@code IIOReadUpdateListener} objects may be updated at * other times during the read as pixels are decoded. Finally, * {@code IIOReadWarningListener} objects will receive * notification of any non-fatal warnings that occur during * decoding. * * <p> The set of source bands to be read and destination bands to * be written is determined by calling {@code getSourceBands} * and {@code getDestinationBands} on the supplied * {@code ImageReadParam}. If the lengths of the arrays * returned by these methods differ, the set of source bands * contains an index larger that the largest available source * index, or the set of destination bands contains an index larger * than the largest legal destination index, an * {@code IllegalArgumentException} is thrown. * * <p> If the supplied {@code ImageReadParam} contains * optional setting values not supported by this reader (<i>e.g.</i> * source render size or any format-specific settings), they will * be ignored. * * @param imageIndex the index of the image to be retrieved. * @param param an {@code ImageReadParam} used to control * the reading process, or {@code null}. * * @return the desired portion of the image as a * {@code BufferedImage}. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IllegalArgumentException if the set of source and * destination bands specified by * {@code param.getSourceBands} and * {@code param.getDestinationBands} differ in length or * include indices that are out of bounds. * @exception IllegalArgumentException if the resulting image would * have a width or height less than 1. * @exception IOException if an error occurs during reading. */ public abstract BufferedImage read(int imageIndex, ImageReadParam param) throws IOException; /** * Reads the image indexed by {@code imageIndex} and returns * an {@code IIOImage} containing the image, thumbnails, and * associated image metadata, using a supplied * {@code ImageReadParam}. * * <p> The actual {@code BufferedImage} referenced by the * returned {@code IIOImage} will be chosen using the * algorithm defined by the {@code getDestination} method. * * <p> Any registered {@code IIOReadProgressListener} objects * will be notified by calling their {@code imageStarted} * method, followed by calls to their {@code imageProgress} * method as the read progresses. Finally their * {@code imageComplete} method will be called. * {@code IIOReadUpdateListener} objects may be updated at * other times during the read as pixels are decoded. Finally, * {@code IIOReadWarningListener} objects will receive * notification of any non-fatal warnings that occur during * decoding. * * <p> The set of source bands to be read and destination bands to * be written is determined by calling {@code getSourceBands} * and {@code getDestinationBands} on the supplied * {@code ImageReadParam}. If the lengths of the arrays * returned by these methods differ, the set of source bands * contains an index larger that the largest available source * index, or the set of destination bands contains an index larger * than the largest legal destination index, an * {@code IllegalArgumentException} is thrown. * * <p> Thumbnails will be returned in their entirety regardless of * the region settings. * * <p> If the supplied {@code ImageReadParam} contains * optional setting values not supported by this reader (<i>e.g.</i> * source render size or any format-specific settings), those * values will be ignored. * * @param imageIndex the index of the image to be retrieved. * @param param an {@code ImageReadParam} used to control * the reading process, or {@code null}. * * @return an {@code IIOImage} containing the desired portion * of the image, a set of thumbnails, and associated image * metadata. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IllegalArgumentException if the set of source and * destination bands specified by * {@code param.getSourceBands} and * {@code param.getDestinationBands} differ in length or * include indices that are out of bounds. * @exception IllegalArgumentException if the resulting image * would have a width or height less than 1. * @exception IOException if an error occurs during reading. */ public IIOImage readAll(int imageIndex, ImageReadParam param) throws IOException { if (imageIndex < getMinIndex()) { throw new IndexOutOfBoundsException("imageIndex < getMinIndex()!"); } BufferedImage im = read(imageIndex, param); ArrayList<BufferedImage> thumbnails = null; int numThumbnails = getNumThumbnails(imageIndex); if (numThumbnails > 0) { thumbnails = new ArrayList<>(); for (int j = 0; j < numThumbnails; j++) { thumbnails.add(readThumbnail(imageIndex, j)); } } IIOMetadata metadata = getImageMetadata(imageIndex); return new IIOImage(im, thumbnails, metadata); } /** * Returns an {@code Iterator} containing all the images, * thumbnails, and metadata, starting at the index given by * {@code getMinIndex}, from the input source in the form of * {@code IIOImage} objects. An {@code Iterator} * containing {@code ImageReadParam} objects is supplied; one * element is consumed for each image read from the input source * until no more images are available. If the read param * {@code Iterator} runs out of elements, but there are still * more images available from the input source, default read * params are used for the remaining images. * * <p> If {@code params} is {@code null}, a default read * param will be used for all images. * * <p> The actual {@code BufferedImage} referenced by the * returned {@code IIOImage} will be chosen using the * algorithm defined by the {@code getDestination} method. * * <p> Any registered {@code IIOReadProgressListener} objects * will be notified by calling their {@code sequenceStarted} * method once. Then, for each image decoded, there will be a * call to {@code imageStarted}, followed by calls to * {@code imageProgress} as the read progresses, and finally * to {@code imageComplete}. The * {@code sequenceComplete} method will be called after the * last image has been decoded. * {@code IIOReadUpdateListener} objects may be updated at * other times during the read as pixels are decoded. Finally, * {@code IIOReadWarningListener} objects will receive * notification of any non-fatal warnings that occur during * decoding. * * <p> The set of source bands to be read and destination bands to * be written is determined by calling {@code getSourceBands} * and {@code getDestinationBands} on the supplied * {@code ImageReadParam}. If the lengths of the arrays * returned by these methods differ, the set of source bands * contains an index larger that the largest available source * index, or the set of destination bands contains an index larger * than the largest legal destination index, an * {@code IllegalArgumentException} is thrown. * * <p> Thumbnails will be returned in their entirety regardless of the * region settings. * * <p> If any of the supplied {@code ImageReadParam}s contain * optional setting values not supported by this reader (<i>e.g.</i> * source render size or any format-specific settings), they will * be ignored. * * @param params an {@code Iterator} containing * {@code ImageReadParam} objects. * * @return an {@code Iterator} representing the * contents of the input source as {@code IIOImage}s. * * @exception IllegalStateException if the input source has not been * set. * @exception IllegalArgumentException if any * non-{@code null} element of {@code params} is not an * {@code ImageReadParam}. * @exception IllegalArgumentException if the set of source and * destination bands specified by * {@code param.getSourceBands} and * {@code param.getDestinationBands} differ in length or * include indices that are out of bounds. * @exception IllegalArgumentException if a resulting image would * have a width or height less than 1. * @exception IOException if an error occurs during reading. * * @see ImageReadParam * @see IIOImage */ public Iterator<IIOImage> readAll(Iterator<? extends ImageReadParam> params) throws IOException { List<IIOImage> output = new ArrayList<>(); int imageIndex = getMinIndex(); // Inform IIOReadProgressListeners we're starting a sequence processSequenceStarted(imageIndex); while (true) { // Inform IIOReadProgressListeners and IIOReadUpdateListeners // that we're starting a new image ImageReadParam param = null; if (params != null && params.hasNext()) { Object o = params.next(); if (o != null) { if (o instanceof ImageReadParam) { param = (ImageReadParam)o; } else { throw new IllegalArgumentException ("Non-ImageReadParam supplied as part of params!"); } } } BufferedImage bi = null; try { bi = read(imageIndex, param); } catch (IndexOutOfBoundsException e) { break; } ArrayList<BufferedImage> thumbnails = null; int numThumbnails = getNumThumbnails(imageIndex); if (numThumbnails > 0) { thumbnails = new ArrayList<>(); for (int j = 0; j < numThumbnails; j++) { thumbnails.add(readThumbnail(imageIndex, j)); } } IIOMetadata metadata = getImageMetadata(imageIndex); IIOImage im = new IIOImage(bi, thumbnails, metadata); output.add(im); ++imageIndex; } // Inform IIOReadProgressListeners we're ending a sequence processSequenceComplete(); return output.iterator(); } /** * Returns {@code true} if this plug-in supports reading * just a {@link java.awt.image.Raster Raster} of pixel data. * If this method returns {@code false}, calls to * {@link #readRaster readRaster} or {@link #readTileRaster readTileRaster} * will throw an {@code UnsupportedOperationException}. * * <p> The default implementation returns {@code false}. * * @return {@code true} if this plug-in supports reading raw * {@code Raster}s. * * @see #readRaster * @see #readTileRaster */ public boolean canReadRaster() { return false; } /** * Returns a new {@code Raster} object containing the raw pixel data * from the image stream, without any color conversion applied. The * application must determine how to interpret the pixel data by other * means. Any destination or image-type parameters in the supplied * {@code ImageReadParam} object are ignored, but all other * parameters are used exactly as in the {@link #read read} * method, except that any destination offset is used as a logical rather * than a physical offset. The size of the returned {@code Raster} * will always be that of the source region clipped to the actual image. * Logical offsets in the stream itself are ignored. * * <p> This method allows formats that normally apply a color * conversion, such as JPEG, and formats that do not normally have an * associated colorspace, such as remote sensing or medical imaging data, * to provide access to raw pixel data. * * <p> Any registered {@code readUpdateListener}s are ignored, as * there is no {@code BufferedImage}, but all other listeners are * called exactly as they are for the {@link #read read} method. * * <p> If {@link #canReadRaster canReadRaster()} returns * {@code false}, this method throws an * {@code UnsupportedOperationException}. * * <p> If the supplied {@code ImageReadParam} contains * optional setting values not supported by this reader (<i>e.g.</i> * source render size or any format-specific settings), they will * be ignored. * * <p> The default implementation throws an * {@code UnsupportedOperationException}. * * @param imageIndex the index of the image to be read. * @param param an {@code ImageReadParam} used to control * the reading process, or {@code null}. * * @return the desired portion of the image as a * {@code Raster}. * * @exception UnsupportedOperationException if this plug-in does not * support reading raw {@code Raster}s. * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs during reading. * * @see #canReadRaster * @see #read * @see java.awt.image.Raster */ public Raster readRaster(int imageIndex, ImageReadParam param) throws IOException { throw new UnsupportedOperationException("readRaster not supported!"); } /** * Returns {@code true} if the image is organized into * <i>tiles</i>, that is, equal-sized non-overlapping rectangles. * * <p> A reader plug-in may choose whether or not to expose tiling * that is present in the image as it is stored. It may even * choose to advertise tiling when none is explicitly present. In * general, tiling should only be advertised if there is some * advantage (in speed or space) to accessing individual tiles. * Regardless of whether the reader advertises tiling, it must be * capable of reading an arbitrary rectangular region specified in * an {@code ImageReadParam}. * * <p> A reader for which all images are guaranteed to be tiled, * or are guaranteed not to be tiled, may return {@code true} * or {@code false} respectively without accessing any image * data. In such cases, it is not necessary to throw an exception * even if no input source has been set or the image index is out * of bounds. * * <p> The default implementation just returns {@code false}. * * @param imageIndex the index of the image to be queried. * * @return {@code true} if the image is tiled. * * @exception IllegalStateException if an input source is required * to determine the return value, but none has been set. * @exception IndexOutOfBoundsException if an image must be * accessed to determine the return value, but the supplied index * is out of bounds. * @exception IOException if an error occurs during reading. */ public boolean isImageTiled(int imageIndex) throws IOException { return false; } /** * Returns the width of a tile in the given image. * * <p> The default implementation simply returns * {@code getWidth(imageIndex)}, which is correct for * non-tiled images. Readers that support tiling should override * this method. * * @return the width of a tile. * * @param imageIndex the index of the image to be queried. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs during reading. */ public int getTileWidth(int imageIndex) throws IOException { return getWidth(imageIndex); } /** * Returns the height of a tile in the given image. * * <p> The default implementation simply returns * {@code getHeight(imageIndex)}, which is correct for * non-tiled images. Readers that support tiling should override * this method. * * @return the height of a tile. * * @param imageIndex the index of the image to be queried. * * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IOException if an error occurs during reading. */ public int getTileHeight(int imageIndex) throws IOException { return getHeight(imageIndex); } /** * Returns the X coordinate of the upper-left corner of tile (0, * 0) in the given image. * * <p> A reader for which the tile grid X offset always has the * same value (usually 0), may return the value without accessing * any image data. In such cases, it is not necessary to throw an * exception even if no input source has been set or the image * index is out of bounds. * * <p> The default implementation simply returns 0, which is * correct for non-tiled images and tiled images in most formats. * Readers that support tiling with non-(0, 0) offsets should * override this method. * * @return the X offset of the tile grid. * * @param imageIndex the index of the image to be queried. * * @exception IllegalStateException if an input source is required * to determine the return value, but none has been set. * @exception IndexOutOfBoundsException if an image must be * accessed to determine the return value, but the supplied index * is out of bounds. * @exception IOException if an error occurs during reading. */ public int getTileGridXOffset(int imageIndex) throws IOException { return 0; } /** * Returns the Y coordinate of the upper-left corner of tile (0, * 0) in the given image. * * <p> A reader for which the tile grid Y offset always has the * same value (usually 0), may return the value without accessing * any image data. In such cases, it is not necessary to throw an * exception even if no input source has been set or the image * index is out of bounds. * * <p> The default implementation simply returns 0, which is * correct for non-tiled images and tiled images in most formats. * Readers that support tiling with non-(0, 0) offsets should * override this method. * * @return the Y offset of the tile grid. * * @param imageIndex the index of the image to be queried. * * @exception IllegalStateException if an input source is required * to determine the return value, but none has been set. * @exception IndexOutOfBoundsException if an image must be * accessed to determine the return value, but the supplied index * is out of bounds. * @exception IOException if an error occurs during reading. */ public int getTileGridYOffset(int imageIndex) throws IOException { return 0; } /** * Reads the tile indicated by the {@code tileX} and * {@code tileY} arguments, returning it as a * {@code BufferedImage}. If the arguments are out of range, * an {@code IllegalArgumentException} is thrown. If the * image is not tiled, the values 0, 0 will return the entire * image; any other values will cause an * {@code IllegalArgumentException} to be thrown. * * <p> This method is merely a convenience equivalent to calling * {@code read(int, ImageReadParam)} with a read param * specifying a source region having offsets of * {@code tileX*getTileWidth(imageIndex)}, * {@code tileY*getTileHeight(imageIndex)} and width and * height of {@code getTileWidth(imageIndex)}, * {@code getTileHeight(imageIndex)}; and subsampling * factors of 1 and offsets of 0. To subsample a tile, call * {@code read} with a read param specifying this region * and different subsampling parameters. * * <p> The default implementation returns the entire image if * {@code tileX} and {@code tileY} are 0, or throws * an {@code IllegalArgumentException} otherwise. * * @param imageIndex the index of the image to be retrieved. * @param tileX the column index (starting with 0) of the tile * to be retrieved. * @param tileY the row index (starting with 0) of the tile * to be retrieved. * * @return the tile as a {@code BufferedImage}. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if {@code imageIndex} * is out of bounds. * @exception IllegalArgumentException if the tile indices are * out of bounds. * @exception IOException if an error occurs during reading. */ public BufferedImage readTile(int imageIndex, int tileX, int tileY) throws IOException { if ((tileX != 0) || (tileY != 0)) { throw new IllegalArgumentException("Invalid tile indices"); } return read(imageIndex); } /** * Returns a new {@code Raster} object containing the raw * pixel data from the tile, without any color conversion applied. * The application must determine how to interpret the pixel data by other * means. * * <p> If {@link #canReadRaster canReadRaster()} returns * {@code false}, this method throws an * {@code UnsupportedOperationException}. * * <p> The default implementation checks if reading * {@code Raster}s is supported, and if so calls {@link * #readRaster readRaster(imageIndex, null)} if * {@code tileX} and {@code tileY} are 0, or throws an * {@code IllegalArgumentException} otherwise. * * @param imageIndex the index of the image to be retrieved. * @param tileX the column index (starting with 0) of the tile * to be retrieved. * @param tileY the row index (starting with 0) of the tile * to be retrieved. * * @return the tile as a {@code Raster}. * * @exception UnsupportedOperationException if this plug-in does not * support reading raw {@code Raster}s. * @exception IllegalArgumentException if the tile indices are * out of bounds. * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if {@code imageIndex} * is out of bounds. * @exception IOException if an error occurs during reading. * * @see #readTile * @see #readRaster * @see java.awt.image.Raster */ public Raster readTileRaster(int imageIndex, int tileX, int tileY) throws IOException { if (!canReadRaster()) { throw new UnsupportedOperationException ("readTileRaster not supported!"); } if ((tileX != 0) || (tileY != 0)) { throw new IllegalArgumentException("Invalid tile indices"); } return readRaster(imageIndex, null); } // RenderedImages /** * Returns a {@code RenderedImage} object that contains the * contents of the image indexed by {@code imageIndex}. By * default, the returned image is simply the * {@code BufferedImage} returned by * {@code read(imageIndex, param)}. * * <p> The semantics of this method may differ from those of the * other {@code read} methods in several ways. First, any * destination image and/or image type set in the * {@code ImageReadParam} may be ignored. Second, the usual * listener calls are not guaranteed to be made, or to be * meaningful if they are. This is because the returned image may * not be fully populated with pixel data at the time it is * returned, or indeed at any time. * * <p> If the supplied {@code ImageReadParam} contains * optional setting values not supported by this reader (<i>e.g.</i> * source render size or any format-specific settings), they will * be ignored. * * <p> The default implementation just calls * {@link #read read(imageIndex, param)}. * * @param imageIndex the index of the image to be retrieved. * @param param an {@code ImageReadParam} used to control * the reading process, or {@code null}. * * @return a {@code RenderedImage} object providing a view of * the image. * * @exception IllegalStateException if the input source has not been * set. * @exception IndexOutOfBoundsException if the supplied index is * out of bounds. * @exception IllegalArgumentException if the set of source and * destination bands specified by * {@code param.getSourceBands} and * {@code param.getDestinationBands} differ in length or * include indices that are out of bounds. * @exception IllegalArgumentException if the resulting image * would have a width or height less than 1. * @exception IOException if an error occurs during reading. */ public RenderedImage readAsRenderedImage(int imageIndex, ImageReadParam param) throws IOException { return read(imageIndex, param); } // Thumbnails /** * Returns {@code true} if the image format understood by * this reader supports thumbnail preview images associated with * it. The default implementation returns {@code false}. * * <p> If this method returns {@code false}, * {@code hasThumbnails} and {@code getNumThumbnails} * will return {@code false} and {@code 0}, * respectively, and {@code readThumbnail} will throw an * {@code UnsupportedOperationException}, regardless of their * arguments. * * <p> A reader that does not support thumbnails need not * implement any of the thumbnail-related methods. * * @return {@code true} if thumbnails are supported. */ public boolean readerSupportsThumbnails() { return false; } /** * Returns {@code true} if the given image has thumbnail * preview images associated with it. If the format does not * support thumbnails ({@code readerSupportsThumbnails} * returns {@code false}), {@code false} will be * returned regardless of whether an input source has been set or * whether {@code imageIndex} is in bounds. * * <p> The default implementation returns {@code true} if * {@code getNumThumbnails} returns a value greater than 0. * * @param imageIndex the index of the image being queried. * * @return {@code true} if the given image has thumbnails. * * @exception IllegalStateException if the reader supports * thumbnails but the input source has not been set. * @exception IndexOutOfBoundsException if the reader supports * thumbnails but {@code imageIndex} is out of bounds. * @exception IOException if an error occurs during reading. */ public boolean hasThumbnails(int imageIndex) throws IOException { return getNumThumbnails(imageIndex) > 0; } /** * Returns the number of thumbnail preview images associated with * the given image. If the format does not support thumbnails, * ({@code readerSupportsThumbnails} returns * {@code false}), {@code 0} will be returned regardless * of whether an input source has been set or whether * {@code imageIndex} is in bounds. * * <p> The default implementation returns 0 without checking its * argument. * * @param imageIndex the index of the image being queried. * * @return the number of thumbnails associated with the given * image. * * @exception IllegalStateException if the reader supports * thumbnails but the input source has not been set. * @exception IndexOutOfBoundsException if the reader supports * thumbnails but {@code imageIndex} is out of bounds. * @exception IOException if an error occurs during reading. */ public int getNumThumbnails(int imageIndex) throws IOException { return 0; } /** * Returns the width of the thumbnail preview image indexed by * {@code thumbnailIndex}, associated with the image indexed * by {@code ImageIndex}. * * <p> If the reader does not support thumbnails, * ({@code readerSupportsThumbnails} returns * {@code false}), an {@code UnsupportedOperationException} * will be thrown. * * <p> The default implementation simply returns * {@code readThumbnail(imageindex, thumbnailIndex).getWidth()}. * Subclasses should therefore * override this method if possible in order to avoid forcing the * thumbnail to be read. * * @param imageIndex the index of the image to be retrieved. * @param thumbnailIndex the index of the thumbnail to be retrieved. * * @return the width of the desired thumbnail as an {@code int}. * * @exception UnsupportedOperationException if thumbnails are not * supported. * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if either of the supplied * indices are out of bounds. * @exception IOException if an error occurs during reading. */ public int getThumbnailWidth(int imageIndex, int thumbnailIndex) throws IOException { return readThumbnail(imageIndex, thumbnailIndex).getWidth(); } /** * Returns the height of the thumbnail preview image indexed by * {@code thumbnailIndex}, associated with the image indexed * by {@code ImageIndex}. * * <p> If the reader does not support thumbnails, * ({@code readerSupportsThumbnails} returns * {@code false}), an {@code UnsupportedOperationException} * will be thrown. * * <p> The default implementation simply returns * {@code readThumbnail(imageindex, thumbnailIndex).getHeight()}. * Subclasses should therefore override * this method if possible in order to avoid * forcing the thumbnail to be read. * * @param imageIndex the index of the image to be retrieved. * @param thumbnailIndex the index of the thumbnail to be retrieved. * * @return the height of the desired thumbnail as an {@code int}. * * @exception UnsupportedOperationException if thumbnails are not * supported. * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if either of the supplied * indices are out of bounds. * @exception IOException if an error occurs during reading. */ public int getThumbnailHeight(int imageIndex, int thumbnailIndex) throws IOException { return readThumbnail(imageIndex, thumbnailIndex).getHeight(); } /** * Returns the thumbnail preview image indexed by * {@code thumbnailIndex}, associated with the image indexed * by {@code ImageIndex} as a {@code BufferedImage}. * * <p> Any registered {@code IIOReadProgressListener} objects * will be notified by calling their * {@code thumbnailStarted}, {@code thumbnailProgress}, * and {@code thumbnailComplete} methods. * * <p> If the reader does not support thumbnails, * ({@code readerSupportsThumbnails} returns * {@code false}), an {@code UnsupportedOperationException} * will be thrown regardless of whether an input source has been * set or whether the indices are in bounds. * * <p> The default implementation throws an * {@code UnsupportedOperationException}. * * @param imageIndex the index of the image to be retrieved. * @param thumbnailIndex the index of the thumbnail to be retrieved. * * @return the desired thumbnail as a {@code BufferedImage}. * * @exception UnsupportedOperationException if thumbnails are not * supported. * @exception IllegalStateException if the input source has not been set. * @exception IndexOutOfBoundsException if either of the supplied * indices are out of bounds. * @exception IOException if an error occurs during reading. */ public BufferedImage readThumbnail(int imageIndex, int thumbnailIndex) throws IOException { throw new UnsupportedOperationException("Thumbnails not supported!"); } // Abort /** * Requests that any current read operation be aborted. The * contents of the image following the abort will be undefined. * * <p> Readers should call {@code clearAbortRequest} at the * beginning of each read operation, and poll the value of * {@code abortRequested} regularly during the read. */ public synchronized void abort() { this.abortFlag = true; } /** * Returns {@code true} if a request to abort the current * read operation has been made since the reader was instantiated or * {@code clearAbortRequest} was called. * * @return {@code true} if the current read operation should * be aborted. * * @see #abort * @see #clearAbortRequest */ protected synchronized boolean abortRequested() { return this.abortFlag; } /** * Clears any previous abort request. After this method has been * called, {@code abortRequested} will return * {@code false}. * * @see #abort * @see #abortRequested */ protected synchronized void clearAbortRequest() { this.abortFlag = false; } // Listeners // Add an element to a list, creating a new list if the // existing list is null, and return the list. static <T> List<T> addToList(List<T> l, T elt) { if (l == null) { l = new ArrayList<>(); } l.add(elt); return l; } // Remove an element from a list, discarding the list if the // resulting list is empty, and return the list or null. static <T> List<T> removeFromList(List<T> l, T elt) { if (l == null) { return l; } l.remove(elt); if (l.size() == 0) { l = null; } return l; } /** * Adds an {@code IIOReadWarningListener} to the list of * registered warning listeners. If {@code listener} is * {@code null}, no exception will be thrown and no action * will be taken. Messages sent to the given listener will be * localized, if possible, to match the current * {@code Locale}. If no {@code Locale} has been set, * warning messages may be localized as the reader sees fit. * * @param listener an {@code IIOReadWarningListener} to be registered. * * @see #removeIIOReadWarningListener */ public void addIIOReadWarningListener(IIOReadWarningListener listener) { if (listener == null) { return; } warningListeners = addToList(warningListeners, listener); warningLocales = addToList(warningLocales, getLocale()); } /** * Removes an {@code IIOReadWarningListener} from the list of * registered error listeners. If the listener was not previously * registered, or if {@code listener} is {@code null}, * no exception will be thrown and no action will be taken. * * @param listener an IIOReadWarningListener to be unregistered. * * @see #addIIOReadWarningListener */ public void removeIIOReadWarningListener(IIOReadWarningListener listener) { if (listener == null || warningListeners == null) { return; } int index = warningListeners.indexOf(listener); if (index != -1) { warningListeners.remove(index); warningLocales.remove(index); if (warningListeners.size() == 0) { warningListeners = null; warningLocales = null; } } } /** * Removes all currently registered * {@code IIOReadWarningListener} objects. * * <p> The default implementation sets the * {@code warningListeners} and {@code warningLocales} * instance variables to {@code null}. */ public void removeAllIIOReadWarningListeners() { warningListeners = null; warningLocales = null; } /** * Adds an {@code IIOReadProgressListener} to the list of * registered progress listeners. If {@code listener} is * {@code null}, no exception will be thrown and no action * will be taken. * * @param listener an IIOReadProgressListener to be registered. * * @see #removeIIOReadProgressListener */ public void addIIOReadProgressListener(IIOReadProgressListener listener) { if (listener == null) { return; } progressListeners = addToList(progressListeners, listener); } /** * Removes an {@code IIOReadProgressListener} from the list * of registered progress listeners. If the listener was not * previously registered, or if {@code listener} is * {@code null}, no exception will be thrown and no action * will be taken. * * @param listener an IIOReadProgressListener to be unregistered. * * @see #addIIOReadProgressListener */ public void removeIIOReadProgressListener (IIOReadProgressListener listener) { if (listener == null || progressListeners == null) { return; } progressListeners = removeFromList(progressListeners, listener); } /** * Removes all currently registered * {@code IIOReadProgressListener} objects. * * <p> The default implementation sets the * {@code progressListeners} instance variable to * {@code null}. */ public void removeAllIIOReadProgressListeners() { progressListeners = null; } /** * Adds an {@code IIOReadUpdateListener} to the list of * registered update listeners. If {@code listener} is * {@code null}, no exception will be thrown and no action * will be taken. The listener will receive notification of pixel * updates as images and thumbnails are decoded, including the * starts and ends of progressive passes. * * <p> If no update listeners are present, the reader may choose * to perform fewer updates to the pixels of the destination * images and/or thumbnails, which may result in more efficient * decoding. * * <p> For example, in progressive JPEG decoding each pass * contains updates to a set of coefficients, which would have to * be transformed into pixel values and converted to an RGB color * space for each pass if listeners are present. If no listeners * are present, the coefficients may simply be accumulated and the * final results transformed and color converted one time only. * * <p> The final results of decoding will be the same whether or * not intermediate updates are performed. Thus if only the final * image is desired it may be preferable not to register any * {@code IIOReadUpdateListener}s. In general, progressive * updating is most effective when fetching images over a network * connection that is very slow compared to local CPU processing; * over a fast connection, progressive updates may actually slow * down the presentation of the image. * * @param listener an IIOReadUpdateListener to be registered. * * @see #removeIIOReadUpdateListener */ public void addIIOReadUpdateListener(IIOReadUpdateListener listener) { if (listener == null) { return; } updateListeners = addToList(updateListeners, listener); } /** * Removes an {@code IIOReadUpdateListener} from the list of * registered update listeners. If the listener was not * previously registered, or if {@code listener} is * {@code null}, no exception will be thrown and no action * will be taken. * * @param listener an IIOReadUpdateListener to be unregistered. * * @see #addIIOReadUpdateListener */ public void removeIIOReadUpdateListener(IIOReadUpdateListener listener) { if (listener == null || updateListeners == null) { return; } updateListeners = removeFromList(updateListeners, listener); } /** * Removes all currently registered * {@code IIOReadUpdateListener} objects. * * <p> The default implementation sets the * {@code updateListeners} instance variable to * {@code null}. */ public void removeAllIIOReadUpdateListeners() { updateListeners = null; } /** * Broadcasts the start of an sequence of image reads to all * registered {@code IIOReadProgressListener}s by calling * their {@code sequenceStarted} method. Subclasses may use * this method as a convenience. * * @param minIndex the lowest index being read. */ protected void processSequenceStarted(int minIndex) { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.sequenceStarted(this, minIndex); } } /** * Broadcasts the completion of an sequence of image reads to all * registered {@code IIOReadProgressListener}s by calling * their {@code sequenceComplete} method. Subclasses may use * this method as a convenience. */ protected void processSequenceComplete() { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.sequenceComplete(this); } } /** * Broadcasts the start of an image read to all registered * {@code IIOReadProgressListener}s by calling their * {@code imageStarted} method. Subclasses may use this * method as a convenience. * * @param imageIndex the index of the image about to be read. */ protected void processImageStarted(int imageIndex) { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.imageStarted(this, imageIndex); } } /** * Broadcasts the current percentage of image completion to all * registered {@code IIOReadProgressListener}s by calling * their {@code imageProgress} method. Subclasses may use * this method as a convenience. * * @param percentageDone the current percentage of completion, * as a {@code float}. */ protected void processImageProgress(float percentageDone) { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.imageProgress(this, percentageDone); } } /** * Broadcasts the completion of an image read to all registered * {@code IIOReadProgressListener}s by calling their * {@code imageComplete} method. Subclasses may use this * method as a convenience. */ protected void processImageComplete() { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.imageComplete(this); } } /** * Broadcasts the start of a thumbnail read to all registered * {@code IIOReadProgressListener}s by calling their * {@code thumbnailStarted} method. Subclasses may use this * method as a convenience. * * @param imageIndex the index of the image associated with the * thumbnail. * @param thumbnailIndex the index of the thumbnail. */ protected void processThumbnailStarted(int imageIndex, int thumbnailIndex) { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.thumbnailStarted(this, imageIndex, thumbnailIndex); } } /** * Broadcasts the current percentage of thumbnail completion to * all registered {@code IIOReadProgressListener}s by calling * their {@code thumbnailProgress} method. Subclasses may * use this method as a convenience. * * @param percentageDone the current percentage of completion, * as a {@code float}. */ protected void processThumbnailProgress(float percentageDone) { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.thumbnailProgress(this, percentageDone); } } /** * Broadcasts the completion of a thumbnail read to all registered * {@code IIOReadProgressListener}s by calling their * {@code thumbnailComplete} method. Subclasses may use this * method as a convenience. */ protected void processThumbnailComplete() { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.thumbnailComplete(this); } } /** * Broadcasts that the read has been aborted to all registered * {@code IIOReadProgressListener}s by calling their * {@code readAborted} method. Subclasses may use this * method as a convenience. */ protected void processReadAborted() { if (progressListeners == null) { return; } int numListeners = progressListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadProgressListener listener = progressListeners.get(i); listener.readAborted(this); } } /** * Broadcasts the beginning of a progressive pass to all * registered {@code IIOReadUpdateListener}s by calling their * {@code passStarted} method. Subclasses may use this * method as a convenience. * * @param theImage the {@code BufferedImage} being updated. * @param pass the index of the current pass, starting with 0. * @param minPass the index of the first pass that will be decoded. * @param maxPass the index of the last pass that will be decoded. * @param minX the X coordinate of the upper-left pixel included * in the pass. * @param minY the X coordinate of the upper-left pixel included * in the pass. * @param periodX the horizontal separation between pixels. * @param periodY the vertical separation between pixels. * @param bands an array of {@code int}s indicating the * set of affected bands of the destination. */ protected void processPassStarted(BufferedImage theImage, int pass, int minPass, int maxPass, int minX, int minY, int periodX, int periodY, int[] bands) { if (updateListeners == null) { return; } int numListeners = updateListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadUpdateListener listener = updateListeners.get(i); listener.passStarted(this, theImage, pass, minPass, maxPass, minX, minY, periodX, periodY, bands); } } /** * Broadcasts the update of a set of samples to all registered * {@code IIOReadUpdateListener}s by calling their * {@code imageUpdate} method. Subclasses may use this * method as a convenience. * * @param theImage the {@code BufferedImage} being updated. * @param minX the X coordinate of the upper-left pixel included * in the pass. * @param minY the X coordinate of the upper-left pixel included * in the pass. * @param width the total width of the area being updated, including * pixels being skipped if {@code periodX > 1}. * @param height the total height of the area being updated, * including pixels being skipped if {@code periodY > 1}. * @param periodX the horizontal separation between pixels. * @param periodY the vertical separation between pixels. * @param bands an array of {@code int}s indicating the * set of affected bands of the destination. */ protected void processImageUpdate(BufferedImage theImage, int minX, int minY, int width, int height, int periodX, int periodY, int[] bands) { if (updateListeners == null) { return; } int numListeners = updateListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadUpdateListener listener = updateListeners.get(i); listener.imageUpdate(this, theImage, minX, minY, width, height, periodX, periodY, bands); } } /** * Broadcasts the end of a progressive pass to all * registered {@code IIOReadUpdateListener}s by calling their * {@code passComplete} method. Subclasses may use this * method as a convenience. * * @param theImage the {@code BufferedImage} being updated. */ protected void processPassComplete(BufferedImage theImage) { if (updateListeners == null) { return; } int numListeners = updateListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadUpdateListener listener = updateListeners.get(i); listener.passComplete(this, theImage); } } /** * Broadcasts the beginning of a thumbnail progressive pass to all * registered {@code IIOReadUpdateListener}s by calling their * {@code thumbnailPassStarted} method. Subclasses may use this * method as a convenience. * * @param theThumbnail the {@code BufferedImage} thumbnail * being updated. * @param pass the index of the current pass, starting with 0. * @param minPass the index of the first pass that will be decoded. * @param maxPass the index of the last pass that will be decoded. * @param minX the X coordinate of the upper-left pixel included * in the pass. * @param minY the X coordinate of the upper-left pixel included * in the pass. * @param periodX the horizontal separation between pixels. * @param periodY the vertical separation between pixels. * @param bands an array of {@code int}s indicating the * set of affected bands of the destination. */ protected void processThumbnailPassStarted(BufferedImage theThumbnail, int pass, int minPass, int maxPass, int minX, int minY, int periodX, int periodY, int[] bands) { if (updateListeners == null) { return; } int numListeners = updateListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadUpdateListener listener = updateListeners.get(i); listener.thumbnailPassStarted(this, theThumbnail, pass, minPass, maxPass, minX, minY, periodX, periodY, bands); } } /** * Broadcasts the update of a set of samples in a thumbnail image * to all registered {@code IIOReadUpdateListener}s by * calling their {@code thumbnailUpdate} method. Subclasses may * use this method as a convenience. * * @param theThumbnail the {@code BufferedImage} thumbnail * being updated. * @param minX the X coordinate of the upper-left pixel included * in the pass. * @param minY the X coordinate of the upper-left pixel included * in the pass. * @param width the total width of the area being updated, including * pixels being skipped if {@code periodX > 1}. * @param height the total height of the area being updated, * including pixels being skipped if {@code periodY > 1}. * @param periodX the horizontal separation between pixels. * @param periodY the vertical separation between pixels. * @param bands an array of {@code int}s indicating the * set of affected bands of the destination. */ protected void processThumbnailUpdate(BufferedImage theThumbnail, int minX, int minY, int width, int height, int periodX, int periodY, int[] bands) { if (updateListeners == null) { return; } int numListeners = updateListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadUpdateListener listener = updateListeners.get(i); listener.thumbnailUpdate(this, theThumbnail, minX, minY, width, height, periodX, periodY, bands); } } /** * Broadcasts the end of a thumbnail progressive pass to all * registered {@code IIOReadUpdateListener}s by calling their * {@code thumbnailPassComplete} method. Subclasses may use this * method as a convenience. * * @param theThumbnail the {@code BufferedImage} thumbnail * being updated. */ protected void processThumbnailPassComplete(BufferedImage theThumbnail) { if (updateListeners == null) { return; } int numListeners = updateListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadUpdateListener listener = updateListeners.get(i); listener.thumbnailPassComplete(this, theThumbnail); } } /** * Broadcasts a warning message to all registered * {@code IIOReadWarningListener}s by calling their * {@code warningOccurred} method. Subclasses may use this * method as a convenience. * * @param warning the warning message to send. * * @exception IllegalArgumentException if {@code warning} * is {@code null}. */ protected void processWarningOccurred(String warning) { if (warningListeners == null) { return; } if (warning == null) { throw new IllegalArgumentException("warning == null!"); } int numListeners = warningListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadWarningListener listener = warningListeners.get(i); listener.warningOccurred(this, warning); } } /** * Broadcasts a localized warning message to all registered * {@code IIOReadWarningListener}s by calling their * {@code warningOccurred} method with a string taken * from a {@code ResourceBundle}. Subclasses may use this * method as a convenience. * * @param baseName the base name of a set of * {@code ResourceBundle}s containing localized warning * messages. * @param keyword the keyword used to index the warning message * within the set of {@code ResourceBundle}s. * * @exception IllegalArgumentException if {@code baseName} * is {@code null}. * @exception IllegalArgumentException if {@code keyword} * is {@code null}. * @exception IllegalArgumentException if no appropriate * {@code ResourceBundle} may be located. * @exception IllegalArgumentException if the named resource is * not found in the located {@code ResourceBundle}. * @exception IllegalArgumentException if the object retrieved * from the {@code ResourceBundle} is not a * {@code String}. */ protected void processWarningOccurred(String baseName, String keyword) { if (warningListeners == null) { return; } if (baseName == null) { throw new IllegalArgumentException("baseName == null!"); } if (keyword == null) { throw new IllegalArgumentException("keyword == null!"); } int numListeners = warningListeners.size(); for (int i = 0; i < numListeners; i++) { IIOReadWarningListener listener = warningListeners.get(i); Locale locale = warningLocales.get(i); if (locale == null) { locale = Locale.getDefault(); } /* * Only the plugin knows the messages that are provided, so we * can always locate the resource bundles from the same loader * as that for the plugin code itself. */ ResourceBundle bundle = null; try { bundle = ResourceBundle.getBundle(baseName, locale, this.getClass().getModule()); } catch (MissingResourceException mre) { throw new IllegalArgumentException("Bundle not found!", mre); } String warning = null; try { warning = bundle.getString(keyword); } catch (ClassCastException cce) { throw new IllegalArgumentException("Resource is not a String!", cce); } catch (MissingResourceException mre) { throw new IllegalArgumentException("Resource is missing!", mre); } listener.warningOccurred(this, warning); } } // State management /** * Restores the {@code ImageReader} to its initial state. * * <p> The default implementation calls * {@code setInput(null, false)}, * {@code setLocale(null)}, * {@code removeAllIIOReadUpdateListeners()}, * {@code removeAllIIOReadWarningListeners()}, * {@code removeAllIIOReadProgressListeners()}, and * {@code clearAbortRequest}. */ public void reset() { setInput(null, false, false); setLocale(null); removeAllIIOReadUpdateListeners(); removeAllIIOReadProgressListeners(); removeAllIIOReadWarningListeners(); clearAbortRequest(); } /** * Allows any resources held by this object to be released. The * result of calling any other method (other than * {@code finalize}) subsequent to a call to this method * is undefined. * * <p>It is important for applications to call this method when they * know they will no longer be using this {@code ImageReader}. * Otherwise, the reader may continue to hold on to resources * indefinitely. * * <p>The default implementation of this method in the superclass does * nothing. Subclass implementations should ensure that all resources, * especially native resources, are released. */ public void dispose() { } // Utility methods /** * A utility method that may be used by readers to compute the * region of the source image that should be read, taking into * account any source region and subsampling offset settings in * the supplied {@code ImageReadParam}. The actual * subsampling factors, destination size, and destination offset * are <em>not</em> taken into consideration, thus further * clipping must take place. The {@link #computeRegions computeRegions} * method performs all necessary clipping. * * @param param the {@code ImageReadParam} being used, or * {@code null}. * @param srcWidth the width of the source image. * @param srcHeight the height of the source image. * * @return the source region as a {@code Rectangle}. */ protected static Rectangle getSourceRegion(ImageReadParam param, int srcWidth, int srcHeight) { Rectangle sourceRegion = new Rectangle(0, 0, srcWidth, srcHeight); if (param != null) { Rectangle region = param.getSourceRegion(); if (region != null) { sourceRegion = sourceRegion.intersection(region); } int subsampleXOffset = param.getSubsamplingXOffset(); int subsampleYOffset = param.getSubsamplingYOffset(); sourceRegion.x += subsampleXOffset; sourceRegion.y += subsampleYOffset; sourceRegion.width -= subsampleXOffset; sourceRegion.height -= subsampleYOffset; } return sourceRegion; } /** * Computes the source region of interest and the destination * region of interest, taking the width and height of the source * image, an optional destination image, and an optional * {@code ImageReadParam} into account. The source region * begins with the entire source image. Then that is clipped to * the source region specified in the {@code ImageReadParam}, * if one is specified. * * <p> If either of the destination offsets are negative, the * source region is clipped so that its top left will coincide * with the top left of the destination image, taking subsampling * into account. Then the result is clipped to the destination * image on the right and bottom, if one is specified, taking * subsampling and destination offsets into account. * * <p> Similarly, the destination region begins with the source * image, is translated to the destination offset given in the * {@code ImageReadParam} if there is one, and finally is * clipped to the destination image, if there is one. * * <p> If either the source or destination regions end up having a * width or height of 0, an {@code IllegalArgumentException} * is thrown. * * <p> The {@link #getSourceRegion getSourceRegion>} * method may be used if only source clipping is desired. * * @param param an {@code ImageReadParam}, or {@code null}. * @param srcWidth the width of the source image. * @param srcHeight the height of the source image. * @param image a {@code BufferedImage} that will be the * destination image, or {@code null}. * @param srcRegion a {@code Rectangle} that will be filled with * the source region of interest. * @param destRegion a {@code Rectangle} that will be filled with * the destination region of interest. * @exception IllegalArgumentException if {@code srcRegion} * is {@code null}. * @exception IllegalArgumentException if {@code dstRegion} * is {@code null}. * @exception IllegalArgumentException if the resulting source or * destination region is empty. */ protected static void computeRegions(ImageReadParam param, int srcWidth, int srcHeight, BufferedImage image, Rectangle srcRegion, Rectangle destRegion) { if (srcRegion == null) { throw new IllegalArgumentException("srcRegion == null!"); } if (destRegion == null) { throw new IllegalArgumentException("destRegion == null!"); } // Start with the entire source image srcRegion.setBounds(0, 0, srcWidth, srcHeight); // Destination also starts with source image, as that is the // maximum extent if there is no subsampling destRegion.setBounds(0, 0, srcWidth, srcHeight); // Clip that to the param region, if there is one int periodX = 1; int periodY = 1; int gridX = 0; int gridY = 0; if (param != null) { Rectangle paramSrcRegion = param.getSourceRegion(); if (paramSrcRegion != null) { srcRegion.setBounds(srcRegion.intersection(paramSrcRegion)); } periodX = param.getSourceXSubsampling(); periodY = param.getSourceYSubsampling(); gridX = param.getSubsamplingXOffset(); gridY = param.getSubsamplingYOffset(); srcRegion.translate(gridX, gridY); srcRegion.width -= gridX; srcRegion.height -= gridY; destRegion.setLocation(param.getDestinationOffset()); } // Now clip any negative destination offsets, i.e. clip // to the top and left of the destination image if (destRegion.x < 0) { int delta = -destRegion.x*periodX; srcRegion.x += delta; srcRegion.width -= delta; destRegion.x = 0; } if (destRegion.y < 0) { int delta = -destRegion.y*periodY; srcRegion.y += delta; srcRegion.height -= delta; destRegion.y = 0; } // Now clip the destination Region to the subsampled width and height int subsampledWidth = (srcRegion.width + periodX - 1)/periodX; int subsampledHeight = (srcRegion.height + periodY - 1)/periodY; destRegion.width = subsampledWidth; destRegion.height = subsampledHeight; // Now clip that to right and bottom of the destination image, // if there is one, taking subsampling into account if (image != null) { Rectangle destImageRect = new Rectangle(0, 0, image.getWidth(), image.getHeight()); destRegion.setBounds(destRegion.intersection(destImageRect)); if (destRegion.isEmpty()) { throw new IllegalArgumentException ("Empty destination region!"); } int deltaX = destRegion.x + subsampledWidth - image.getWidth(); if (deltaX > 0) { srcRegion.width -= deltaX*periodX; } int deltaY = destRegion.y + subsampledHeight - image.getHeight(); if (deltaY > 0) { srcRegion.height -= deltaY*periodY; } } if (srcRegion.isEmpty() || destRegion.isEmpty()) { throw new IllegalArgumentException("Empty region!"); } } /** * A utility method that may be used by readers to test the * validity of the source and destination band settings of an * {@code ImageReadParam}. This method may be called as soon * as the reader knows both the number of bands of the source * image as it exists in the input stream, and the number of bands * of the destination image that being written. * * <p> The method retrieves the source and destination band * setting arrays from param using the {@code getSourceBands} * and {@code getDestinationBands} methods (or considers them * to be {@code null} if {@code param} is * {@code null}). If the source band setting array is * {@code null}, it is considered to be equal to the array * {@code { 0, 1, ..., numSrcBands - 1 }}, and similarly for * the destination band setting array. * * <p> The method then tests that both arrays are equal in length, * and that neither array contains a value larger than the largest * available band index. * * <p> Any failure results in an * {@code IllegalArgumentException} being thrown; success * results in the method returning silently. * * @param param the {@code ImageReadParam} being used to read * the image. * @param numSrcBands the number of bands of the image as it exists * int the input source. * @param numDstBands the number of bands in the destination image * being written. * * @exception IllegalArgumentException if {@code param} * contains an invalid specification of a source and/or * destination band subset. */ protected static void checkReadParamBandSettings(ImageReadParam param, int numSrcBands, int numDstBands) { // A null param is equivalent to srcBands == dstBands == null. int[] srcBands = null; int[] dstBands = null; if (param != null) { srcBands = param.getSourceBands(); dstBands = param.getDestinationBands(); } int paramSrcBandLength = (srcBands == null) ? numSrcBands : srcBands.length; int paramDstBandLength = (dstBands == null) ? numDstBands : dstBands.length; if (paramSrcBandLength != paramDstBandLength) { throw new IllegalArgumentException("ImageReadParam num source & dest bands differ!"); } if (srcBands != null) { for (int i = 0; i < srcBands.length; i++) { if (srcBands[i] >= numSrcBands) { throw new IllegalArgumentException("ImageReadParam source bands contains a value >= the number of source bands!"); } } } if (dstBands != null) { for (int i = 0; i < dstBands.length; i++) { if (dstBands[i] >= numDstBands) { throw new IllegalArgumentException("ImageReadParam dest bands contains a value >= the number of dest bands!"); } } } } /** * Returns the {@code BufferedImage} to which decoded pixel * data should be written. The image is determined by inspecting * the supplied {@code ImageReadParam} if it is * non-{@code null}; if its {@code getDestination} * method returns a non-{@code null} value, that image is * simply returned. Otherwise, * {@code param.getDestinationType} method is called to * determine if a particular image type has been specified. If * so, the returned {@code ImageTypeSpecifier} is used after * checking that it is equal to one of those included in * {@code imageTypes}. * * <p> If {@code param} is {@code null} or the above * steps have not yielded an image or an * {@code ImageTypeSpecifier}, the first value obtained from * the {@code imageTypes} parameter is used. Typically, the * caller will set {@code imageTypes} to the value of * {@code getImageTypes(imageIndex)}. * * <p> Next, the dimensions of the image are determined by a call * to {@code computeRegions}. The actual width and height of * the image being decoded are passed in as the {@code width} * and {@code height} parameters. * * @param param an {@code ImageReadParam} to be used to get * the destination image or image type, or {@code null}. * @param imageTypes an {@code Iterator} of * {@code ImageTypeSpecifier}s indicating the legal image * types, with the default first. * @param width the true width of the image or tile being decoded. * @param height the true width of the image or tile being decoded. * * @return the {@code BufferedImage} to which decoded pixel * data should be written. * * @exception IIOException if the {@code ImageTypeSpecifier} * specified by {@code param} does not match any of the legal * ones from {@code imageTypes}. * @exception IllegalArgumentException if {@code imageTypes} * is {@code null} or empty, or if an object not of type * {@code ImageTypeSpecifier} is retrieved from it. * @exception IllegalArgumentException if the resulting image would * have a width or height less than 1. * @exception IllegalArgumentException if the product of * {@code width} and {@code height} is greater than * {@code Integer.MAX_VALUE}. */ protected static BufferedImage getDestination(ImageReadParam param, Iterator<ImageTypeSpecifier> imageTypes, int width, int height) throws IIOException { if (imageTypes == null || !imageTypes.hasNext()) { throw new IllegalArgumentException("imageTypes null or empty!"); } if ((long)width*height > Integer.MAX_VALUE) { throw new IllegalArgumentException ("width*height > Integer.MAX_VALUE!"); } BufferedImage dest = null; ImageTypeSpecifier imageType = null; // If param is non-null, use it if (param != null) { // Try to get the image itself dest = param.getDestination(); if (dest != null) { return dest; } // No image, get the image type imageType = param.getDestinationType(); } // No info from param, use fallback image type if (imageType == null) { Object o = imageTypes.next(); if (!(o instanceof ImageTypeSpecifier)) { throw new IllegalArgumentException ("Non-ImageTypeSpecifier retrieved from imageTypes!"); } imageType = (ImageTypeSpecifier)o; } else { boolean foundIt = false; while (imageTypes.hasNext()) { ImageTypeSpecifier type = imageTypes.next(); if (type.equals(imageType)) { foundIt = true; break; } } if (!foundIt) { throw new IIOException ("Destination type from ImageReadParam does not match!"); } } Rectangle srcRegion = new Rectangle(0,0,0,0); Rectangle destRegion = new Rectangle(0,0,0,0); computeRegions(param, width, height, null, srcRegion, destRegion); int destWidth = destRegion.x + destRegion.width; int destHeight = destRegion.y + destRegion.height; // Create a new image based on the type specifier return imageType.createBufferedImage(destWidth, destHeight); } }
gpl-2.0
FauxFaux/jdk9-jdk
src/jdk.jdi/share/classes/com/sun/jdi/ShortType.java
1523
/* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.jdi; /** * The type of all primitive <code>short</code> values * accessed in the target VM. Calls to {@link Value#type} will return an * implementor of this interface. * * @see LongValue * * @author James McIlree * @since 1.3 */ public interface ShortType extends PrimitiveType { }
gpl-2.0
TalShafir/ansible
lib/ansible/modules/cloud/azure/azure_rm_sqlfirewallrule_facts.py
6043
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_sqlfirewallrule_facts version_added: "2.8" short_description: Get Azure SQL Firewall Rule facts. description: - Get facts of SQL Firewall Rule. options: resource_group: description: - The name of the resource group that contains the server. required: True server_name: description: - The name of the server. required: True name: description: - The name of the firewall rule. extends_documentation_fragment: - azure author: - "Zim Kalinowski (@zikalino)" ''' EXAMPLES = ''' - name: Get instance of SQL Firewall Rule azure_rm_sqlfirewallrule_facts: resource_group: testgroup server_name: testserver name: testrule - name: List instances of SQL Firewall Rule azure_rm_sqlfirewallrule_facts: resource_group: testgroup server_name: testserver ''' RETURN = ''' rules: description: A list of dict results containing the facts for matching SQL firewall rules. returned: always type: complex contains: id: description: - Resource ID returned: always type: str sample: "/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testgroup/providers/Microsoft.Sql/servers/testser ver/firewallRules/testrule" resource_group: description: - Resource group name. returned: always type: str sample: testgroup server_name: description: - SQL server name. returned: always type: str sample: testserver name: description: - Firewall rule name. returned: always type: str sample: testrule start_ip_address: description: - The start IP address of the firewall rule. returned: always type: str sample: 10.0.0.1 end_ip_address: description: - The start IP address of the firewall rule. returned: always type: str sample: 10.0.0.5 ''' from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller from azure.mgmt.sql import SqlManagementClient from msrest.serialization import Model except ImportError: # This is handled in azure_rm_common pass class AzureRMFirewallRulesFacts(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( resource_group=dict( type='str', required=True ), server_name=dict( type='str', required=True ), name=dict( type='str' ) ) # store the results of the module operation self.results = dict( changed=False ) self.resource_group = None self.server_name = None self.name = None super(AzureRMFirewallRulesFacts, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): for key in self.module_arg_spec: setattr(self, key, kwargs[key]) if (self.name is not None): self.results['rules'] = self.get() else: self.results['rules'] = self.list_by_server() return self.results def get(self): ''' Gets facts of the specified SQL Firewall Rule. :return: deserialized SQL Firewall Ruleinstance state dictionary ''' response = None results = [] try: response = self.sql_client.firewall_rules.get(resource_group_name=self.resource_group, server_name=self.server_name, firewall_rule_name=self.name) self.log("Response : {0}".format(response)) except CloudError as e: self.log('Could not get facts for FirewallRules.') if response is not None: results.append(self.format_item(response)) return results def list_by_server(self): ''' Gets facts of the specified SQL Firewall Rule. :return: deserialized SQL Firewall Ruleinstance state dictionary ''' response = None results = [] try: response = self.sql_client.firewall_rules.list_by_server(resource_group_name=self.resource_group, server_name=self.server_name) self.log("Response : {0}".format(response)) except CloudError as e: self.log('Could not get facts for FirewallRules.') if response is not None: for item in response: results.append(self.format_item(item)) return results def format_item(self, item): d = item.as_dict() d = { 'id': d['id'], 'resource_group': self.resource_group, 'server_name': self.server_name, 'name': d['name'], 'start_ip_address': d['start_ip_address'], 'end_ip_address': d['end_ip_address'] } return d def main(): AzureRMFirewallRulesFacts() if __name__ == '__main__': main()
gpl-3.0
writeameer/moodle
lib/yui/3.5.1/build/datatype-date-format/lang/datatype-date-format_ko-KR.js
712
/* YUI 3.5.1 (build 22) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("lang/datatype-date-format_ko-KR",function(a){a.Intl.add("datatype-date-format","ko-KR",{"a":["일","월","화","수","목","금","토"],"A":["일요일","월요일","화요일","수요일","목요일","금요일","토요일"],"b":["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],"B":["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],"c":"%Y년 %b %d일 %a%p %I시 %M분 %S초 %Z","p":["오전","오후"],"P":["오전","오후"],"x":"%y. %m. %d.","X":"%p %I시 %M분 %S초"});},"3.5.1");
gpl-3.0
nerith/servo
ports/cef/wrappers.rs
12006
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use interfaces::{cef_app_t, CefApp, cef_drag_data_t, cef_post_data_element_t, cef_v8value_t, CefPostDataElement}; use interfaces::{CefV8Value}; use interfaces::{cef_download_handler_t, cef_drag_handler_t, cef_context_menu_handler_t}; use interfaces::{cef_dialog_handler_t, cef_focus_handler_t}; use interfaces::{cef_load_handler_t, cef_request_handler_t}; use interfaces::{cef_geolocation_handler_t, cef_jsdialog_handler_t, cef_keyboard_handler_t}; use rustc_unicode::str::Utf16Encoder; use types::{cef_base_t, cef_browser_settings_t, CefBrowserSettings, cef_color_model_t}; use types::{cef_context_menu_edit_state_flags_t}; use types::{cef_context_menu_media_state_flags_t}; use types::{cef_context_menu_media_type_t, cef_context_menu_type_flags_t, cef_cookie_t, cef_cursor_info_t, CefCursorInfo, cef_cursor_type_t}; use types::{cef_dom_document_type_t, cef_dom_node_type_t}; use types::{cef_drag_operations_mask_t, cef_duplex_mode_t}; use types::{cef_errorcode_t, cef_event_flags_t, cef_event_handle_t}; use types::{cef_file_dialog_mode_t, cef_focus_source_t}; use types::{cef_geoposition_t}; use types::{cef_jsdialog_type_t}; use types::{cef_key_event}; use types::{cef_menu_item_type_t, cef_mouse_button_type_t}; use types::{cef_mouse_event, cef_navigation_type_t}; use types::{cef_page_range_t, cef_paint_element_type_t, cef_point_t, cef_postdataelement_type_t}; use types::{cef_popup_features_t, cef_process_id_t}; use types::{cef_rect_t, cef_request_context_settings_t, CefRequestContextSettings}; use types::{cef_resource_type_t, cef_return_value_t}; use types::{cef_screen_info_t, CefScreenInfo, cef_size_t, cef_string_t, cef_string_userfree_t}; use types::{cef_string_list_t, cef_string_map_t, cef_string_multimap_t, cef_string_utf16}; use types::{cef_termination_status_t, cef_text_input_context_t, cef_thread_id_t}; use types::{cef_time_t, cef_transition_type_t, cef_urlrequest_status_t}; use types::{cef_v8_accesscontrol_t, cef_v8_propertyattribute_t, cef_value_type_t}; use types::{cef_window_info_t, cef_window_open_disposition_t, cef_xml_encoding_type_t, cef_xml_node_type_t}; use libc::{self, c_char, c_int, c_ushort, c_void}; use std::collections::HashMap; use std::mem; use std::ptr; use std::slice; pub trait CefWrap<CObject> { fn to_c(rust_object: Self) -> CObject; unsafe fn to_rust(c_object: CObject) -> Self; } macro_rules! cef_noop_wrapper( ($ty:ty) => ( impl CefWrap<$ty> for $ty { fn to_c(rust_object: $ty) -> $ty { rust_object } unsafe fn to_rust(c_object: $ty) -> $ty { c_object } } ) ); macro_rules! cef_pointer_wrapper( ($ty:ty) => ( impl<'a> CefWrap<*const $ty> for &'a $ty { fn to_c(rust_object: &'a $ty) -> *const $ty { rust_object } unsafe fn to_rust(c_object: *const $ty) -> &'a $ty { &*c_object } } impl<'a> CefWrap<*mut $ty> for &'a mut $ty { fn to_c(rust_object: &'a mut $ty) -> *mut $ty { rust_object } unsafe fn to_rust(c_object: *mut $ty) -> &'a mut $ty { &mut *c_object } } cef_noop_wrapper!(*const $ty); cef_noop_wrapper!(*mut $ty); ) ); macro_rules! cef_unimplemented_wrapper( ($c_type:ty, $rust_type:ty) => ( impl CefWrap<$c_type> for $rust_type { fn to_c(_: $rust_type) -> $c_type { panic!("unimplemented CEF type conversion: {}", stringify!($c_type)) } unsafe fn to_rust(_: $c_type) -> $rust_type { panic!("unimplemented CEF type conversion: {}", stringify!($c_type)) } } ) ); cef_pointer_wrapper!(()); cef_pointer_wrapper!(*mut ()); cef_pointer_wrapper!(*mut c_void); cef_pointer_wrapper!(c_void); cef_pointer_wrapper!(cef_app_t); cef_pointer_wrapper!(cef_base_t); cef_pointer_wrapper!(cef_browser_settings_t); cef_pointer_wrapper!(cef_cookie_t); cef_pointer_wrapper!(cef_cursor_info_t); cef_pointer_wrapper!(cef_geoposition_t); cef_pointer_wrapper!(cef_key_event); cef_pointer_wrapper!(cef_mouse_event); cef_pointer_wrapper!(cef_page_range_t); cef_pointer_wrapper!(cef_point_t); cef_pointer_wrapper!(cef_popup_features_t); cef_pointer_wrapper!(cef_rect_t); cef_pointer_wrapper!(cef_request_context_settings_t); cef_pointer_wrapper!(cef_screen_info_t); cef_pointer_wrapper!(cef_size_t); cef_pointer_wrapper!(cef_time_t); cef_pointer_wrapper!(cef_window_info_t); cef_pointer_wrapper!(i32); cef_pointer_wrapper!(i64); cef_pointer_wrapper!(u32); cef_pointer_wrapper!(u64); cef_noop_wrapper!(()); cef_noop_wrapper!(*const cef_geolocation_handler_t); cef_noop_wrapper!(*const cef_string_utf16); cef_noop_wrapper!(*mut cef_context_menu_handler_t); cef_noop_wrapper!(*mut cef_dialog_handler_t); cef_noop_wrapper!(*mut cef_download_handler_t); cef_noop_wrapper!(*mut cef_drag_data_t); cef_noop_wrapper!(*mut cef_drag_handler_t); cef_noop_wrapper!(*mut cef_event_handle_t); cef_noop_wrapper!(*mut cef_focus_handler_t); cef_noop_wrapper!(*mut cef_geolocation_handler_t); cef_noop_wrapper!(*mut cef_jsdialog_handler_t); cef_noop_wrapper!(*mut cef_keyboard_handler_t); cef_noop_wrapper!(*mut cef_load_handler_t); cef_noop_wrapper!(*mut cef_request_handler_t); cef_noop_wrapper!(*mut cef_string_utf16); cef_noop_wrapper!(c_int); cef_noop_wrapper!(CefApp); cef_noop_wrapper!(CefBrowserSettings); cef_noop_wrapper!(CefScreenInfo); cef_noop_wrapper!(CefRequestContextSettings); cef_noop_wrapper!(CefCursorInfo); cef_noop_wrapper!(cef_color_model_t); cef_noop_wrapper!(cef_context_menu_edit_state_flags_t); cef_noop_wrapper!(cef_context_menu_media_state_flags_t); cef_noop_wrapper!(cef_context_menu_media_type_t); cef_noop_wrapper!(cef_context_menu_type_flags_t); cef_noop_wrapper!(cef_cursor_type_t); cef_noop_wrapper!(cef_dom_document_type_t); cef_noop_wrapper!(cef_dom_node_type_t); cef_noop_wrapper!(cef_drag_operations_mask_t); cef_noop_wrapper!(cef_duplex_mode_t); cef_noop_wrapper!(cef_errorcode_t); cef_noop_wrapper!(cef_event_flags_t); cef_noop_wrapper!(cef_event_handle_t); cef_noop_wrapper!(cef_file_dialog_mode_t); cef_noop_wrapper!(cef_focus_source_t); cef_noop_wrapper!(cef_jsdialog_handler_t); cef_noop_wrapper!(cef_jsdialog_type_t); cef_noop_wrapper!(cef_key_event); cef_noop_wrapper!(cef_menu_item_type_t); cef_noop_wrapper!(cef_mouse_button_type_t); cef_noop_wrapper!(cef_navigation_type_t); cef_noop_wrapper!(cef_paint_element_type_t); cef_noop_wrapper!(cef_postdataelement_type_t); cef_noop_wrapper!(cef_process_id_t); cef_noop_wrapper!(cef_resource_type_t); cef_noop_wrapper!(cef_return_value_t); cef_noop_wrapper!(cef_termination_status_t); cef_noop_wrapper!(cef_text_input_context_t); cef_noop_wrapper!(cef_thread_id_t); cef_noop_wrapper!(cef_time_t); cef_noop_wrapper!(cef_transition_type_t); cef_noop_wrapper!(cef_urlrequest_status_t); cef_noop_wrapper!(cef_v8_accesscontrol_t); cef_noop_wrapper!(cef_v8_propertyattribute_t); cef_noop_wrapper!(cef_value_type_t); cef_noop_wrapper!(cef_window_open_disposition_t); cef_noop_wrapper!(cef_xml_encoding_type_t); cef_noop_wrapper!(cef_xml_node_type_t); cef_noop_wrapper!(f64); cef_noop_wrapper!(i64); cef_noop_wrapper!(u32); cef_noop_wrapper!(u64); cef_noop_wrapper!(cef_string_list_t); cef_unimplemented_wrapper!(*const *mut cef_v8value_t, *const CefV8Value); cef_unimplemented_wrapper!(*mut *mut cef_post_data_element_t, *mut CefPostDataElement); cef_unimplemented_wrapper!(cef_string_map_t, HashMap<String,String>); cef_unimplemented_wrapper!(cef_string_multimap_t, HashMap<String,Vec<String>>); cef_unimplemented_wrapper!(cef_string_t, String); impl<'a> CefWrap<*const cef_string_t> for &'a [u16] { fn to_c(buffer: &'a [u16]) -> *const cef_string_t { unsafe { let ptr = libc::malloc(((buffer.len() + 1) * 2) as u64) as *mut c_ushort; ptr::copy(buffer.as_ptr(), ptr, buffer.len()); *ptr.offset(buffer.len() as isize) = 0; // FIXME(pcwalton): This leaks!! We should instead have the caller pass some scratch // stack space to create the object in. What a botch. Box::into_raw(box cef_string_utf16 { str: ptr, length: buffer.len() as u64, dtor: Some(free_boxed_utf16_string as extern "C" fn(*mut c_ushort)), }) as *const _ } } unsafe fn to_rust(cef_string: *const cef_string_t) -> &'a [u16] { slice::from_raw_parts((*cef_string).str, (*cef_string).length as usize) } } extern "C" fn free_boxed_utf16_string(string: *mut c_ushort) { unsafe { libc::free(string as *mut c_void) } } impl<'a> CefWrap<*mut cef_string_t> for &'a mut [u16] { fn to_c(_: &'a mut [u16]) -> *mut cef_string_t { panic!("unimplemented CEF type conversion: &'a str") } unsafe fn to_rust(_: *mut cef_string_t) -> &'a mut [u16] { panic!("unimplemented CEF type conversion: *mut cef_string_t") } } // FIXME(pcwalton): This is pretty bogus, but it's only used for `init_from_argv`, which should // never be called by Rust programs anyway. We should fix the wrapper generation though. impl<'a,'b> CefWrap<*const *const c_char> for &'a &'b str { fn to_c(_: &'a &'b str) -> *const *const c_char { panic!("unimplemented CEF type conversion: &'a &'b str") } unsafe fn to_rust(_: *const *const c_char) -> &'a &'b str { panic!("unimplemented CEF type conversion: *const *const cef_string_t") } } impl<'a,'b> CefWrap<*mut *const c_char> for &'a mut &'b str { fn to_c(_: &'a mut &'b str) -> *mut *const c_char { panic!("unimplemented CEF type conversion: &'a mut &'b str") } unsafe fn to_rust(_: *mut *const c_char) -> &'a mut &'b str { panic!("unimplemented CEF type conversion: *mut *const c_char") } } impl<'a> CefWrap<cef_string_userfree_t> for String { fn to_c(string: String) -> cef_string_userfree_t { let utf16_chars: Vec<u16> = Utf16Encoder::new(string.chars()).collect(); let boxed_string; unsafe { let buffer = libc::malloc((mem::size_of::<c_ushort>() as libc::size_t) * ((utf16_chars.len() + 1) as libc::size_t)) as *mut u16; for (i, ch) in utf16_chars.iter().enumerate() { *buffer.offset(i as isize) = *ch } *buffer.offset(utf16_chars.len() as isize) = 0; boxed_string = libc::malloc(mem::size_of::<cef_string_utf16>() as libc::size_t) as *mut cef_string_utf16; ptr::write(&mut (*boxed_string).str, buffer); ptr::write(&mut (*boxed_string).length, utf16_chars.len() as u64); ptr::write(&mut (*boxed_string).dtor, Some(free_utf16_buffer as extern "C" fn(*mut c_ushort))); } boxed_string } unsafe fn to_rust(_: cef_string_userfree_t) -> String { panic!("unimplemented CEF type conversion: cef_string_userfree_t") } } extern "C" fn free_utf16_buffer(buffer: *mut c_ushort) { unsafe { libc::free(buffer as *mut c_void) } } impl<'a> CefWrap<cef_string_t> for &'a mut String { fn to_c(_: &'a mut String) -> cef_string_t { panic!("unimplemented CEF type conversion: &'a mut String"); } unsafe fn to_rust(_: cef_string_t) -> &'a mut String { panic!("unimplemented CEF type conversion: cef_string_t"); } } impl<'a> CefWrap<&'a cef_string_list_t> for &'a cef_string_list_t { fn to_c(stringlist: &'a cef_string_list_t) -> &'a cef_string_list_t { stringlist } unsafe fn to_rust(_: &'a cef_string_list_t) -> &'a cef_string_list_t { panic!("unimplemented CEF type conversion: cef_string_t"); } }
mpl-2.0
bac/juju
environs/tools/storage.go
2683
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package tools import ( "errors" "fmt" "path/filepath" "strings" "github.com/juju/utils/arch" "github.com/juju/version" "github.com/juju/juju/environs/storage" coretools "github.com/juju/juju/tools" ) var ErrNoTools = errors.New("no tools available") const ( toolPrefix = "tools/%s/juju-" toolSuffix = ".tgz" ) // StorageName returns the name that is used to store and retrieve the // given version of the juju tools. func StorageName(vers version.Binary, stream string) string { return storagePrefix(stream) + vers.String() + toolSuffix } func storagePrefix(stream string) string { return fmt.Sprintf(toolPrefix, stream) } // ReadList returns a List of the tools in store with the given major.minor version. // If minorVersion = -1, then only majorVersion is considered. // If majorVersion is -1, then all tools tarballs are used. // If store contains no such tools, it returns ErrNoMatches. func ReadList(stor storage.StorageReader, toolsDir string, majorVersion, minorVersion int) (coretools.List, error) { if minorVersion >= 0 { logger.Debugf("reading v%d.%d tools", majorVersion, minorVersion) } else { logger.Debugf("reading v%d.* tools", majorVersion) } storagePrefix := storagePrefix(toolsDir) names, err := storage.List(stor, storagePrefix) if err != nil { return nil, err } var list coretools.List var foundAnyTools bool for _, name := range names { name = filepath.ToSlash(name) if !strings.HasPrefix(name, storagePrefix) || !strings.HasSuffix(name, toolSuffix) { continue } var t coretools.Tools vers := name[len(storagePrefix) : len(name)-len(toolSuffix)] if t.Version, err = version.ParseBinary(vers); err != nil { logger.Debugf("failed to parse version %q: %v", vers, err) continue } foundAnyTools = true // If specified major version value supplied, major version must match. if majorVersion >= 0 && t.Version.Major != majorVersion { continue } // If specified minor version value supplied, minor version must match. if minorVersion >= 0 && t.Version.Minor != minorVersion { continue } logger.Debugf("found %s", vers) if t.URL, err = stor.URL(name); err != nil { return nil, err } list = append(list, &t) // Older versions of Juju only know about ppc64, so add metadata for that arch. if t.Version.Arch == arch.PPC64EL { legacyPPC64Tools := t legacyPPC64Tools.Version.Arch = arch.LEGACY_PPC64 list = append(list, &legacyPPC64Tools) } } if len(list) == 0 { if foundAnyTools { return nil, coretools.ErrNoMatches } return nil, ErrNoTools } return list, nil }
agpl-3.0
abhinavmoudgil95/root
interpreter/llvm/src/lib/Target/Sparc/AsmParser/SparcAsmParser.cpp
40075
//===-- SparcAsmParser.cpp - Parse Sparc assembly to MCInst instructions --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCTargetDesc/SparcMCExpr.h" #include "MCTargetDesc/SparcMCTargetDesc.h" #include "llvm/ADT/STLExtras.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/MCParsedAsmOperand.h" #include "llvm/MC/MCParser/MCTargetAsmParser.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; // The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target // namespace. But SPARC backend uses "SP" as its namespace. namespace llvm { namespace Sparc { using namespace SP; } } namespace { class SparcOperand; class SparcAsmParser : public MCTargetAsmParser { MCAsmParser &Parser; /// @name Auto-generated Match Functions /// { #define GET_ASSEMBLER_HEADER #include "SparcGenAsmMatcher.inc" /// } // public interface of the MCTargetAsmParser. bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm) override; bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override; bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands) override; bool ParseDirective(AsmToken DirectiveID) override; unsigned validateTargetOperandClass(MCParsedAsmOperand &Op, unsigned Kind) override; // Custom parse functions for Sparc specific operands. OperandMatchResultTy parseMEMOperand(OperandVector &Operands); OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Name); OperandMatchResultTy parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Operand, bool isCall = false); OperandMatchResultTy parseBranchModifiers(OperandVector &Operands); // Helper function for dealing with %lo / %hi in PIC mode. const SparcMCExpr *adjustPICRelocation(SparcMCExpr::VariantKind VK, const MCExpr *subExpr); // returns true if Tok is matched to a register and returns register in RegNo. bool matchRegisterName(const AsmToken &Tok, unsigned &RegNo, unsigned &RegKind); bool matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc); bool parseDirectiveWord(unsigned Size, SMLoc L); bool is64Bit() const { return getSTI().getTargetTriple().getArch() == Triple::sparcv9; } void expandSET(MCInst &Inst, SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions); public: SparcAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser, const MCInstrInfo &MII, const MCTargetOptions &Options) : MCTargetAsmParser(Options, sti), Parser(parser) { // Initialize the set of available features. setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits())); } }; static const MCPhysReg IntRegs[32] = { Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3, Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7, Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3, Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7, Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3, Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7, Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3, Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 }; static const MCPhysReg FloatRegs[32] = { Sparc::F0, Sparc::F1, Sparc::F2, Sparc::F3, Sparc::F4, Sparc::F5, Sparc::F6, Sparc::F7, Sparc::F8, Sparc::F9, Sparc::F10, Sparc::F11, Sparc::F12, Sparc::F13, Sparc::F14, Sparc::F15, Sparc::F16, Sparc::F17, Sparc::F18, Sparc::F19, Sparc::F20, Sparc::F21, Sparc::F22, Sparc::F23, Sparc::F24, Sparc::F25, Sparc::F26, Sparc::F27, Sparc::F28, Sparc::F29, Sparc::F30, Sparc::F31 }; static const MCPhysReg DoubleRegs[32] = { Sparc::D0, Sparc::D1, Sparc::D2, Sparc::D3, Sparc::D4, Sparc::D5, Sparc::D6, Sparc::D7, Sparc::D8, Sparc::D7, Sparc::D8, Sparc::D9, Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15, Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19, Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23, Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27, Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 }; static const MCPhysReg QuadFPRegs[32] = { Sparc::Q0, Sparc::Q1, Sparc::Q2, Sparc::Q3, Sparc::Q4, Sparc::Q5, Sparc::Q6, Sparc::Q7, Sparc::Q8, Sparc::Q9, Sparc::Q10, Sparc::Q11, Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 }; static const MCPhysReg ASRRegs[32] = { SP::Y, SP::ASR1, SP::ASR2, SP::ASR3, SP::ASR4, SP::ASR5, SP::ASR6, SP::ASR7, SP::ASR8, SP::ASR9, SP::ASR10, SP::ASR11, SP::ASR12, SP::ASR13, SP::ASR14, SP::ASR15, SP::ASR16, SP::ASR17, SP::ASR18, SP::ASR19, SP::ASR20, SP::ASR21, SP::ASR22, SP::ASR23, SP::ASR24, SP::ASR25, SP::ASR26, SP::ASR27, SP::ASR28, SP::ASR29, SP::ASR30, SP::ASR31}; static const MCPhysReg IntPairRegs[] = { Sparc::G0_G1, Sparc::G2_G3, Sparc::G4_G5, Sparc::G6_G7, Sparc::O0_O1, Sparc::O2_O3, Sparc::O4_O5, Sparc::O6_O7, Sparc::L0_L1, Sparc::L2_L3, Sparc::L4_L5, Sparc::L6_L7, Sparc::I0_I1, Sparc::I2_I3, Sparc::I4_I5, Sparc::I6_I7}; static const MCPhysReg CoprocRegs[32] = { Sparc::C0, Sparc::C1, Sparc::C2, Sparc::C3, Sparc::C4, Sparc::C5, Sparc::C6, Sparc::C7, Sparc::C8, Sparc::C9, Sparc::C10, Sparc::C11, Sparc::C12, Sparc::C13, Sparc::C14, Sparc::C15, Sparc::C16, Sparc::C17, Sparc::C18, Sparc::C19, Sparc::C20, Sparc::C21, Sparc::C22, Sparc::C23, Sparc::C24, Sparc::C25, Sparc::C26, Sparc::C27, Sparc::C28, Sparc::C29, Sparc::C30, Sparc::C31 }; static const MCPhysReg CoprocPairRegs[] = { Sparc::C0_C1, Sparc::C2_C3, Sparc::C4_C5, Sparc::C6_C7, Sparc::C8_C9, Sparc::C10_C11, Sparc::C12_C13, Sparc::C14_C15, Sparc::C16_C17, Sparc::C18_C19, Sparc::C20_C21, Sparc::C22_C23, Sparc::C24_C25, Sparc::C26_C27, Sparc::C28_C29, Sparc::C30_C31}; /// SparcOperand - Instances of this class represent a parsed Sparc machine /// instruction. class SparcOperand : public MCParsedAsmOperand { public: enum RegisterKind { rk_None, rk_IntReg, rk_IntPairReg, rk_FloatReg, rk_DoubleReg, rk_QuadReg, rk_CoprocReg, rk_CoprocPairReg, rk_Special, }; private: enum KindTy { k_Token, k_Register, k_Immediate, k_MemoryReg, k_MemoryImm } Kind; SMLoc StartLoc, EndLoc; struct Token { const char *Data; unsigned Length; }; struct RegOp { unsigned RegNum; RegisterKind Kind; }; struct ImmOp { const MCExpr *Val; }; struct MemOp { unsigned Base; unsigned OffsetReg; const MCExpr *Off; }; union { struct Token Tok; struct RegOp Reg; struct ImmOp Imm; struct MemOp Mem; }; public: SparcOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {} bool isToken() const override { return Kind == k_Token; } bool isReg() const override { return Kind == k_Register; } bool isImm() const override { return Kind == k_Immediate; } bool isMem() const override { return isMEMrr() || isMEMri(); } bool isMEMrr() const { return Kind == k_MemoryReg; } bool isMEMri() const { return Kind == k_MemoryImm; } bool isIntReg() const { return (Kind == k_Register && Reg.Kind == rk_IntReg); } bool isFloatReg() const { return (Kind == k_Register && Reg.Kind == rk_FloatReg); } bool isFloatOrDoubleReg() const { return (Kind == k_Register && (Reg.Kind == rk_FloatReg || Reg.Kind == rk_DoubleReg)); } bool isCoprocReg() const { return (Kind == k_Register && Reg.Kind == rk_CoprocReg); } StringRef getToken() const { assert(Kind == k_Token && "Invalid access!"); return StringRef(Tok.Data, Tok.Length); } unsigned getReg() const override { assert((Kind == k_Register) && "Invalid access!"); return Reg.RegNum; } const MCExpr *getImm() const { assert((Kind == k_Immediate) && "Invalid access!"); return Imm.Val; } unsigned getMemBase() const { assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!"); return Mem.Base; } unsigned getMemOffsetReg() const { assert((Kind == k_MemoryReg) && "Invalid access!"); return Mem.OffsetReg; } const MCExpr *getMemOff() const { assert((Kind == k_MemoryImm) && "Invalid access!"); return Mem.Off; } /// getStartLoc - Get the location of the first token of this operand. SMLoc getStartLoc() const override { return StartLoc; } /// getEndLoc - Get the location of the last token of this operand. SMLoc getEndLoc() const override { return EndLoc; } void print(raw_ostream &OS) const override { switch (Kind) { case k_Token: OS << "Token: " << getToken() << "\n"; break; case k_Register: OS << "Reg: #" << getReg() << "\n"; break; case k_Immediate: OS << "Imm: " << getImm() << "\n"; break; case k_MemoryReg: OS << "Mem: " << getMemBase() << "+" << getMemOffsetReg() << "\n"; break; case k_MemoryImm: assert(getMemOff() != nullptr); OS << "Mem: " << getMemBase() << "+" << *getMemOff() << "\n"; break; } } void addRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getReg())); } void addImmOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); const MCExpr *Expr = getImm(); addExpr(Inst, Expr); } void addExpr(MCInst &Inst, const MCExpr *Expr) const{ // Add as immediate when possible. Null MCExpr = 0. if (!Expr) Inst.addOperand(MCOperand::createImm(0)); else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) Inst.addOperand(MCOperand::createImm(CE->getValue())); else Inst.addOperand(MCOperand::createExpr(Expr)); } void addMEMrrOperands(MCInst &Inst, unsigned N) const { assert(N == 2 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getMemBase())); assert(getMemOffsetReg() != 0 && "Invalid offset"); Inst.addOperand(MCOperand::createReg(getMemOffsetReg())); } void addMEMriOperands(MCInst &Inst, unsigned N) const { assert(N == 2 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getMemBase())); const MCExpr *Expr = getMemOff(); addExpr(Inst, Expr); } static std::unique_ptr<SparcOperand> CreateToken(StringRef Str, SMLoc S) { auto Op = make_unique<SparcOperand>(k_Token); Op->Tok.Data = Str.data(); Op->Tok.Length = Str.size(); Op->StartLoc = S; Op->EndLoc = S; return Op; } static std::unique_ptr<SparcOperand> CreateReg(unsigned RegNum, unsigned Kind, SMLoc S, SMLoc E) { auto Op = make_unique<SparcOperand>(k_Register); Op->Reg.RegNum = RegNum; Op->Reg.Kind = (SparcOperand::RegisterKind)Kind; Op->StartLoc = S; Op->EndLoc = E; return Op; } static std::unique_ptr<SparcOperand> CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) { auto Op = make_unique<SparcOperand>(k_Immediate); Op->Imm.Val = Val; Op->StartLoc = S; Op->EndLoc = E; return Op; } static bool MorphToIntPairReg(SparcOperand &Op) { unsigned Reg = Op.getReg(); assert(Op.Reg.Kind == rk_IntReg); unsigned regIdx = 32; if (Reg >= Sparc::G0 && Reg <= Sparc::G7) regIdx = Reg - Sparc::G0; else if (Reg >= Sparc::O0 && Reg <= Sparc::O7) regIdx = Reg - Sparc::O0 + 8; else if (Reg >= Sparc::L0 && Reg <= Sparc::L7) regIdx = Reg - Sparc::L0 + 16; else if (Reg >= Sparc::I0 && Reg <= Sparc::I7) regIdx = Reg - Sparc::I0 + 24; if (regIdx % 2 || regIdx > 31) return false; Op.Reg.RegNum = IntPairRegs[regIdx / 2]; Op.Reg.Kind = rk_IntPairReg; return true; } static bool MorphToDoubleReg(SparcOperand &Op) { unsigned Reg = Op.getReg(); assert(Op.Reg.Kind == rk_FloatReg); unsigned regIdx = Reg - Sparc::F0; if (regIdx % 2 || regIdx > 31) return false; Op.Reg.RegNum = DoubleRegs[regIdx / 2]; Op.Reg.Kind = rk_DoubleReg; return true; } static bool MorphToQuadReg(SparcOperand &Op) { unsigned Reg = Op.getReg(); unsigned regIdx = 0; switch (Op.Reg.Kind) { default: llvm_unreachable("Unexpected register kind!"); case rk_FloatReg: regIdx = Reg - Sparc::F0; if (regIdx % 4 || regIdx > 31) return false; Reg = QuadFPRegs[regIdx / 4]; break; case rk_DoubleReg: regIdx = Reg - Sparc::D0; if (regIdx % 2 || regIdx > 31) return false; Reg = QuadFPRegs[regIdx / 2]; break; } Op.Reg.RegNum = Reg; Op.Reg.Kind = rk_QuadReg; return true; } static bool MorphToCoprocPairReg(SparcOperand &Op) { unsigned Reg = Op.getReg(); assert(Op.Reg.Kind == rk_CoprocReg); unsigned regIdx = 32; if (Reg >= Sparc::C0 && Reg <= Sparc::C31) regIdx = Reg - Sparc::C0; if (regIdx % 2 || regIdx > 31) return false; Op.Reg.RegNum = CoprocPairRegs[regIdx / 2]; Op.Reg.Kind = rk_CoprocPairReg; return true; } static std::unique_ptr<SparcOperand> MorphToMEMrr(unsigned Base, std::unique_ptr<SparcOperand> Op) { unsigned offsetReg = Op->getReg(); Op->Kind = k_MemoryReg; Op->Mem.Base = Base; Op->Mem.OffsetReg = offsetReg; Op->Mem.Off = nullptr; return Op; } static std::unique_ptr<SparcOperand> CreateMEMr(unsigned Base, SMLoc S, SMLoc E) { auto Op = make_unique<SparcOperand>(k_MemoryReg); Op->Mem.Base = Base; Op->Mem.OffsetReg = Sparc::G0; // always 0 Op->Mem.Off = nullptr; Op->StartLoc = S; Op->EndLoc = E; return Op; } static std::unique_ptr<SparcOperand> MorphToMEMri(unsigned Base, std::unique_ptr<SparcOperand> Op) { const MCExpr *Imm = Op->getImm(); Op->Kind = k_MemoryImm; Op->Mem.Base = Base; Op->Mem.OffsetReg = 0; Op->Mem.Off = Imm; return Op; } }; } // end namespace void SparcAsmParser::expandSET(MCInst &Inst, SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) { MCOperand MCRegOp = Inst.getOperand(0); MCOperand MCValOp = Inst.getOperand(1); assert(MCRegOp.isReg()); assert(MCValOp.isImm() || MCValOp.isExpr()); // the imm operand can be either an expression or an immediate. bool IsImm = Inst.getOperand(1).isImm(); int64_t RawImmValue = IsImm ? MCValOp.getImm() : 0; // Allow either a signed or unsigned 32-bit immediate. if (RawImmValue < -2147483648LL || RawImmValue > 4294967295LL) { Error(IDLoc, "set: argument must be between -2147483648 and 4294967295"); return; } // If the value was expressed as a large unsigned number, that's ok. // We want to see if it "looks like" a small signed number. int32_t ImmValue = RawImmValue; // For 'set' you can't use 'or' with a negative operand on V9 because // that would splat the sign bit across the upper half of the destination // register, whereas 'set' is defined to zero the high 32 bits. bool IsEffectivelyImm13 = IsImm && ((is64Bit() ? 0 : -4096) <= ImmValue && ImmValue < 4096); const MCExpr *ValExpr; if (IsImm) ValExpr = MCConstantExpr::create(ImmValue, getContext()); else ValExpr = MCValOp.getExpr(); MCOperand PrevReg = MCOperand::createReg(Sparc::G0); // If not just a signed imm13 value, then either we use a 'sethi' with a // following 'or', or a 'sethi' by itself if there are no more 1 bits. // In either case, start with the 'sethi'. if (!IsEffectivelyImm13) { MCInst TmpInst; const MCExpr *Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_HI, ValExpr); TmpInst.setLoc(IDLoc); TmpInst.setOpcode(SP::SETHIi); TmpInst.addOperand(MCRegOp); TmpInst.addOperand(MCOperand::createExpr(Expr)); Instructions.push_back(TmpInst); PrevReg = MCRegOp; } // The low bits require touching in 3 cases: // * A non-immediate value will always require both instructions. // * An effectively imm13 value needs only an 'or' instruction. // * Otherwise, an immediate that is not effectively imm13 requires the // 'or' only if bits remain after clearing the 22 bits that 'sethi' set. // If the low bits are known zeros, there's nothing to do. // In the second case, and only in that case, must we NOT clear // bits of the immediate value via the %lo() assembler function. // Note also, the 'or' instruction doesn't mind a large value in the case // where the operand to 'set' was 0xFFFFFzzz - it does exactly what you mean. if (!IsImm || IsEffectivelyImm13 || (ImmValue & 0x3ff)) { MCInst TmpInst; const MCExpr *Expr; if (IsEffectivelyImm13) Expr = ValExpr; else Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_LO, ValExpr); TmpInst.setLoc(IDLoc); TmpInst.setOpcode(SP::ORri); TmpInst.addOperand(MCRegOp); TmpInst.addOperand(PrevReg); TmpInst.addOperand(MCOperand::createExpr(Expr)); Instructions.push_back(TmpInst); } } bool SparcAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm) { MCInst Inst; SmallVector<MCInst, 8> Instructions; unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm); switch (MatchResult) { case Match_Success: { switch (Inst.getOpcode()) { default: Inst.setLoc(IDLoc); Instructions.push_back(Inst); break; case SP::SET: expandSET(Inst, IDLoc, Instructions); break; } for (const MCInst &I : Instructions) { Out.EmitInstruction(I, getSTI()); } return false; } case Match_MissingFeature: return Error(IDLoc, "instruction requires a CPU feature not currently enabled"); case Match_InvalidOperand: { SMLoc ErrorLoc = IDLoc; if (ErrorInfo != ~0ULL) { if (ErrorInfo >= Operands.size()) return Error(IDLoc, "too few operands for instruction"); ErrorLoc = ((SparcOperand &)*Operands[ErrorInfo]).getStartLoc(); if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc; } return Error(ErrorLoc, "invalid operand for instruction"); } case Match_MnemonicFail: return Error(IDLoc, "invalid instruction mnemonic"); } llvm_unreachable("Implement any new match types added!"); } bool SparcAsmParser:: ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) { const AsmToken &Tok = Parser.getTok(); StartLoc = Tok.getLoc(); EndLoc = Tok.getEndLoc(); RegNo = 0; if (getLexer().getKind() != AsmToken::Percent) return false; Parser.Lex(); unsigned regKind = SparcOperand::rk_None; if (matchRegisterName(Tok, RegNo, regKind)) { Parser.Lex(); return false; } return Error(StartLoc, "invalid register name"); } static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features, unsigned VariantID); bool SparcAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands) { // First operand in MCInst is instruction mnemonic. Operands.push_back(SparcOperand::CreateToken(Name, NameLoc)); // apply mnemonic aliases, if any, so that we can parse operands correctly. applyMnemonicAliases(Name, getAvailableFeatures(), 0); if (getLexer().isNot(AsmToken::EndOfStatement)) { // Read the first operand. if (getLexer().is(AsmToken::Comma)) { if (parseBranchModifiers(Operands) != MatchOperand_Success) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token"); } } if (parseOperand(Operands, Name) != MatchOperand_Success) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token"); } while (getLexer().is(AsmToken::Comma) || getLexer().is(AsmToken::Plus)) { if (getLexer().is(AsmToken::Plus)) { // Plus tokens are significant in software_traps (p83, sparcv8.pdf). We must capture them. Operands.push_back(SparcOperand::CreateToken("+", Parser.getTok().getLoc())); } Parser.Lex(); // Eat the comma or plus. // Parse and remember the operand. if (parseOperand(Operands, Name) != MatchOperand_Success) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token"); } } } if (getLexer().isNot(AsmToken::EndOfStatement)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token"); } Parser.Lex(); // Consume the EndOfStatement. return false; } bool SparcAsmParser:: ParseDirective(AsmToken DirectiveID) { StringRef IDVal = DirectiveID.getString(); if (IDVal == ".byte") return parseDirectiveWord(1, DirectiveID.getLoc()); if (IDVal == ".half") return parseDirectiveWord(2, DirectiveID.getLoc()); if (IDVal == ".word") return parseDirectiveWord(4, DirectiveID.getLoc()); if (IDVal == ".nword") return parseDirectiveWord(is64Bit() ? 8 : 4, DirectiveID.getLoc()); if (is64Bit() && IDVal == ".xword") return parseDirectiveWord(8, DirectiveID.getLoc()); if (IDVal == ".register") { // For now, ignore .register directive. Parser.eatToEndOfStatement(); return false; } if (IDVal == ".proc") { // For compatibility, ignore this directive. // (It's supposed to be an "optimization" in the Sun assembler) Parser.eatToEndOfStatement(); return false; } // Let the MC layer to handle other directives. return true; } bool SparcAsmParser:: parseDirectiveWord(unsigned Size, SMLoc L) { if (getLexer().isNot(AsmToken::EndOfStatement)) { for (;;) { const MCExpr *Value; if (getParser().parseExpression(Value)) return true; getParser().getStreamer().EmitValue(Value, Size); if (getLexer().is(AsmToken::EndOfStatement)) break; // FIXME: Improve diagnostic. if (getLexer().isNot(AsmToken::Comma)) return Error(L, "unexpected token in directive"); Parser.Lex(); } } Parser.Lex(); return false; } SparcAsmParser::OperandMatchResultTy SparcAsmParser::parseMEMOperand(OperandVector &Operands) { SMLoc S, E; unsigned BaseReg = 0; if (ParseRegister(BaseReg, S, E)) { return MatchOperand_NoMatch; } switch (getLexer().getKind()) { default: return MatchOperand_NoMatch; case AsmToken::Comma: case AsmToken::RBrac: case AsmToken::EndOfStatement: Operands.push_back(SparcOperand::CreateMEMr(BaseReg, S, E)); return MatchOperand_Success; case AsmToken:: Plus: Parser.Lex(); // Eat the '+' break; case AsmToken::Minus: break; } std::unique_ptr<SparcOperand> Offset; OperandMatchResultTy ResTy = parseSparcAsmOperand(Offset); if (ResTy != MatchOperand_Success || !Offset) return MatchOperand_NoMatch; Operands.push_back( Offset->isImm() ? SparcOperand::MorphToMEMri(BaseReg, std::move(Offset)) : SparcOperand::MorphToMEMrr(BaseReg, std::move(Offset))); return MatchOperand_Success; } SparcAsmParser::OperandMatchResultTy SparcAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) { OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic); // If there wasn't a custom match, try the generic matcher below. Otherwise, // there was a match, but an error occurred, in which case, just return that // the operand parsing failed. if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail) return ResTy; if (getLexer().is(AsmToken::LBrac)) { // Memory operand Operands.push_back(SparcOperand::CreateToken("[", Parser.getTok().getLoc())); Parser.Lex(); // Eat the [ if (Mnemonic == "cas" || Mnemonic == "casx" || Mnemonic == "casa") { SMLoc S = Parser.getTok().getLoc(); if (getLexer().getKind() != AsmToken::Percent) return MatchOperand_NoMatch; Parser.Lex(); // eat % unsigned RegNo, RegKind; if (!matchRegisterName(Parser.getTok(), RegNo, RegKind)) return MatchOperand_NoMatch; Parser.Lex(); // Eat the identifier token. SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer()-1); Operands.push_back(SparcOperand::CreateReg(RegNo, RegKind, S, E)); ResTy = MatchOperand_Success; } else { ResTy = parseMEMOperand(Operands); } if (ResTy != MatchOperand_Success) return ResTy; if (!getLexer().is(AsmToken::RBrac)) return MatchOperand_ParseFail; Operands.push_back(SparcOperand::CreateToken("]", Parser.getTok().getLoc())); Parser.Lex(); // Eat the ] // Parse an optional address-space identifier after the address. if (getLexer().is(AsmToken::Integer)) { std::unique_ptr<SparcOperand> Op; ResTy = parseSparcAsmOperand(Op, false); if (ResTy != MatchOperand_Success || !Op) return MatchOperand_ParseFail; Operands.push_back(std::move(Op)); } return MatchOperand_Success; } std::unique_ptr<SparcOperand> Op; ResTy = parseSparcAsmOperand(Op, (Mnemonic == "call")); if (ResTy != MatchOperand_Success || !Op) return MatchOperand_ParseFail; // Push the parsed operand into the list of operands Operands.push_back(std::move(Op)); return MatchOperand_Success; } SparcAsmParser::OperandMatchResultTy SparcAsmParser::parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Op, bool isCall) { SMLoc S = Parser.getTok().getLoc(); SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); const MCExpr *EVal; Op = nullptr; switch (getLexer().getKind()) { default: break; case AsmToken::Percent: Parser.Lex(); // Eat the '%'. unsigned RegNo; unsigned RegKind; if (matchRegisterName(Parser.getTok(), RegNo, RegKind)) { StringRef name = Parser.getTok().getString(); Parser.Lex(); // Eat the identifier token. E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); switch (RegNo) { default: Op = SparcOperand::CreateReg(RegNo, RegKind, S, E); break; case Sparc::PSR: Op = SparcOperand::CreateToken("%psr", S); break; case Sparc::FSR: Op = SparcOperand::CreateToken("%fsr", S); break; case Sparc::FQ: Op = SparcOperand::CreateToken("%fq", S); break; case Sparc::CPSR: Op = SparcOperand::CreateToken("%csr", S); break; case Sparc::CPQ: Op = SparcOperand::CreateToken("%cq", S); break; case Sparc::WIM: Op = SparcOperand::CreateToken("%wim", S); break; case Sparc::TBR: Op = SparcOperand::CreateToken("%tbr", S); break; case Sparc::ICC: if (name == "xcc") Op = SparcOperand::CreateToken("%xcc", S); else Op = SparcOperand::CreateToken("%icc", S); break; } break; } if (matchSparcAsmModifiers(EVal, E)) { E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); Op = SparcOperand::CreateImm(EVal, S, E); } break; case AsmToken::Minus: case AsmToken::Integer: case AsmToken::LParen: case AsmToken::Dot: if (!getParser().parseExpression(EVal, E)) Op = SparcOperand::CreateImm(EVal, S, E); break; case AsmToken::Identifier: { StringRef Identifier; if (!getParser().parseIdentifier(Identifier)) { E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier); const MCExpr *Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); if (isCall && getContext().getObjectFileInfo()->isPositionIndependent()) Res = SparcMCExpr::create(SparcMCExpr::VK_Sparc_WPLT30, Res, getContext()); Op = SparcOperand::CreateImm(Res, S, E); } break; } } return (Op) ? MatchOperand_Success : MatchOperand_ParseFail; } SparcAsmParser::OperandMatchResultTy SparcAsmParser::parseBranchModifiers(OperandVector &Operands) { // parse (,a|,pn|,pt)+ while (getLexer().is(AsmToken::Comma)) { Parser.Lex(); // Eat the comma if (!getLexer().is(AsmToken::Identifier)) return MatchOperand_ParseFail; StringRef modName = Parser.getTok().getString(); if (modName == "a" || modName == "pn" || modName == "pt") { Operands.push_back(SparcOperand::CreateToken(modName, Parser.getTok().getLoc())); Parser.Lex(); // eat the identifier. } } return MatchOperand_Success; } bool SparcAsmParser::matchRegisterName(const AsmToken &Tok, unsigned &RegNo, unsigned &RegKind) { int64_t intVal = 0; RegNo = 0; RegKind = SparcOperand::rk_None; if (Tok.is(AsmToken::Identifier)) { StringRef name = Tok.getString(); // %fp if (name.equals("fp")) { RegNo = Sparc::I6; RegKind = SparcOperand::rk_IntReg; return true; } // %sp if (name.equals("sp")) { RegNo = Sparc::O6; RegKind = SparcOperand::rk_IntReg; return true; } if (name.equals("y")) { RegNo = Sparc::Y; RegKind = SparcOperand::rk_Special; return true; } if (name.substr(0, 3).equals_lower("asr") && !name.substr(3).getAsInteger(10, intVal) && intVal > 0 && intVal < 32) { RegNo = ASRRegs[intVal]; RegKind = SparcOperand::rk_Special; return true; } // %fprs is an alias of %asr6. if (name.equals("fprs")) { RegNo = ASRRegs[6]; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("icc")) { RegNo = Sparc::ICC; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("psr")) { RegNo = Sparc::PSR; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("fsr")) { RegNo = Sparc::FSR; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("fq")) { RegNo = Sparc::FQ; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("csr")) { RegNo = Sparc::CPSR; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("cq")) { RegNo = Sparc::CPQ; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("wim")) { RegNo = Sparc::WIM; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tbr")) { RegNo = Sparc::TBR; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("xcc")) { // FIXME:: check 64bit. RegNo = Sparc::ICC; RegKind = SparcOperand::rk_Special; return true; } // %fcc0 - %fcc3 if (name.substr(0, 3).equals_lower("fcc") && !name.substr(3).getAsInteger(10, intVal) && intVal < 4) { // FIXME: check 64bit and handle %fcc1 - %fcc3 RegNo = Sparc::FCC0 + intVal; RegKind = SparcOperand::rk_Special; return true; } // %g0 - %g7 if (name.substr(0, 1).equals_lower("g") && !name.substr(1).getAsInteger(10, intVal) && intVal < 8) { RegNo = IntRegs[intVal]; RegKind = SparcOperand::rk_IntReg; return true; } // %o0 - %o7 if (name.substr(0, 1).equals_lower("o") && !name.substr(1).getAsInteger(10, intVal) && intVal < 8) { RegNo = IntRegs[8 + intVal]; RegKind = SparcOperand::rk_IntReg; return true; } if (name.substr(0, 1).equals_lower("l") && !name.substr(1).getAsInteger(10, intVal) && intVal < 8) { RegNo = IntRegs[16 + intVal]; RegKind = SparcOperand::rk_IntReg; return true; } if (name.substr(0, 1).equals_lower("i") && !name.substr(1).getAsInteger(10, intVal) && intVal < 8) { RegNo = IntRegs[24 + intVal]; RegKind = SparcOperand::rk_IntReg; return true; } // %f0 - %f31 if (name.substr(0, 1).equals_lower("f") && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) { RegNo = FloatRegs[intVal]; RegKind = SparcOperand::rk_FloatReg; return true; } // %f32 - %f62 if (name.substr(0, 1).equals_lower("f") && !name.substr(1, 2).getAsInteger(10, intVal) && intVal >= 32 && intVal <= 62 && (intVal % 2 == 0)) { // FIXME: Check V9 RegNo = DoubleRegs[intVal/2]; RegKind = SparcOperand::rk_DoubleReg; return true; } // %r0 - %r31 if (name.substr(0, 1).equals_lower("r") && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) { RegNo = IntRegs[intVal]; RegKind = SparcOperand::rk_IntReg; return true; } // %c0 - %c31 if (name.substr(0, 1).equals_lower("c") && !name.substr(1).getAsInteger(10, intVal) && intVal < 32) { RegNo = CoprocRegs[intVal]; RegKind = SparcOperand::rk_CoprocReg; return true; } if (name.equals("tpc")) { RegNo = Sparc::TPC; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tnpc")) { RegNo = Sparc::TNPC; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tstate")) { RegNo = Sparc::TSTATE; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tt")) { RegNo = Sparc::TT; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tick")) { RegNo = Sparc::TICK; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tba")) { RegNo = Sparc::TBA; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("pstate")) { RegNo = Sparc::PSTATE; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("tl")) { RegNo = Sparc::TL; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("pil")) { RegNo = Sparc::PIL; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("cwp")) { RegNo = Sparc::CWP; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("cansave")) { RegNo = Sparc::CANSAVE; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("canrestore")) { RegNo = Sparc::CANRESTORE; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("cleanwin")) { RegNo = Sparc::CLEANWIN; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("otherwin")) { RegNo = Sparc::OTHERWIN; RegKind = SparcOperand::rk_Special; return true; } if (name.equals("wstate")) { RegNo = Sparc::WSTATE; RegKind = SparcOperand::rk_Special; return true; } } return false; } // Determine if an expression contains a reference to the symbol // "_GLOBAL_OFFSET_TABLE_". static bool hasGOTReference(const MCExpr *Expr) { switch (Expr->getKind()) { case MCExpr::Target: if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr)) return hasGOTReference(SE->getSubExpr()); break; case MCExpr::Constant: break; case MCExpr::Binary: { const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr); return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS()); } case MCExpr::SymbolRef: { const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr); return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_"); } case MCExpr::Unary: return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr()); } return false; } const SparcMCExpr * SparcAsmParser::adjustPICRelocation(SparcMCExpr::VariantKind VK, const MCExpr *subExpr) { // When in PIC mode, "%lo(...)" and "%hi(...)" behave differently. // If the expression refers contains _GLOBAL_OFFSETE_TABLE, it is // actually a %pc10 or %pc22 relocation. Otherwise, they are interpreted // as %got10 or %got22 relocation. if (getContext().getObjectFileInfo()->isPositionIndependent()) { switch(VK) { default: break; case SparcMCExpr::VK_Sparc_LO: VK = (hasGOTReference(subExpr) ? SparcMCExpr::VK_Sparc_PC10 : SparcMCExpr::VK_Sparc_GOT10); break; case SparcMCExpr::VK_Sparc_HI: VK = (hasGOTReference(subExpr) ? SparcMCExpr::VK_Sparc_PC22 : SparcMCExpr::VK_Sparc_GOT22); break; } } return SparcMCExpr::create(VK, subExpr, getContext()); } bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc) { AsmToken Tok = Parser.getTok(); if (!Tok.is(AsmToken::Identifier)) return false; StringRef name = Tok.getString(); SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name); if (VK == SparcMCExpr::VK_Sparc_None) return false; Parser.Lex(); // Eat the identifier. if (Parser.getTok().getKind() != AsmToken::LParen) return false; Parser.Lex(); // Eat the LParen token. const MCExpr *subExpr; if (Parser.parseParenExpression(subExpr, EndLoc)) return false; EVal = adjustPICRelocation(VK, subExpr); return true; } extern "C" void LLVMInitializeSparcAsmParser() { RegisterMCAsmParser<SparcAsmParser> A(TheSparcTarget); RegisterMCAsmParser<SparcAsmParser> B(TheSparcV9Target); RegisterMCAsmParser<SparcAsmParser> C(TheSparcelTarget); } #define GET_REGISTER_MATCHER #define GET_MATCHER_IMPLEMENTATION #include "SparcGenAsmMatcher.inc" unsigned SparcAsmParser::validateTargetOperandClass(MCParsedAsmOperand &GOp, unsigned Kind) { SparcOperand &Op = (SparcOperand &)GOp; if (Op.isFloatOrDoubleReg()) { switch (Kind) { default: break; case MCK_DFPRegs: if (!Op.isFloatReg() || SparcOperand::MorphToDoubleReg(Op)) return MCTargetAsmParser::Match_Success; break; case MCK_QFPRegs: if (SparcOperand::MorphToQuadReg(Op)) return MCTargetAsmParser::Match_Success; break; } } if (Op.isIntReg() && Kind == MCK_IntPair) { if (SparcOperand::MorphToIntPairReg(Op)) return MCTargetAsmParser::Match_Success; } if (Op.isCoprocReg() && Kind == MCK_CoprocPair) { if (SparcOperand::MorphToCoprocPairReg(Op)) return MCTargetAsmParser::Match_Success; } return Match_InvalidOperand; }
lgpl-2.1
jkorab/camel
camel-core/src/main/java/org/apache/camel/component/directvm/DirectVmComponent.java
6000
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.directvm; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.camel.Endpoint; import org.apache.camel.impl.UriEndpointComponent; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.spi.Metadata; /** * The <a href="http://camel.apache.org/direct-vm.html">Direct VM Component</a> manages {@link DirectVmEndpoint} and holds the list of named direct-vm endpoints. */ public class DirectVmComponent extends UriEndpointComponent { private static final AtomicInteger START_COUNTER = new AtomicInteger(); // must keep a map of consumers on the component to ensure endpoints can lookup old consumers // later in case the DirectVmEndpoint was re-created due the old was evicted from the endpoints LRUCache // on DefaultCamelContext private static final ConcurrentMap<String, DirectVmConsumer> CONSUMERS = new ConcurrentHashMap<String, DirectVmConsumer>(); @Metadata(label = "producer") private boolean block; @Metadata(label = "producer", defaultValue = "30000") private long timeout = 30000L; private HeaderFilterStrategy headerFilterStrategy; @Metadata(label = "advanced", defaultValue = "true") private boolean propagateProperties = true; public DirectVmComponent() { super(DirectVmEndpoint.class); } /** * Gets all the consumer endpoints. * * @return consumer endpoints */ public static Collection<Endpoint> getConsumerEndpoints() { Collection<Endpoint> endpoints = new ArrayList<Endpoint>(CONSUMERS.size()); for (DirectVmConsumer consumer : CONSUMERS.values()) { endpoints.add(consumer.getEndpoint()); } return endpoints; } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { DirectVmEndpoint answer = new DirectVmEndpoint(uri, this); answer.setBlock(block); answer.setTimeout(timeout); answer.setPropagateProperties(propagateProperties); answer.configureProperties(parameters); setProperties(answer, parameters); return answer; } public DirectVmConsumer getConsumer(DirectVmEndpoint endpoint) { String key = getConsumerKey(endpoint.getEndpointUri()); return CONSUMERS.get(key); } public void addConsumer(DirectVmEndpoint endpoint, DirectVmConsumer consumer) { String key = getConsumerKey(endpoint.getEndpointUri()); DirectVmConsumer existing = CONSUMERS.putIfAbsent(key, consumer); if (existing != null) { String contextId = existing.getEndpoint().getCamelContext().getName(); throw new IllegalStateException("A consumer " + existing + " already exists from CamelContext: " + contextId + ". Multiple consumers not supported"); } } public void removeConsumer(DirectVmEndpoint endpoint, DirectVmConsumer consumer) { String key = getConsumerKey(endpoint.getEndpointUri()); CONSUMERS.remove(key); } private static String getConsumerKey(String uri) { if (uri.contains("?")) { // strip parameters uri = uri.substring(0, uri.indexOf('?')); } return uri; } @Override protected void doStart() throws Exception { super.doStart(); START_COUNTER.incrementAndGet(); } @Override protected void doStop() throws Exception { if (START_COUNTER.decrementAndGet() <= 0) { // clear queues when no more direct-vm components in use CONSUMERS.clear(); } super.doStop(); } public boolean isBlock() { return block; } /** * If sending a message to a direct endpoint which has no active consumer, * then we can tell the producer to block and wait for the consumer to become active. */ public void setBlock(boolean block) { this.block = block; } public long getTimeout() { return timeout; } /** * The timeout value to use if block is enabled. */ public void setTimeout(long timeout) { this.timeout = timeout; } public HeaderFilterStrategy getHeaderFilterStrategy() { return headerFilterStrategy; } /** * Sets a {@link HeaderFilterStrategy} that will only be applied on producer endpoints (on both directions: request and response). * <p>Default value: none.</p> */ public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; } public boolean isPropagateProperties() { return propagateProperties; } /** * Whether to propagate or not properties from the producer side to the consumer side, and vice versa. * <p>Default value: true.</p> */ public void setPropagateProperties(boolean propagateProperties) { this.propagateProperties = propagateProperties; } }
apache-2.0
russgove/PnP
Solutions/Governance.ExternalSharing/Governance.ExternalSharingWeb/Scripts/externalSharing.js
1972
// SCRIPT TO HANDLE SETTING THE STATUS BAR THAT EXTERNAL SHARING IS ENABLED ON THIS SITE. var jQuery = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.2.min.js"; // Is MDS enabled? if ("undefined" != typeof g_MinimalDownload && g_MinimalDownload && (window.location.pathname.toLowerCase()).endsWith("/_layouts/15/start.aspx") && "undefined" != typeof asyncDeltaManager) { // Register script for MDS if possible RegisterModuleInit("externalSharing.js", JavaScript_Embed); //MDS registration JavaScript_Embed(); //non MDS run } else { JavaScript_Embed(); } function JavaScript_Embed() { loadScript(jQuery, function () { $(document).ready(function () { var message = "This site can be shared with people outside of Contoso" // Execute status setter only after SP.JS has been loaded SP.SOD.executeOrDelayUntilScriptLoaded(function () { SetStatusBar(message); }, 'sp.js'); }); }); } function SetStatusBar(message) { var statusId = SP.UI.Status.addStatus(message); SP.UI.Status.setStatusPriColor(statusId, "#f0f0f0"); } function IsOnPage(pageName) { if (window.location.href.toLowerCase().indexOf(pageName.toLowerCase()) > -1) { return true; } else { return false; } } function loadScript(url, callback) { var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.src = url; // Attach handlers for all browsers var done = false; script.onload = script.onreadystatechange = function () { if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) { done = true; // Continue your code callback(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; head.removeChild(script); } }; head.appendChild(script); }
apache-2.0
chromium/chromium
third_party/blink/web_tests/external/wpt/shadow-dom/declarative/support/helpers.js
271
function setInnerHTML(el,content) { const fragment = (new DOMParser()).parseFromString(`<pre>${content}</pre>`, 'text/html', {includeShadowRoots: true}); (el instanceof HTMLTemplateElement ? el.content : el).replaceChildren(...fragment.body.firstChild.childNodes); }
bsd-3-clause
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/chart--minimum/24.d.ts
67
import { ChartMinimum24 } from "../../"; export = ChartMinimum24;
mit
tobowers/elasticsearch-kopf
src/kopf/models/warmer_filter.js
491
function WarmerFilter(id) { this.id = id; this.clone = function() { return new WarmerFilter(this.id); }; this.getSorting = function() { return undefined; }; this.equals = function(other) { return other !== null && this.id == other.id; }; this.isBlank = function() { return !notEmpty(this.id); }; this.matches = function(warmer) { if (this.isBlank()) { return true; } else { return warmer.id.indexOf(this.id) != -1; } }; }
mit
koshihikari/modularization
else/past/yuraku past/yuraku 0905 1001/request/pc/view/AutoAddressManagerForIE10.js
5275
jQuery.noConflict(); jQuery(document).ready(function($){ MYNAMESPACE.namespace('view.AutoAddressManagerForIE10'); MYNAMESPACE.view.AutoAddressManagerForIE10 = function() { this.initialize.apply(this, arguments); }; MYNAMESPACE.view.AutoAddressManagerForIE10.prototype = { _Num_Name1 : null ,_Num_Name2 : null ,_Text_Name1 : null ,_Text_Name2 : null ,_Text_Name3 : null ,_Name2 : '' ,_Name4 : '' ,_isCorrect : true ,_AddressNumInput : null ,_AddressNumlength : null ,initialize: function() {//初期設定的な var thisObj = this; _.bindAll( this ,'autoAddress' ,'ajaxZip3Action' ,'changeNameAddressNum' ,'changeNameAddressText' ,'realTimeCheck' ,'returnName' ,'ajaxZip3zip2addrAction' ); this._instances = {// } this._Num_Name1 = $('#AutoAddressNum1').attr('name') this._Num_Name2 = $('#AutoAddressNum2').attr('name') this._Text_Name1 = $('#AutoAddressText1').attr('name') this._Text_Name2 = $('#AutoAddressText2').attr('name') this._Text_Name3 = $('#AutoAddressText3').attr('name') } ,autoAddress: function() { var thisObj = this; $('#B1').click(function(){ var rimit = 10000 /*消すべき?*/ $(thisObj).trigger('onChangeAddressName',[thisObj._Num_Name1,thisObj._Num_Name2,thisObj._Text_Name1,thisObj._Text_Name2,thisObj._Text_Name3,rimit]); }) if($('#AutoAddressNum2').length === 0){ thisObj._AddressNumlength = 7 thisObj._AddressNumInput = $('#AutoAddressNum1') } else { thisObj._AddressNumlength = 4 thisObj._AddressNumInput = $('#AutoAddressNum2') //次のフォームへ移る $('form') .on('keyup', '#AutoAddressNum1', function(event) { if($('#AutoAddressNum1').val().replace('-', '').replace('-', '').length == 3){ $('#AutoAddressNum2').focus(); }; }) } thisObj._AddressNumInput .on('keyup change', function(event) { var countval = thisObj._AddressNumInput.val().replace('-', '').replace('-', '').replace(/[A-Za-z0-9]/g,function(s){return String.fromCharCode(s.charCodeAt(0)-0xFEE0)}); var count = countval.length; if(count == thisObj._AddressNumlength){ thisObj.ajaxZip3Action(); } }) } ,ajaxZip3Action: function() { var thisObj = this; thisObj.changeNameAddressNum();//name1、2を確定させるアクション thisObj.changeNameAddressText();//name3,4,5を確定させるアクション thisObj.ajaxZip3zip2addrAction(); /*カスタマイズ*/ thisObj.realTimeCheck();//飛ばされた項目をblurする。 thisObj.returnName();//name1,2を戻すアクション var rimit = 30 /*消すべき?*/ $(thisObj).trigger('onChangeAddressName',[thisObj._Num_Name1,thisObj._Num_Name2,thisObj._Text_Name1,thisObj._Text_Name2,thisObj._Text_Name3,rimit]); } ,changeNameAddressNum: function() { var thisObj = this; if($('#AutoAddressNum1').length !== 0){ // thisObj._Num_Name1 = $('#AutoAddressNum1').attr('name') $('#AutoAddressNum1').attr('name','name1') if($('#AutoAddressNum2').length !== 0){ // thisObj._Num_Name2 = $('#AutoAddressNum2').attr('name') $('#AutoAddressNum2').attr('name','name2') thisObj._Name2 = 'name2' } else { thisObj._Name2 = '' } } else { alert('class=AutoAddressNum1を設定してください。') } } ,changeNameAddressText: function() { var thisObj = this; if($('#AutoAddressText1').length !== 0){//true // thisObj._Text_Name1 = $('#AutoAddressText1').attr('name') $('#AutoAddressText1').attr('name','name3') if($('#AutoAddressText2').length !== 0){//true // thisObj._Text_Name2 = $('#AutoAddressText2').attr('name') $('#AutoAddressText2').attr('name','name4') thisObj._Name4 = 'name4' if($('#AutoAddressText3').length !== 0){//false thisObj._isCorrect = false; // thisObj._Text_Name3 = $('#AutoAddressText3').attr('name') $('#AutoAddressText3').attr('name','name5') } } else { thisObj._Name4 = 'name3' } } else { alert('class=AutoAddressText1を設定してください。') } } ,realTimeCheck: function() { var thisObj = this; $('#AutoAddressText1,#AutoAddressText2,#AutoAddressText3').blur() } ,returnName: function() { var thisObj = this; // alert(thisObj._Num_Name1+' , '+thisObj._Num_Name2+' , '+thisObj._Text_Name1+' , '+thisObj._Text_Name2+' , '+thisObj._Text_Name3) var arr = [ {'class':'AutoAddressNum1' , 'name':thisObj._Num_Name1 } ,{'class':'AutoAddressNum2' , 'name':thisObj._Num_Name2 } ,{'class':'AutoAddressText1' , 'name':thisObj._Text_Name1 } ,{'class':'AutoAddressText2' , 'name':thisObj._Text_Name2 } ,{'class':'AutoAddressText3' , 'name':thisObj._Text_Name3 } ] for (var i=0,len=arr.length; i<len; i++) { $('.' + arr[i]['class']).attr('name',arr[i]['name']); } } ,ajaxZip3zip2addrAction: function() { var thisObj = this; if(thisObj._isCorrect === true){ AjaxZip3.zip2addr('name1',thisObj._Name2,'name3',thisObj._Name4);//県・市区町村 } else if (thisObj._isCorrect === false){ AjaxZip3.zip2addr('name1',thisObj._Name2,'name3','name4','','name5');//県・市区・町村 } } } });
mit
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/deploy-rules/32.d.ts
65
import { DeployRules32 } from "../../"; export = DeployRules32;
mit
sashberd/cdnjs
ajax/libs/ag-grid/18.1.0/lib/rendering/overlays/overlayWrapperComponent.js
5069
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v18.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("../../utils"); var gridOptionsWrapper_1 = require("../../gridOptionsWrapper"); var context_1 = require("../../context/context"); var component_1 = require("../../widgets/component"); var componentRecipes_1 = require("../../components/framework/componentRecipes"); var OverlayWrapperComponent = (function (_super) { __extends(OverlayWrapperComponent, _super); function OverlayWrapperComponent() { return _super.call(this) || this; } OverlayWrapperComponent.prototype.init = function () { }; OverlayWrapperComponent.prototype.showLoadingOverlay = function (eOverlayWrapper) { var _this = this; this.setTemplate(OverlayWrapperComponent.LOADING_WRAPPER_OVERLAY_TEMPLATE); this.componentRecipes.newLoadingOverlayComponent().then(function (renderer) { var loadingOverlayWrapper = _this.getRefElement("loadingOverlayWrapper"); utils_1.Utils.removeAllChildren(loadingOverlayWrapper); loadingOverlayWrapper.appendChild(renderer.getGui()); }); this.showOverlay(eOverlayWrapper, this.getGui()); }; OverlayWrapperComponent.prototype.showNoRowsOverlay = function (eOverlayWrapper) { var _this = this; this.setTemplate(OverlayWrapperComponent.NO_ROWS_WRAPPER_OVERLAY_TEMPLATE); this.componentRecipes.newNoRowsOverlayComponent().then(function (renderer) { var noRowsOverlayWrapper = _this.getRefElement("noRowsOverlayWrapper"); utils_1.Utils.removeAllChildren(noRowsOverlayWrapper); noRowsOverlayWrapper.appendChild(renderer.getGui()); }); this.showOverlay(eOverlayWrapper, this.getGui()); }; OverlayWrapperComponent.prototype.hideOverlay = function (eOverlayWrapper) { utils_1.Utils.removeAllChildren(eOverlayWrapper); utils_1.Utils.setVisible(eOverlayWrapper, false); }; OverlayWrapperComponent.prototype.showOverlay = function (eOverlayWrapper, overlay) { if (overlay) { utils_1.Utils.removeAllChildren(eOverlayWrapper); utils_1.Utils.setVisible(eOverlayWrapper, true); eOverlayWrapper.appendChild(overlay); } else { console.warn('ag-Grid: unknown overlay'); this.hideOverlay(eOverlayWrapper); } }; // wrapping in outer div, and wrapper, is needed to center the loading icon // The idea for centering came from here: http://www.vanseodesign.com/css/vertical-centering/ OverlayWrapperComponent.LOADING_WRAPPER_OVERLAY_TEMPLATE = '<div class="ag-overlay-panel" role="presentation">' + '<div class="ag-overlay-wrapper ag-overlay-loading-wrapper" ref="loadingOverlayWrapper">[OVERLAY_TEMPLATE]</div>' + '</div>'; OverlayWrapperComponent.NO_ROWS_WRAPPER_OVERLAY_TEMPLATE = '<div class="ag-overlay-panel" role="presentation">' + '<div class="ag-overlay-wrapper ag-overlay-no-rows-wrapper" ref="noRowsOverlayWrapper">[OVERLAY_TEMPLATE]</div>' + '</div>'; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], OverlayWrapperComponent.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('componentRecipes'), __metadata("design:type", componentRecipes_1.ComponentRecipes) ], OverlayWrapperComponent.prototype, "componentRecipes", void 0); return OverlayWrapperComponent; }(component_1.Component)); exports.OverlayWrapperComponent = OverlayWrapperComponent;
mit
hsteinhaus/uavcan
libuavcan/test/node/scheduler.cpp
3882
/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #include <gtest/gtest.h> #include <uavcan/node/timer.hpp> #include <uavcan/util/method_binder.hpp> #include "../clock.hpp" #include "../transport/can/can.hpp" #include "test_node.hpp" #if !defined(UAVCAN_CPP11) || !defined(UAVCAN_CPP_VERSION) # error UAVCAN_CPP_VERSION #endif struct TimerCallCounter { std::vector<uavcan::TimerEvent> events_a; std::vector<uavcan::TimerEvent> events_b; void callA(const uavcan::TimerEvent& ev) { events_a.push_back(ev); } void callB(const uavcan::TimerEvent& ev) { events_b.push_back(ev); } typedef uavcan::MethodBinder<TimerCallCounter*, void (TimerCallCounter::*)(const uavcan::TimerEvent&)> Binder; Binder bindA() { return Binder(this, &TimerCallCounter::callA); } Binder bindB() { return Binder(this, &TimerCallCounter::callB); } }; /* * This test can fail on a non real time system. That's kinda sad but okay. */ TEST(Scheduler, Timers) { SystemClockDriver clock_driver; CanDriverMock can_driver(2, clock_driver); TestNode node(can_driver, clock_driver, 1); /* * Registration */ { TimerCallCounter tcc; uavcan::TimerEventForwarder<TimerCallCounter::Binder> a(node, tcc.bindA()); uavcan::TimerEventForwarder<TimerCallCounter::Binder> b(node, tcc.bindB()); ASSERT_EQ(0, node.getScheduler().getDeadlineScheduler().getNumHandlers()); const uavcan::MonotonicTime start_ts = clock_driver.getMonotonic(); a.startOneShotWithDeadline(start_ts + durMono(100000)); b.startPeriodic(durMono(1000)); ASSERT_EQ(2, node.getScheduler().getDeadlineScheduler().getNumHandlers()); /* * Spinning */ ASSERT_EQ(0, node.spin(start_ts + durMono(1000000))); ASSERT_EQ(1, tcc.events_a.size()); ASSERT_TRUE(areTimestampsClose(tcc.events_a[0].scheduled_time, start_ts + durMono(100000))); ASSERT_TRUE(areTimestampsClose(tcc.events_a[0].scheduled_time, tcc.events_a[0].real_time)); ASSERT_LT(900, tcc.events_b.size()); ASSERT_GT(1100, tcc.events_b.size()); { uavcan::MonotonicTime next_expected_deadline = start_ts + durMono(1000); for (unsigned i = 0; i < tcc.events_b.size(); i++) { ASSERT_TRUE(areTimestampsClose(tcc.events_b[i].scheduled_time, next_expected_deadline)); ASSERT_TRUE(areTimestampsClose(tcc.events_b[i].scheduled_time, tcc.events_b[i].real_time)); next_expected_deadline += durMono(1000); } } /* * Deinitialization */ ASSERT_EQ(1, node.getScheduler().getDeadlineScheduler().getNumHandlers()); ASSERT_FALSE(a.isRunning()); ASSERT_EQ(uavcan::MonotonicDuration::getInfinite(), a.getPeriod()); ASSERT_TRUE(b.isRunning()); ASSERT_EQ(1000, b.getPeriod().toUSec()); } ASSERT_EQ(0, node.getScheduler().getDeadlineScheduler().getNumHandlers()); // Both timers were destroyed by now ASSERT_EQ(0, node.spin(durMono(1000))); // Spin some more without timers } #if UAVCAN_CPP_VERSION >= UAVCAN_CPP11 TEST(Scheduler, TimerCpp11) { SystemClockDriver clock_driver; CanDriverMock can_driver(2, clock_driver); TestNode node(can_driver, clock_driver, 1); int count = 0; uavcan::Timer tm(node, [&count](const uavcan::TimerEvent&) { count++; }); ASSERT_EQ(0, node.getScheduler().getDeadlineScheduler().getNumHandlers()); tm.startPeriodic(uavcan::MonotonicDuration::fromMSec(10)); ASSERT_EQ(1, node.getScheduler().getDeadlineScheduler().getNumHandlers()); ASSERT_EQ(0, node.spin(uavcan::MonotonicDuration::fromMSec(100))); std::cout << count << std::endl; ASSERT_LE(5, count); ASSERT_GE(15, count); } #endif
mit