repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Block-code/TreeOfSaviorInteractiveMap | lib/Cake/Test/Case/View/Helper/PrototypeEngineHelperTest.php | 13119 | <?php
/**
* PrototypeEngine TestCase
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.View.Helper
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('View', 'View');
App::uses('HtmlHelper', 'View/Helper');
App::uses('JsHelper', 'View/Helper');
App::uses('PrototypeEngineHelper', 'View/Helper');
/**
* PrototypeEngineHelperTest
*
* @package Cake.Test.Case.View.Helper
*/
class PrototypeEngineHelperTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = $this->getMock('View', array('addScript'), array(&$controller));
$this->Proto = new PrototypeEngineHelper($this->View);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Proto);
}
/**
* test selector method
*
* @return void
*/
public function testSelector() {
$result = $this->Proto->get('#content');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$("content")');
$result = $this->Proto->get('a .remove');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$$("a .remove")');
$result = $this->Proto->get('document');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, "$(document)");
$result = $this->Proto->get('window');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, "$(window)");
$result = $this->Proto->get('ul');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$$("ul")');
$result = $this->Proto->get('#some_long-id.class');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$$("#some_long-id.class")');
}
/**
* test event binding
*
* @return void
*/
public function testEvent() {
$this->Proto->get('#myLink');
$result = $this->Proto->event('click', 'doClick', array('wrap' => false));
$expected = '$("myLink").observe("click", doClick);';
$this->assertEquals($expected, $result);
$result = $this->Proto->event('click', 'Element.hide(this);', array('stop' => false));
$expected = '$("myLink").observe("click", function (event) {Element.hide(this);});';
$this->assertEquals($expected, $result);
$result = $this->Proto->event('click', 'Element.hide(this);');
$expected = "\$(\"myLink\").observe(\"click\", function (event) {event.stop();\nElement.hide(this);});";
$this->assertEquals($expected, $result);
}
/**
* test dom ready event creation
*
* @return void
*/
public function testDomReady() {
$result = $this->Proto->domReady('foo.name = "bar";');
$expected = 'document.observe("dom:loaded", function (event) {foo.name = "bar";});';
$this->assertEquals($expected, $result);
}
/**
* test Each method
*
* @return void
*/
public function testEach() {
$this->Proto->get('#foo li');
$result = $this->Proto->each('item.hide();');
$expected = '$$("#foo li").each(function (item, index) {item.hide();});';
$this->assertEquals($expected, $result);
}
/**
* test Effect generation
*
* @return void
*/
public function testEffect() {
$this->Proto->get('#foo');
$result = $this->Proto->effect('show');
$expected = '$("foo").show();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('hide');
$expected = '$("foo").hide();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeIn');
$expected = '$("foo").appear();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeIn', array('speed' => 'fast'));
$expected = '$("foo").appear({duration:0.50000000000});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeIn', array('speed' => 'slow'));
$expected = '$("foo").appear({duration:2});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeOut');
$expected = '$("foo").fade();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeOut', array('speed' => 'fast'));
$expected = '$("foo").fade({duration:0.50000000000});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeOut', array('speed' => 'slow'));
$expected = '$("foo").fade({duration:2});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideIn');
$expected = 'Effect.slideDown($("foo"));';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideOut');
$expected = 'Effect.slideUp($("foo"));';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideOut', array('speed' => 'fast'));
$expected = 'Effect.slideUp($("foo"), {duration:0.50000000000});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideOut', array('speed' => 'slow'));
$expected = 'Effect.slideUp($("foo"), {duration:2});';
$this->assertEquals($expected, $result);
}
/**
* Test Request Generation
*
* @return void
*/
public function testRequest() {
$result = $this->Proto->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'var jsRequest = new Ajax.Request("/posts/view/1");';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/posts/view/1', array(
'method' => 'post',
'complete' => 'doComplete',
'before' => 'doBefore',
'success' => 'doSuccess',
'error' => 'doError',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/posts/view/1", {method:"post", onComplete:doComplete, onCreate:doBefore, onFailure:doError, onSuccess:doSuccess, parameters:{"name":"jim","height":"185cm"}});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/posts/view/1', array('update' => 'content'));
$expected = 'var jsRequest = new Ajax.Updater("content", "/posts/view/1");';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'update' => '#update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Updater("update-zone", "/people/edit/1", {method:"post", onComplete:doSuccess});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:doSuccess, onFailure:handleError, parameters:{"name":"jim","height":"185cm"}});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => '$("element").serialize()',
'dataExpression' => true,
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:doSuccess, onFailure:handleError, parameters:$("element").serialize()});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore();',
'success' => 'doSuccess();',
'complete' => 'doComplete();',
'error' => 'handleError();',
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:function (transport) {doComplete();}, onCreate:function (transport) {doBefore();}, onFailure:function (response, jsonHeader) {handleError();}, onSuccess:function (response, jsonHeader) {doSuccess();}});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'async' => false,
'method' => 'post',
'before' => 'doBefore();',
'success' => 'doSuccess();',
'complete' => 'doComplete();',
'error' => 'handleError();',
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {asynchronous:false, method:"post", onComplete:function (transport) {doComplete();}, onCreate:function (transport) {doBefore();}, onFailure:function (response, jsonHeader) {handleError();}, onSuccess:function (response, jsonHeader) {doSuccess();}});';
$this->assertEquals($expected, $result);
$this->Proto->get('#submit');
$result = $this->Proto->request('/users/login', array(
'before' => 'login.create(event)',
'complete' => 'login.complete(event)',
'update' => 'auth',
'data' => $this->Proto->serializeForm(array('isForm' => false, 'inline' => true)),
'dataExpression' => true
));
$this->assertTrue(strpos($result, '$($("submit").form).serialize()') > 0);
$this->assertFalse(strpos($result, 'parameters:function () {$($("submit").form).serialize()}') > 0);
}
/**
* test sortable list generation
*
* @return void
*/
public function testSortable() {
$this->Proto->get('#myList');
$result = $this->Proto->sortable(array(
'complete' => 'onComplete',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = 'var jsSortable = Sortable.create($("myList"), {onChange:onSort, onUpdate:onComplete});';
$this->assertEquals($expected, $result);
}
/**
* test drag() method. Scriptaculous lacks the ability to take an Array of Elements
* in new Drag() when selection is a multiple type. Iterate over the array.
*
* @return void
*/
public function testDrag() {
$this->Proto->get('#element');
$result = $this->Proto->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = 'var jsDrag = new Draggable($("element"), {onDrag:onDrag, onEnd:onStop, onStart:onStart, snap:[10,10]});';
$this->assertEquals($expected, $result);
$this->Proto->get('div.dragger');
$result = $this->Proto->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = '$$("div.dragger").each(function (item, index) {new Draggable(item, {onDrag:onDrag, onEnd:onStop, onStart:onStart, snap:[10,10]});});';
$this->assertEquals($expected, $result);
}
/**
* test drop() method
*
* @return void
*/
public function testDrop() {
$this->Proto->get('#element');
$result = $this->Proto->drop(array(
'hover' => 'onHover',
'drop' => 'onDrop',
'accept' => '.drag-me',
'wrapCallbacks' => false
));
$expected = 'Droppables.add($("element"), {accept:".drag-me", onDrop:onDrop, onHover:onHover});';
$this->assertEquals($expected, $result);
}
/**
* ensure that slider() method behaves properly
*
* @return void
*/
public function testSlider() {
$this->Proto->get('#element');
$result = $this->Proto->slider(array(
'handle' => '#handle',
'direction' => 'horizontal',
'change' => 'onChange',
'complete' => 'onComplete',
'value' => 4,
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Control.Slider($("handle"), $("element"), {axis:"horizontal", onChange:onComplete, onSlide:onChange, sliderValue:4});';
$this->assertEquals($expected, $result);
$this->Proto->get('#element');
$result = $this->Proto->slider(array(
'handle' => '#handle',
'change' => 'change();',
'complete' => 'complete();',
'value' => 4,
'min' => 10,
'max' => 100
));
$expected = 'var jsSlider = new Control.Slider($("handle"), $("element"), {onChange:function (value) {complete();}, onSlide:function (value) {change();}, range:$R(10,100), sliderValue:4});';
$this->assertEquals($expected, $result);
}
/**
* test the serializeForm implementation.
*
* @return void
*/
public function testSerializeForm() {
$this->Proto->get('#element');
$result = $this->Proto->serializeForm(array('isForm' => true));
$expected = '$("element").serialize();';
$this->assertEquals($expected, $result);
$result = $this->Proto->serializeForm(array('isForm' => true, 'inline' => true));
$expected = '$("element").serialize()';
$this->assertEquals($expected, $result);
$result = $this->Proto->serializeForm(array('isForm' => false));
$expected = '$($("element").form).serialize();';
$this->assertEquals($expected, $result);
$result = $this->Proto->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$($("element").form).serialize()';
$this->assertEquals($expected, $result);
}
}
| mit |
JakeShanley/xamarin-forms-samples | TodoMvvm/TodoMvvm/Views/TodoItemCell.cs | 949 | using System;
using Xamarin.Forms;
namespace TodoMvvm
{
public class TodoItemCell : ViewCell
{
public TodoItemCell ()
{
var label = new Label {
YAlign = TextAlignment.Center
};
label.SetBinding (Label.TextProperty, "Name");
var tick = new Image {
Source = FileImageSource.FromFile ("check"),
};
tick.SetBinding (Image.IsVisibleProperty, "Done");
var layout = new StackLayout {
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.StartAndExpand,
Children = {label, tick}
};
View = layout;
}
protected override void OnBindingContextChanged ()
{
// Fixme : this is happening because the View.Parent is getting
// set after the Cell gets the binding context set on it. Then it is inheriting
// the parents binding context.
View.BindingContext = BindingContext;
base.OnBindingContextChanged ();
}
}
}
| mit |
veikkoeeva/orleans | test/DependencyInjection.Tests/Autofac/DependencyInjectionDisambiguationTestsUsingAutofac.cs | 647 | using System;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace DependencyInjection.Tests.Autofac
{
[TestCategory("DI"), TestCategory("Functional")]
public class DependencyInjectionDisambiguationTestsUsingAutofac : DependencyInjectionDisambiguationTestRunner
{
protected override IServiceProvider BuildServiceProvider(IServiceCollection services)
{
var containerBuilder = new ContainerBuilder();
containerBuilder.Populate(services);
return new AutofacServiceProvider(containerBuilder.Build());
}
}
}
| mit |
ahmedvc/umple | Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/associations/CARuleMiner.java | 2479 | /*
* 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/>.
*/
/*
* CARuleMiner.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.associations;
import java.util.ArrayList;
import weka.core.Instances;
import weka.core.OptionHandler;
/**
* Interface for learning class association rules. All schemes for learning
* class association rules implemement this interface.
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision: 10172 $
*/
public interface CARuleMiner extends OptionHandler {
/**
* Method for mining class association rules. Must initialize all fields of
* the CARuleMiner that are not being set via options (ie. multiple calls of
* mineCARs must always lead to the same result). Must not change the dataset
* in any way.
*
* @param data the insatnces for which class association rules are mined
* @throws Exception throws exception if class association rules cannot be
* mined
* @return class association rules and their scoring metric in an FastVector
* array
*/
public ArrayList<Object>[] mineCARs(Instances data) throws Exception;
/**
* Gets the instances without the class attribute
*
* @return the instances withoput the class attribute
*/
public Instances getInstancesNoClass();
/**
* Gets the class attribute and its values for all instances
*
* @return the class attribute and its values for all instances
*/
public Instances getInstancesOnlyClass();
/**
* Gets name of the scoring metric used for car mining
*
* @return string containing the name of the scoring metric
*/
public String metricString();
/**
* Sets the class index for the class association rule miner
*
* @param index the class index
*/
public void setClassIndex(int index);
}
| mit |
travis-south/symfony2 | vendor/phing/phing/classes/phing/BuildException.php | 3591 | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
/**
* BuildException is for when things go wrong in a build execution.
*
* @author Andreas Aderhold <andi@binarycloud.com>
* @version $Id$
* @package phing
*/
class BuildException extends Exception {
/**
* Location in the xml file.
* @var Location
*/
protected $location;
/**
* The nested "cause" exception.
* @var Exception
*/
protected $cause;
/**
* Construct a BuildException.
* Supported signatures:
* throw new BuildException($causeExc);
* throw new BuildException($msg);
* throw new Buildexception($causeExc, $loc);
* throw new BuildException($msg, $causeExc);
* throw new BuildException($msg, $loc);
* throw new BuildException($msg, $causeExc, $loc);
* @param Exception|string $p1
* @param Location|Exception|null $p2
* @param Location|null $p3
*/
public function __construct($p1, $p2 = null, $p3 = null) {
$cause = null;
$loc = null;
$msg = "";
if ($p3 !== null) {
$cause = $p2;
$loc = $p3;
$msg = $p1;
} elseif ($p2 !== null) {
if ($p2 instanceof Exception) {
$cause = $p2;
$msg = $p1;
} elseif ($p2 instanceof Location) {
$loc = $p2;
if ($p1 instanceof Exception) {
$cause = $p1;
} else {
$msg = $p1;
}
}
} elseif ($p1 instanceof Exception) {
$cause = $p1;
} else {
$msg = $p1;
}
parent::__construct($msg);
if ($cause !== null) {
$this->cause = $cause;
$this->message .= " [wrapped: " . $cause->getMessage() ."]";
}
if ($loc !== null) {
$this->setLocation($loc);
}
}
/**
* Gets the cause exception.
*
* @return Exception
*/
public function getCause() {
return $this->cause;
}
/**
* Gets the location of error in XML file.
*
* @return Location
*/
public function getLocation() {
return $this->location;
}
/**
* Sets the location of error in XML file.
*
* @param Location $loc
*/
public function setLocation(Location $loc) {
$this->location = $loc;
$this->message = $loc->toString() . ': ' . $this->message;
}
}
| mit |
ilovett/material | gulp/util.js | 8815 | var config = require('./config');
var gulp = require('gulp');
var gutil = require('gulp-util');
var frep = require('gulp-frep');
var fs = require('fs');
var args = require('minimist')(process.argv.slice(2));
var path = require('path');
var rename = require('gulp-rename');
var filter = require('gulp-filter');
var concat = require('gulp-concat');
var series = require('stream-series');
var lazypipe = require('lazypipe');
var glob = require('glob').sync;
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var ngAnnotate = require('gulp-ng-annotate');
var insert = require('gulp-insert');
var gulpif = require('gulp-if');
var nano = require('gulp-cssnano');
var postcss = require('postcss');
var _ = require('lodash');
var constants = require('./const');
var VERSION = constants.VERSION;
var BUILD_MODE = constants.BUILD_MODE;
var IS_DEV = constants.IS_DEV;
var ROOT = constants.ROOT;
var utils = require('../scripts/gulp-utils.js');
exports.buildJs = buildJs;
exports.autoprefix = utils.autoprefix;
exports.buildModule = buildModule;
exports.filterNonCodeFiles = filterNonCodeFiles;
exports.readModuleArg = readModuleArg;
exports.themeBuildStream = themeBuildStream;
exports.minifyCss = minifyCss;
exports.dedupeCss = dedupeCss;
exports.args = args;
/**
* Builds the entire component library javascript.
* @param {boolean} isRelease Whether to build in release mode.
*/
function buildJs () {
var jsFiles = config.jsBaseFiles.concat([path.join(config.paths, '*.js')]);
gutil.log("building js files...");
var jsBuildStream = gulp.src( jsFiles )
.pipe(filterNonCodeFiles())
.pipe(utils.buildNgMaterialDefinition())
.pipe(plumber())
.pipe(ngAnnotate())
.pipe(utils.addJsWrapper(true));
var jsProcess = series(jsBuildStream, themeBuildStream() )
.pipe(concat('angular-material.js'))
.pipe(BUILD_MODE.transform())
.pipe(insert.prepend(config.banner))
.pipe(insert.append(';window.ngMaterial={version:{full: "' + VERSION +'"}};'))
.pipe(gulp.dest(config.outputDir))
.pipe(gulpif(!IS_DEV, uglify({ preserveComments: 'some' })))
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(config.outputDir));
return series(jsProcess, deployMaterialMocks());
// Deploy the `angular-material-mocks.js` file to the `dist` directory
function deployMaterialMocks() {
return gulp.src(config.mockFiles)
.pipe(gulp.dest(config.outputDir));
}
}
function minifyCss(extraOptions) {
var options = {
autoprefixer: false,
reduceTransforms: false,
svgo: false,
safe: true
};
return nano(_.assign(options, extraOptions));
}
function buildModule(module, opts) {
opts = opts || {};
if ( module.indexOf(".") < 0) {
module = "material.components." + module;
}
gutil.log('Building ' + module + (opts.isRelease && ' minified' || '') + ' ...');
var name = module.split('.').pop();
utils.copyDemoAssets(name, 'src/components/', 'dist/demos/');
var stream = utils.filesForModule(module)
.pipe(filterNonCodeFiles())
.pipe(filterLayoutAttrFiles())
.pipe(gulpif('*.scss', buildModuleStyles(name)))
.pipe(gulpif('*.js', buildModuleJs(name)));
if (module === 'material.core') {
stream = splitStream(stream);
}
return stream
.pipe(BUILD_MODE.transform())
.pipe(insert.prepend(config.banner))
.pipe(gulpif(opts.minify, buildMin()))
.pipe(gulpif(opts.useBower, buildBower()))
.pipe(gulp.dest(BUILD_MODE.outputDir + name));
function splitStream (stream) {
var js = series(stream, themeBuildStream())
.pipe(filter('**/*.js'))
.pipe(concat('core.js'));
var css = stream
.pipe(filter(['**/*.css', '!**/ie_fixes.css']))
return series(js, css);
}
function buildMin() {
return lazypipe()
.pipe(gulpif, /.css$/, minifyCss(),
uglify({ preserveComments: 'some' })
.on('error', function(e) {
console.log('\x07',e.message);
return this.end();
}
)
)
.pipe(rename, function(path) {
path.extname = path.extname
.replace(/.js$/, '.min.js')
.replace(/.css$/, '.min.css');
})
();
}
function buildBower() {
return lazypipe()
.pipe(utils.buildModuleBower, name, VERSION)();
}
function buildModuleJs(name) {
var patterns = [
{
pattern: /\@ngInject/g,
replacement: 'ngInject'
},
{
// Turns `thing.$inject` into `thing['$inject']` in order to prevent
// Closure from stripping it from objects with an @constructor
// annotation.
pattern: /\.\$inject\b/g,
replacement: "['$inject']"
}
];
return lazypipe()
.pipe(plumber)
.pipe(ngAnnotate)
.pipe(frep, patterns)
.pipe(concat, name + '.js')
();
}
function buildModuleStyles(name) {
var files = [];
config.themeBaseFiles.forEach(function(fileGlob) {
files = files.concat(glob(fileGlob, { cwd: ROOT }));
});
var baseStyles = files.map(function(fileName) {
return fs.readFileSync(fileName, 'utf8').toString();
}).join('\n');
return lazypipe()
.pipe(insert.prepend, baseStyles)
.pipe(gulpif, /theme.scss/, rename(name + '-default-theme.scss'), concat(name + '.scss'))
// Theme files are suffixed with the `default-theme.scss` string.
// In some cases there are multiple theme SCSS files, which should be concatenated together.
.pipe(gulpif, /default-theme.scss/, concat(name + '-default-theme.scss'))
.pipe(sass)
.pipe(dedupeCss)
.pipe(utils.autoprefix)
(); // Invoke the returning lazypipe function to create our new pipe.
}
}
function readModuleArg() {
var module = args.c ? 'material.components.' + args.c : (args.module || args.m);
if (!module) {
gutil.log('\nProvide a component argument via `-c`:',
'\nExample: -c toast');
gutil.log('\nOr provide a module argument via `--module` or `-m`.',
'\nExample: --module=material.components.toast or -m material.components.dialog');
process.exit(1);
}
return module;
}
/**
* We are not injecting the layout-attributes selectors into the core module css,
* otherwise we would have the layout-classes and layout-attributes in there.
*/
function filterLayoutAttrFiles() {
return filter(function(file) {
return !/.*layout-attributes\.scss/g.test(file.path);
});
}
function filterNonCodeFiles() {
return filter(function(file) {
return !/demo|module\.json|script\.js|\.spec.js|README/.test(file.path);
});
}
// builds the theming related css and provides it as a JS const for angular
function themeBuildStream() {
return gulp.src( config.themeBaseFiles.concat(path.join(config.paths, '*-theme.scss')) )
.pipe(concat('default-theme.scss'))
.pipe(utils.hoistScssVariables())
.pipe(sass())
.pipe(dedupeCss())
// The PostCSS orderedValues plugin modifies the theme color expressions.
.pipe(minifyCss({ orderedValues: false }))
.pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS'));
}
// Removes duplicated CSS properties.
function dedupeCss() {
var prefixRegex = /-(webkit|moz|ms|o)-.+/;
return insert.transform(function(contents) {
// Parse the CSS into an AST.
var parsed = postcss.parse(contents);
// Walk through all the rules, skipping comments, media queries etc.
parsed.walk(function(rule) {
// Skip over any comments, media queries and rules that have less than 2 properties.
if (rule.type !== 'rule' || !rule.nodes || rule.nodes.length < 2) return;
// Walk all of the properties within a rule.
rule.walk(function(prop) {
// Check if there's a similar property that comes after the current one.
var hasDuplicate = validateProp(prop) && _.find(rule.nodes, function(otherProp) {
return prop !== otherProp && prop.prop === otherProp.prop && validateProp(otherProp);
});
// Remove the declaration if it's duplicated.
if (hasDuplicate) {
prop.remove();
gutil.log(gutil.colors.yellow(
'Removed duplicate property: "' +
prop.prop + ': ' + prop.value + '" from "' + rule.selector + '"...'
));
}
});
});
// Turn the AST back into CSS.
return parsed.toResult().css;
});
// Checks if a property is a style declaration and that it
// doesn't contain any vendor prefixes.
function validateProp(prop) {
return prop && prop.type === 'decl' && ![prop.prop, prop.value].some(function(value) {
return value.indexOf('-') > -1 && prefixRegex.test(value);
});
}
}
| mit |
dmourato/mastercv | scaffolding/test_juicebox/app/abstractors/tweet.js | 393 | // placeholder abstractor
var abstractor = function () {}
abstractor.prototype.init = function (context) {
return new Promise(function (resolve, reject) {
// initialize abstractor
resolve()
})
}
abstractor.prototype.abstract = function (context) {
return new Promise(function (resolve, reject) {
// abstract directive
return resolve()
})
}
module.exports = new abstractor()
| mit |
annvnzndrvn/discord-wikibot | node_modules/discord.js/src/structures/GroupDMChannel.js | 3516 | const Channel = require('./Channel');
const TextBasedChannel = require('./interface/TextBasedChannel');
const Collection = require('../util/Collection');
/*
{ type: 3,
recipients:
[ { username: 'Charlie',
id: '123',
discriminator: '6631',
avatar: '123' },
{ username: 'Ben',
id: '123',
discriminator: '2055',
avatar: '123' },
{ username: 'Adam',
id: '123',
discriminator: '2406',
avatar: '123' } ],
owner_id: '123',
name: null,
last_message_id: '123',
id: '123',
icon: null }
*/
/**
* Represents a Group DM on Discord
* @extends {Channel}
* @implements {TextBasedChannel}
*/
class GroupDMChannel extends Channel {
constructor(client, data) {
super(client, data);
this.type = 'group';
this.messages = new Collection();
this._typing = new Map();
}
setup(data) {
super.setup(data);
/**
* The name of this Group DM, can be null if one isn't set.
* @type {string}
*/
this.name = data.name;
/**
* A hash of the Group DM icon.
* @type {string}
*/
this.icon = data.icon;
/**
* The user ID of this Group DM's owner.
* @type {string}
*/
this.ownerID = data.owner_id;
if (!this.recipients) {
/**
* A collection of the recipients of this DM, mapped by their ID.
* @type {Collection<string, User>}
*/
this.recipients = new Collection();
}
if (data.recipients) {
for (const recipient of data.recipients) {
const user = this.client.dataManager.newUser(recipient);
this.recipients.set(user.id, user);
}
}
this.lastMessageID = data.last_message_id;
}
/**
* The owner of this Group DM.
* @type {User}
* @readonly
*/
get owner() {
return this.client.users.get(this.ownerID);
}
/**
* Whether this channel equals another channel. It compares all properties, so for most operations
* it is advisable to just compare `channel.id === channel2.id` as it is much faster and is often
* what most users need.
* @param {GroupDMChannel} channel Channel to compare with
* @returns {boolean}
*/
equals(channel) {
const equal = channel &&
this.id === channel.id &&
this.name === channel.name &&
this.icon === channel.icon &&
this.ownerID === channel.ownerID;
if (equal) {
return this.recipients.equals(channel.recipients);
}
return equal;
}
/**
* When concatenated with a string, this automatically concatenates the channel's name instead of the Channel object.
* @returns {string}
* @example
* // logs: Hello from My Group DM!
* console.log(`Hello from ${channel}!`);
* @example
* // logs: Hello from My Group DM!
* console.log(`Hello from ' + channel + '!');
*/
toString() {
return this.name;
}
// These are here only for documentation purposes - they are implemented by TextBasedChannel
send() { return; }
sendMessage() { return; }
sendEmbed() { return; }
sendFile() { return; }
sendCode() { return; }
fetchMessage() { return; }
fetchMessages() { return; }
fetchPinnedMessages() { return; }
startTyping() { return; }
stopTyping() { return; }
get typing() { return; }
get typingCount() { return; }
createCollector() { return; }
awaitMessages() { return; }
bulkDelete() { return; }
_cacheMessage() { return; }
}
TextBasedChannel.applyToClass(GroupDMChannel, true);
module.exports = GroupDMChannel;
| mit |
plumer/codana | tomcat_files/8.0.21/ELInterpreter.java | 2073 | /*
* 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.jasper.compiler;
import org.apache.jasper.JspCompilationContext;
/**
* Defines the interface for the expression language interpreter. This allows
* users to provide custom EL interpreter implementations that can optimise
* EL processing for an application by , for example, performing code generation
* for simple expressions.
*/
public interface ELInterpreter {
/**
* Returns the string representing the code that will be inserted into the
* servlet generated for JSP. The default implementation creates a call to
* {@link org.apache.jasper.runtime.PageContextImpl#proprietaryEvaluate(
* String, Class, javax.servlet.jsp.PageContext,
* org.apache.jasper.runtime.ProtectedFunctionMapper)} but other
* implementations may produce more optimised code.
*
* @param expression a String containing zero or more "${}" expressions
* @param expectedType the expected type of the interpreted result
* @param fnmapvar Variable pointing to a function map.
* @return a String representing a call to the EL interpreter.
*/
public String interpreterCall(JspCompilationContext context,
boolean isTagFile, String expression,
Class<?> expectedType, String fnmapvar);
}
| mit |
alex-friedl/crossplatform-push-notifications-example | app/ios/Pods/boost-for-react-native/boost/iostreams/filter/counter.hpp | 2506 | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2005-2007 Jonathan Turkanis
// 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.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
#define BOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
#if defined(_MSC_VER)
# pragma once
#endif
#include <algorithm> // count.
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/char_traits.hpp>
#include <boost/iostreams/operations.hpp>
#include <boost/iostreams/pipeline.hpp>
// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // VC7.1 C4244.
namespace boost { namespace iostreams {
//
// Template name: basic_counter.
// Template parameters:
// Ch - The character type.
// Description: Filter which counts lines and characters.
//
template<typename Ch>
class basic_counter {
public:
typedef Ch char_type;
struct category
: dual_use,
filter_tag,
multichar_tag,
optimally_buffered_tag
{ };
explicit basic_counter(int first_line = 0, int first_char = 0)
: lines_(first_line), chars_(first_char)
{ }
int lines() const { return lines_; }
int characters() const { return chars_; }
std::streamsize optimal_buffer_size() const { return 0; }
template<typename Source>
std::streamsize read(Source& src, char_type* s, std::streamsize n)
{
std::streamsize result = iostreams::read(src, s, n);
if (result == -1)
return -1;
lines_ += std::count(s, s + result, char_traits<Ch>::newline());
chars_ += result;
return result;
}
template<typename Sink>
std::streamsize write(Sink& snk, const char_type* s, std::streamsize n)
{
std::streamsize result = iostreams::write(snk, s, n);
lines_ += std::count(s, s + result, char_traits<Ch>::newline());
chars_ += result;
return result;
}
private:
int lines_;
int chars_;
};
BOOST_IOSTREAMS_PIPABLE(basic_counter, 1)
typedef basic_counter<char> counter;
typedef basic_counter<wchar_t> wcounter;
} } // End namespaces iostreams, boost.
#include <boost/iostreams/detail/config/enable_warnings.hpp>
#endif // #ifndef BOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
| mit |
cdnjs/cdnjs | ajax/libs/react-timeago/6.0.0/language-strings/cy.js | 544 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
// Welsh
var strings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: 'yn ôl',
suffixFromNow: 'o hyn',
seconds: 'llai na munud',
minute: 'am funud',
minutes: '%d munud',
hour: 'tua awr',
hours: 'am %d awr',
day: 'y dydd',
days: '%d diwrnod',
month: 'tua mis',
months: '%d mis',
year: 'am y flwyddyn',
years: '%d blynedd',
wordSeparator: ' '
};
var _default = strings;
exports["default"] = _default; | mit |
clinique/openhab2 | bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/transport/MiIoAsyncCommunication.java | 16142 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.miio.internal.transport;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.openhab.binding.miio.internal.Message;
import org.openhab.binding.miio.internal.MiIoBindingConstants;
import org.openhab.binding.miio.internal.MiIoCommand;
import org.openhab.binding.miio.internal.MiIoCrypto;
import org.openhab.binding.miio.internal.MiIoCryptoException;
import org.openhab.binding.miio.internal.MiIoMessageListener;
import org.openhab.binding.miio.internal.MiIoSendCommand;
import org.openhab.binding.miio.internal.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
/**
* The {@link MiIoAsyncCommunication} is responsible for communications with the Mi IO devices
*
* @author Marcel Verpaalen - Initial contribution
*/
public class MiIoAsyncCommunication {
private static final int MSG_BUFFER_SIZE = 2048;
private final Logger logger = LoggerFactory.getLogger(MiIoAsyncCommunication.class);
private final String ip;
private final byte[] token;
private byte[] deviceId;
private DatagramSocket socket;
private List<MiIoMessageListener> listeners = new CopyOnWriteArrayList<>();
private AtomicInteger id = new AtomicInteger(-1);
private int timeDelta;
private int timeStamp;
private final JsonParser parser;
private MessageSenderThread senderThread;
private boolean connected;
private ThingStatusDetail status;
private int errorCounter;
private int timeout;
private boolean needPing = true;
private static final int MAX_ERRORS = 3;
private static final int MAX_ID = 15000;
private ConcurrentLinkedQueue<MiIoSendCommand> concurrentLinkedQueue = new ConcurrentLinkedQueue<MiIoSendCommand>();
public MiIoAsyncCommunication(String ip, byte[] token, byte[] did, int id, int timeout) {
this.ip = ip;
this.token = token;
this.deviceId = did;
this.timeout = timeout;
setId(id);
parser = new JsonParser();
senderThread = new MessageSenderThread();
senderThread.start();
}
protected List<MiIoMessageListener> getListeners() {
return listeners;
}
/**
* Registers a {@link MiIoMessageListener} to be called back, when data is received.
* If no {@link MessageSenderThread} exists, when the method is called, it is being set up.
*
* @param listener {@link MiIoMessageListener} to be called back
*/
public synchronized void registerListener(MiIoMessageListener listener) {
needPing = true;
startReceiver();
if (!getListeners().contains(listener)) {
logger.trace("Adding socket listener {}", listener);
getListeners().add(listener);
}
}
/**
* Unregisters a {@link MiIoMessageListener}. If there are no listeners left,
* the {@link MessageSenderThread} is being closed.
*
* @param listener {@link MiIoMessageListener} to be unregistered
*/
public synchronized void unregisterListener(MiIoMessageListener listener) {
getListeners().remove(listener);
if (getListeners().isEmpty()) {
concurrentLinkedQueue.clear();
close();
}
}
public int queueCommand(MiIoCommand command) throws MiIoCryptoException, IOException {
return queueCommand(command, "[]");
}
public int queueCommand(MiIoCommand command, String params) throws MiIoCryptoException, IOException {
return queueCommand(command.getCommand(), params);
}
public int queueCommand(String command, String params)
throws MiIoCryptoException, IOException, JsonSyntaxException {
try {
JsonObject fullCommand = new JsonObject();
int cmdId = id.incrementAndGet();
if (cmdId > MAX_ID) {
id.set(0);
}
fullCommand.addProperty("id", cmdId);
fullCommand.addProperty("method", command);
fullCommand.add("params", parser.parse(params));
MiIoSendCommand sendCmd = new MiIoSendCommand(cmdId, MiIoCommand.getCommand(command),
fullCommand.toString());
concurrentLinkedQueue.add(sendCmd);
logger.debug("Command added to Queue {} -> {} (Device: {} token: {} Queue: {})", fullCommand.toString(), ip,
Utils.getHex(deviceId), Utils.getHex(token), concurrentLinkedQueue.size());
if (needPing) {
sendPing(ip);
}
return cmdId;
} catch (JsonSyntaxException e) {
logger.warn("Send command '{}' with parameters {} -> {} (Device: {}) gave error {}", command, params, ip,
Utils.getHex(deviceId), e.getMessage());
throw e;
}
}
MiIoSendCommand sendMiIoSendCommand(MiIoSendCommand miIoSendCommand) {
String errorMsg = "Unknown Error while sending command";
String decryptedResponse = "";
try {
decryptedResponse = sendCommand(miIoSendCommand.getCommandString(), token, ip, deviceId);
// hack due to avoid invalid json errors from some misbehaving device firmwares
decryptedResponse = decryptedResponse.replace(",,", ",");
JsonElement response;
response = parser.parse(decryptedResponse);
if (response.isJsonObject()) {
logger.trace("Received JSON message {}", response.toString());
miIoSendCommand.setResponse(response.getAsJsonObject());
return miIoSendCommand;
} else {
errorMsg = "Received message is invalid JSON";
logger.debug("{}: {}", errorMsg, decryptedResponse);
}
} catch (MiIoCryptoException | IOException e) {
logger.debug("Send command '{}' -> {} (Device: {}) gave error {}", miIoSendCommand.getCommandString(), ip,
Utils.getHex(deviceId), e.getMessage());
errorMsg = e.getMessage();
} catch (JsonSyntaxException e) {
logger.warn("Could not parse '{}' <- {} (Device: {}) gave error {}", decryptedResponse,
miIoSendCommand.getCommandString(), Utils.getHex(deviceId), e.getMessage());
errorMsg = "Received message is invalid JSON";
}
JsonObject erroResp = new JsonObject();
erroResp.addProperty("error", errorMsg);
miIoSendCommand.setResponse(erroResp);
return miIoSendCommand;
}
public synchronized void startReceiver() {
if (senderThread == null) {
senderThread = new MessageSenderThread();
}
if (!senderThread.isAlive()) {
senderThread.start();
}
}
/**
* The {@link MessageSenderThread} is responsible for consuming messages from the queue and sending these to the
* device
*
*/
private class MessageSenderThread extends Thread {
public MessageSenderThread() {
super("Mi IO MessageSenderThread");
setDaemon(true);
}
@Override
public void run() {
logger.debug("Starting Mi IO MessageSenderThread");
while (!interrupted()) {
try {
if (concurrentLinkedQueue.isEmpty()) {
Thread.sleep(100);
continue;
}
MiIoSendCommand queuedMessage = concurrentLinkedQueue.remove();
MiIoSendCommand miIoSendCommand = sendMiIoSendCommand(queuedMessage);
for (MiIoMessageListener listener : listeners) {
logger.trace("inform listener {}, data {} from {}", listener, queuedMessage, miIoSendCommand);
try {
listener.onMessageReceived(miIoSendCommand);
} catch (Exception e) {
logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
}
}
} catch (NoSuchElementException e) {
// ignore
} catch (InterruptedException e) {
// That's our signal to stop
break;
} catch (Exception e) {
logger.warn("Error while polling/sending message", e);
}
}
logger.debug("Finished Mi IO MessageSenderThread");
}
}
private String sendCommand(String command, byte[] token, String ip, byte[] deviceId)
throws MiIoCryptoException, IOException {
byte[] encr;
encr = MiIoCrypto.encrypt(command.getBytes(), token);
timeStamp = (int) TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().getTime().getTime());
byte[] sendMsg = Message.createMsgData(encr, token, deviceId, timeStamp + timeDelta);
Message miIoResponseMsg = sendData(sendMsg, ip);
if (miIoResponseMsg == null) {
if (logger.isTraceEnabled()) {
logger.trace("No response from device {} at {} for command {}.\r\n{}", Utils.getHex(deviceId), ip,
command, (new Message(sendMsg)).toSting());
} else {
logger.debug("No response from device {} at {} for command {}.", Utils.getHex(deviceId), ip, command);
}
errorCounter++;
if (errorCounter > MAX_ERRORS) {
status = ThingStatusDetail.CONFIGURATION_ERROR;
sendPing(ip);
}
return "{\"error\":\"No Response\"}";
}
if (!miIoResponseMsg.isChecksumValid()) {
return "{\"error\":\"Message has invalid checksum\"}";
}
if (errorCounter > 0) {
errorCounter = 0;
status = ThingStatusDetail.NONE;
updateStatus(ThingStatus.ONLINE, status);
}
if (!connected) {
pingSuccess();
}
String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
logger.trace("Received response from {}: {}", ip, decryptedResponse);
return decryptedResponse;
}
public Message sendPing(String ip) throws IOException {
for (int i = 0; i < 3; i++) {
logger.debug("Sending Ping {} ({})", Utils.getHex(deviceId), ip);
Message resp = sendData(MiIoBindingConstants.DISCOVER_STRING, ip);
if (resp != null) {
pingSuccess();
return resp;
}
}
pingFail();
return null;
}
private void pingFail() {
logger.debug("Ping {} ({}) failed", Utils.getHex(deviceId), ip);
connected = false;
status = ThingStatusDetail.COMMUNICATION_ERROR;
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
}
private void pingSuccess() {
logger.debug("Ping {} ({}) success", Utils.getHex(deviceId), ip);
if (!connected) {
connected = true;
status = ThingStatusDetail.NONE;
updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
} else {
if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
} else {
status = ThingStatusDetail.NONE;
updateStatus(ThingStatus.ONLINE, status);
}
}
}
private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
for (MiIoMessageListener listener : listeners) {
logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
try {
listener.onStatusUpdated(status, statusDetail);
} catch (Exception e) {
logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
}
}
}
private Message sendData(byte[] sendMsg, String ip) throws IOException {
byte[] response = comms(sendMsg, ip);
if (response.length >= 32) {
Message miIoResponse = new Message(response);
timeStamp = (int) TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().getTime().getTime());
timeDelta = miIoResponse.getTimestampAsInt() - timeStamp;
logger.trace("Message Details:{} ", miIoResponse.toSting());
return miIoResponse;
} else {
logger.trace("Reponse length <32 : {}", response.length);
return null;
}
}
private synchronized byte[] comms(byte[] message, String ip) throws IOException {
InetAddress ipAddress = InetAddress.getByName(ip);
DatagramSocket clientSocket = getSocket();
DatagramPacket receivePacket = new DatagramPacket(new byte[MSG_BUFFER_SIZE], MSG_BUFFER_SIZE);
try {
logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
byte[] sendData = new byte[MSG_BUFFER_SIZE];
sendData = message;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
MiIoBindingConstants.PORT);
clientSocket.send(sendPacket);
sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
clientSocket.receive(receivePacket);
byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
receivePacket.getOffset() + receivePacket.getLength());
return response;
} catch (SocketTimeoutException e) {
logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
needPing = true;
return new byte[0];
}
}
private DatagramSocket getSocket() throws SocketException {
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket();
socket.setSoTimeout(timeout);
return socket;
} else {
return socket;
}
}
public void close() {
try {
if (socket != null) {
socket.close();
}
senderThread.interrupt();
} catch (Exception e) {
logger.debug("Error while closing ", e.getMessage());
}
}
/**
* @return the id
*/
public int getId() {
return id.incrementAndGet();
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id.set(id);
}
/**
* Time delta between device time and server time
*
* @return delta
*/
public int getTimeDelta() {
return timeDelta;
}
public byte[] getDeviceId() {
return deviceId;
}
public void setDeviceId(byte[] deviceId) {
this.deviceId = deviceId;
}
public int getQueueLength() {
return concurrentLinkedQueue.size();
}
}
| epl-1.0 |
dabyv/trinity-f | src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp | 13109 | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.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 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/>.
*/
/* ScriptData
SDName: Boss_Warbringer_Omrogg
SD%Complete: 85
SDComment: Heroic enabled. Spell timing may need additional tweaks
SDCategory: Hellfire Citadel, Shattered Halls
EndScriptData */
/* ContentData
npc_omrogg_heads
boss_warbringer_omrogg
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "shattered_halls.h"
enum Yells
{
YELL_DIE_L = 0,
YELL_DIE_R = 1,
EMOTE_ENRAGE = 2,
};
enum Spells
{
SPELL_BLAST_WAVE = 30600,
SPELL_FEAR = 30584,
SPELL_THUNDERCLAP = 30633,
SPELL_BURNING_MAUL = 30598,
H_SPELL_BURNING_MAUL = 36056,
};
enum Creatures
{
NPC_LEFT_HEAD = 19523,
NPC_RIGHT_HEAD = 19524
};
enum SetData
{
SETDATA_DATA = 1,
SETDATA_YELL = 1
};
enum Events
{
// Omrogg Heads
EVENT_DEATH_YELL = 1
};
struct Yell
{
int32 id;
uint32 creature;
};
static Yell GoCombat[]=
{
{0, NPC_LEFT_HEAD},
{1, NPC_LEFT_HEAD},
{2, NPC_LEFT_HEAD},
};
static Yell GoCombatDelay[]=
{
{0, NPC_RIGHT_HEAD},
{1, NPC_RIGHT_HEAD},
{2, NPC_RIGHT_HEAD},
};
static Yell Threat[]=
{
{3, NPC_LEFT_HEAD},
{3, NPC_RIGHT_HEAD},
{4, NPC_LEFT_HEAD},
{5, NPC_LEFT_HEAD},
};
static Yell ThreatDelay1[]=
{
{4, NPC_RIGHT_HEAD},
{6, NPC_LEFT_HEAD},
{5, NPC_RIGHT_HEAD},
{6, NPC_RIGHT_HEAD},
};
static Yell ThreatDelay2[]=
{
{7, NPC_LEFT_HEAD},
{7, NPC_RIGHT_HEAD},
{8, NPC_LEFT_HEAD},
{9, NPC_LEFT_HEAD},
};
static Yell Killing[]=
{
{10, NPC_LEFT_HEAD},
{8, NPC_RIGHT_HEAD},
};
static Yell KillingDelay[]=
{
{9, NPC_RIGHT_HEAD},
{11, NPC_LEFT_HEAD},
};
// ########################################################
// Warbringer_Omrogg
// ########################################################
class boss_warbringer_omrogg : public CreatureScript
{
public:
boss_warbringer_omrogg() : CreatureScript("boss_warbringer_omrogg") { }
struct boss_warbringer_omroggAI : public BossAI
{
boss_warbringer_omroggAI(Creature* creature) : BossAI(creature, DATA_OMROGG)
{
LeftHeadGUID = 0;
RightHeadGUID = 0;
}
void Reset() OVERRIDE
{
if (Unit* LeftHead = Unit::GetUnit(*me, LeftHeadGUID))
{
LeftHead->setDeathState(JUST_DIED);
LeftHeadGUID = 0;
}
if (Unit* RightHead = Unit::GetUnit(*me, RightHeadGUID))
{
RightHead->setDeathState(JUST_DIED);
RightHeadGUID = 0;
}
AggroYell = false;
ThreatYell = false;
ThreatYell2 = false;
KillingYell = false;
Delay_Timer = 4000;
BlastWave_Timer = 0;
BlastCount = 0;
Fear_Timer = 8000;
BurningMaul_Timer = 25000;
ThunderClap_Timer = 15000;
ResetThreat_Timer = 30000;
instance->SetData(DATA_OMROGG, NOT_STARTED); //End boss can use this later. O'mrogg must be defeated(DONE) or he will come to aid.
}
void DoYellForThreat()
{
Creature* LeftHead = Creature::GetCreature(*me, LeftHeadGUID);
Creature* RightHead = Unit::GetCreature(*me, RightHeadGUID);
if (!LeftHead || !RightHead)
return;
ithreat = rand()%4;
Creature* source = (LeftHead->GetEntry() == Threat[ithreat].creature ? LeftHead : RightHead);
source->AI()->Talk(Threat[ithreat].id);
Delay_Timer = 3500;
ThreatYell = true;
}
void EnterCombat(Unit* /*who*/) OVERRIDE
{
me->SummonCreature(NPC_LEFT_HEAD, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0);
me->SummonCreature(NPC_RIGHT_HEAD, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0);
if (Creature* LeftHead = Creature::GetCreature(*me, LeftHeadGUID))
{
iaggro = rand()%3;
LeftHead->AI()->Talk(GoCombat[iaggro].id);
Delay_Timer = 3500;
AggroYell = true;
}
instance->SetBossState(DATA_OMROGG, IN_PROGRESS);
}
void JustSummoned(Creature* summoned) OVERRIDE
{
if (summoned->GetEntry() == NPC_LEFT_HEAD)
LeftHeadGUID = summoned->GetGUID();
if (summoned->GetEntry() == NPC_RIGHT_HEAD)
RightHeadGUID = summoned->GetGUID();
//summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
//summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
summoned->SetVisible(false);
}
void KilledUnit(Unit* /*victim*/) OVERRIDE
{
Creature* LeftHead = Creature::GetCreature(*me, LeftHeadGUID);
Creature* RightHead = Creature::GetCreature(*me, RightHeadGUID);
if (!LeftHead || !RightHead)
return;
ikilling = rand()%2;
Creature* source = (LeftHead->GetEntry() == Killing[ikilling].creature ? LeftHead : RightHead);
switch (ikilling)
{
case 0:
source->AI()->Talk(Killing[ikilling].id);
Delay_Timer = 3500;
KillingYell = true;
break;
case 1:
source->AI()->Talk(Killing[ikilling].id);
KillingYell = false;
break;
}
}
void JustDied(Unit* /*killer*/) OVERRIDE
{
Creature* LeftHead = Creature::GetCreature(*me, LeftHeadGUID);
Creature* RightHead = Creature::GetCreature(*me, RightHeadGUID);
if (!LeftHead || !RightHead)
return;
LeftHead->AI()->Talk(YELL_DIE_L);
RightHead->AI()->SetData(SETDATA_DATA, SETDATA_YELL);
instance->SetBossState(DATA_OMROGG, DONE);
}
void UpdateAI(uint32 diff) OVERRIDE
{
if (Delay_Timer <= diff)
{
Delay_Timer = 3500;
Creature* LeftHead = Creature::GetCreature(*me, LeftHeadGUID);
Creature* RightHead = Creature::GetCreature(*me, RightHeadGUID);
if (!LeftHead || !RightHead)
return;
if (AggroYell)
{
RightHead->AI()->Talk(GoCombatDelay[iaggro].id);
AggroYell = false;
}
if (ThreatYell2)
{
Creature* source = (LeftHead->GetEntry() == ThreatDelay2[ithreat].creature ? LeftHead : RightHead);
source->AI()->Talk(ThreatDelay2[ithreat].id);
ThreatYell2 = false;
}
if (ThreatYell)
{
Creature* source = (LeftHead->GetEntry() == ThreatDelay1[ithreat].creature ? LeftHead : RightHead);
source->AI()->Talk(ThreatDelay1[ithreat].id);
ThreatYell = false;
ThreatYell2 = true;
}
if (KillingYell)
{
Creature* source = (LeftHead->GetEntry() == KillingDelay[ikilling].creature ? LeftHead : RightHead);
source->AI()->Talk(KillingDelay[ikilling].id);
KillingYell = false;
}
} else Delay_Timer -= diff;
if (!UpdateVictim())
return;
if (BlastCount && BlastWave_Timer <= diff)
{
DoCast(me, SPELL_BLAST_WAVE);
BlastWave_Timer = 5000;
++BlastCount;
if (BlastCount == 3)
BlastCount = 0;
}
else
BlastWave_Timer -= diff;
if (BurningMaul_Timer <= diff)
{
Talk(EMOTE_ENRAGE);
DoCast(me, SPELL_BURNING_MAUL);
BurningMaul_Timer = 40000;
BlastWave_Timer = 16000;
BlastCount = 1;
}
else
BurningMaul_Timer -= diff;
if (ResetThreat_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
{
DoYellForThreat();
DoResetThreat();
me->AddThreat(target, 0.0f);
}
ResetThreat_Timer = 25000+rand()%15000;
}
else
ResetThreat_Timer -= diff;
if (Fear_Timer <= diff)
{
DoCast(me, SPELL_FEAR);
Fear_Timer = 15000+rand()%20000;
}
else
Fear_Timer -= diff;
if (ThunderClap_Timer <= diff)
{
DoCast(me, SPELL_THUNDERCLAP);
ThunderClap_Timer = 15000+rand()%15000;
}
else
ThunderClap_Timer -= diff;
DoMeleeAttackIfReady();
}
private:
uint64 LeftHeadGUID;
uint64 RightHeadGUID;
int iaggro;
int ithreat;
int ikilling;
bool AggroYell;
bool ThreatYell;
bool ThreatYell2;
bool KillingYell;
uint32 Delay_Timer;
uint32 BlastWave_Timer;
uint32 BlastCount;
uint32 Fear_Timer;
uint32 BurningMaul_Timer;
uint32 ThunderClap_Timer;
uint32 ResetThreat_Timer;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetInstanceAI<boss_warbringer_omroggAI>(creature);
}
};
// ########################################################
// Omrogg Heads
// ########################################################
class npc_omrogg_heads : public CreatureScript
{
public:
npc_omrogg_heads() : CreatureScript("npc_omrogg_heads") { }
struct npc_omrogg_headsAI : public ScriptedAI
{
npc_omrogg_headsAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
void Reset() OVERRIDE { }
void EnterCombat(Unit* /*who*/) OVERRIDE { }
void SetData(uint32 data, uint32 value)
{
if (data == SETDATA_DATA && value == SETDATA_YELL)
{
events.ScheduleEvent(EVENT_DEATH_YELL, 4000);
}
}
void UpdateAI(uint32 diff) OVERRIDE
{
events.Update(diff);
if (events.ExecuteEvent() == EVENT_DEATH_YELL)
{
Talk(YELL_DIE_R);
me->setDeathState(JUST_DIED);
}
}
private:
InstanceScript* instance;
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetInstanceAI<npc_omrogg_headsAI>(creature);
}
};
void AddSC_boss_warbringer_omrogg()
{
new boss_warbringer_omrogg();
new npc_omrogg_heads();
}
| gpl-2.0 |
urokuta/cspoker | external/pokersource/src/main/java/org/cspoker/external/pokersource/events/poker/EndRound.java | 1143 | /**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.cspoker.external.pokersource.events.poker;
import org.cspoker.external.pokersource.eventlisteners.poker.PokerEventListener;
public class EndRound extends Id{
public String getType() {
return getStaticType();
}
public static String getStaticType() {
return "PacketPokerEndRound";
}
@Override
public void signal(PokerEventListener listener) {
listener.onEndRound(this);
}
}
| gpl-2.0 |
itmoss/Libjingle | talk/app/webrtc/mediastream.cc | 2738 | /*
* libjingle
* Copyright 2011, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "talk/app/webrtc/mediastream.h"
#include "talk/base/logging.h"
namespace webrtc {
talk_base::scoped_refptr<MediaStream> MediaStream::Create(
const std::string& label) {
talk_base::RefCountedObject<MediaStream>* stream =
new talk_base::RefCountedObject<MediaStream>(label);
return stream;
}
MediaStream::MediaStream(const std::string& label)
: label_(label),
ready_state_(MediaStreamInterface::kInitializing),
audio_track_list_(
new talk_base::RefCountedObject<
MediaStreamTrackList<AudioTrackInterface> >()),
video_track_list_(
new talk_base::RefCountedObject<
MediaStreamTrackList<VideoTrackInterface> >()) {
}
void MediaStream::set_ready_state(
MediaStreamInterface::ReadyState new_state) {
if (ready_state_ != new_state) {
ready_state_ = new_state;
Notifier<LocalMediaStreamInterface>::FireOnChanged();
}
}
bool MediaStream::AddTrack(AudioTrackInterface* track) {
if (ready_state() != kInitializing)
return false;
audio_track_list_->AddTrack(track);
return true;
}
bool MediaStream::AddTrack(VideoTrackInterface* track) {
if (ready_state() != kInitializing)
return false;
video_track_list_->AddTrack(track);
return true;
}
} // namespace webrtc
| gpl-2.0 |
ravi-cnetric/cnetric_cm | components/com_jshopping/templates/default/cart/wishlist.php | 6527 | <?php
/**
* @version 4.12.2 13.08.2013
* @author MAXXmarketing GmbH
* @package Jshopping
* @copyright Copyright (C) 2010 webdesigner-profi.de. All rights reserved.
* @license GNU/GPL
*/
defined('_JEXEC') or die();
?>
<div class="jshop" id="comjshop">
<table class = "jshop cart cartwishlist" id="comjshop">
<tr>
<th class="jshop_img_description_center" width = "20%">
<?php print _JSHOP_IMAGE?>
</th>
<th class="product_name">
<?php print _JSHOP_ITEM?>
</th>
<th class="single_price" width = "15%">
<?php print _JSHOP_SINGLEPRICE ?>
</th>
<th class="quantity" width = "15%">
<?php print _JSHOP_NUMBER ?>
</th>
<th class="total_price" width = "15%">
<?php print _JSHOP_PRICE_TOTAL ?>
</th>
<th class="remove_to_cart" width = "10%">
<?php print _JSHOP_REMOVE_TO_CART ?>
</th>
<th class="remove" width = "10%">
<?php print _JSHOP_REMOVE ?>
</th>
</tr>
<?php
$i=1;
foreach($this->products as $key_id=>$prod){
?>
<tr class = "jshop_prod_cart <?php if ($i%2==0) print "even"; else print "odd"?>">
<td class = "jshop_img_description_center">
<div class="mobile-cart">
<?php print _JSHOP_IMAGE; ?>
</div>
<div class="data">
<a href = "<?php print $prod['href']; ?>">
<img src = "<?php print $this->image_product_path ?>/<?php if ($prod['thumb_image']) print $prod['thumb_image']; else print $this->no_image; ?>" alt = "<?php print htmlspecialchars($prod['product_name']);?>" class = "jshop_img" />
</a>
</div>
</td>
<td class="product_name">
<div class="mobile-cart">
<?php print _JSHOP_ITEM; ?>
</div>
<div class="data">
<a href="<?php print $prod['href']?>">
<?php print $prod['product_name']?>
</a>
<?php if ($this->config->show_product_code_in_cart){?>
<span class="jshop_code_prod">(<?php print $prod['ean']?>)</span>
<?php }?>
<?php print $prod['_ext_product_name'] ?>
<?php if ($prod['manufacturer']!=''){?>
<div class="manufacturer">
<?php print _JSHOP_MANUFACTURER?>:
<span><?php print $prod['manufacturer']?></span>
</div>
<?php }?>
<?php print sprintAtributeInCart($prod['attributes_value']);?>
<?php print sprintFreeAtributeInCart($prod['free_attributes_value']);?>
<?php print sprintFreeExtraFiledsInCart($prod['extra_fields']);?>
<?php print $prod['_ext_attribute_html']?>
</div>
</td>
<td class="single_price">
<div class="mobile-cart">
<?php print _JSHOP_SINGLEPRICE; ?>
</div>
<div class="data">
<?php print formatprice($prod['price'])?>
<?php print $prod['_ext_price_html']?>
<?php if ($this->config->show_tax_product_in_cart && $prod['tax']>0){?>
<span class="taxinfo"><?php print productTaxInfo($prod['tax']);?></span>
<?php }?>
<?php if ($this->config->cart_basic_price_show && $prod['basicprice']>0){?>
<div class="basic_price">
<?php print _JSHOP_BASIC_PRICE?>: <span><?php print sprintBasicPrice($prod);?></span>
</div>
<?php }?>
</div>
</td>
<td class="quantity">
<div class="mobile-cart">
<?php print _JSHOP_NUMBER; ?>
</div>
<div class="data">
<?php print $prod['quantity']?><?php print $prod['_qty_unit'];?>
</div>
</td>
<td class="total_price">
<div class="mobile-cart">
<?php print _JSHOP_PRICE_TOTAL; ?>
</div>
<div class="data">
<?php print formatprice($prod['price']*$prod['quantity']);?>
<?php print $prod['_ext_price_total_html']?>
<?php if ($this->config->show_tax_product_in_cart && $prod['tax']>0){?>
<span class="taxinfo"><?php print productTaxInfo($prod['tax']);?></span>
<?php }?>
</div>
</td>
<td class="remove_to_cart">
<div class="mobile-cart">
<?php print _JSHOP_REMOVE_TO_CART; ?>
</div>
<div class="data">
<a class="button-img" href = "<?php print $prod['remove_to_cart'] ?>" >
<img src = "<?php print $this->image_path ?>images/reload.png" alt = "<?php print _JSHOP_REMOVE_TO_CART?>" title = "<?php print _JSHOP_REMOVE_TO_CART?>" />
</a>
<a class="btn btn-primary" href = "<?php print $prod['remove_to_cart'] ?>" >
<?php print _JSHOP_REMOVE_TO_CART?>
</a>
</div>
</td>
<td class="remove">
<div class="mobile-cart">
<?php print _JSHOP_REMOVE; ?>
</div>
<div class="data">
<a class="button-img" href="<?php print $prod['href_delete']?>" onclick="return confirm('<?php print _JSHOP_CONFIRM_REMOVE?>')">
<img src = "<?php print $this->image_path ?>images/remove.png" alt = "<?php print _JSHOP_DELETE?>" title = "<?php print _JSHOP_DELETE?>" />
</a>
</div>
</td>
</tr>
<?php
$i++;
}
?>
</table>
<?php print $this->_tmp_html_before_buttons?>
<div class = "jshop wishlish_buttons">
<div id = "checkout">
<div class = "pull-left td_1">
<a href = "<?php print $this->href_shop ?>" class="btn btn-arrow-left">
<?php print _JSHOP_BACK_TO_SHOP ?>
</a>
</div>
<div class = "pull-right td_2">
<a href = "<?php print $this->href_checkout ?>" class="btn btn-arrow-right">
<?php print _JSHOP_GO_TO_CART ?>
</a>
</div>
<div class = "clearfix"></div>
</div>
</div>
<?php print $this->_tmp_html_after_buttons?>
</div> | gpl-2.0 |
wilminator/dokuwiki | lib/plugins/authpgsql/lang/de-informal/settings.php | 2987 | <?php
/**
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
*
* @author Matthias Schulte <dokuwiki@lupo49.de>
* @author Volker Bödker <volker@boedker.de>
*/
$lang['server'] = 'PostgreSQL-Server';
$lang['port'] = 'Port des PostgreSQL-Servers.';
$lang['user'] = 'Benutzername für den Zugriff auf den PostgreSQL-Server.';
$lang['password'] = 'Passwort des angegebenen Benutzers.';
$lang['database'] = 'Zu verwendende Datenbank.';
$lang['debug'] = 'Debug-Informationen anzeigen?';
$lang['forwardClearPass'] = 'Passwort der DokuWiki-Benutzer im Klartext an die Datenbank übergeben? (Im Normalfall wird die passcrypt-Option angewendet.)';
$lang['checkPass'] = 'SQL-Kommando zum Überprüfen von Passwörtern.';
$lang['getUserInfo'] = 'SQL-Kommando um Benutzerinformationen auszulesen.';
$lang['getGroups'] = 'SQL-Kommando um Gruppen eines Benutzers auszulesen.';
$lang['getUsers'] = 'SQL-Kommando um alle Benutzer auszulesen.';
$lang['FilterLogin'] = 'SQL-Bedingung um Benutzer anhand ihres Anmeldenamens zu filtern.';
$lang['FilterName'] = 'SQL-Bedingung um Benutzer anhand ihres Namens zu filtern.';
$lang['FilterEmail'] = 'SQL-Bedingung um Benutzer anhand ihrer E-Mail-Adresse zu filtern.';
$lang['FilterGroup'] = 'SQL-Bedingung um Benutzer anhand ihrer Gruppenzugehörigkeit zu filtern.';
$lang['SortOrder'] = 'SQL-Bedingung um anhand der die Benutzerliste sortiert wird.';
$lang['addUser'] = 'SQL-Kommando um einen neuen Benutzer anzulegen.';
$lang['addGroup'] = 'SQL-Kommando um eine neue Gruppe anzulegen.';
$lang['addUserGroup'] = 'SQL-Kommando um einen Benutzer zu einer Gruppe hinzuzufügen.';
$lang['delGroup'] = 'SQL-Kommando um eine Gruppe zu löschen.';
$lang['getUserID'] = 'SQL-Kommando um den Primärschlüssel des Benutzers auszulesen.';
$lang['delUser'] = 'SQL-Kommando um einen Benutzer zu löschen.';
$lang['delUserRefs'] = 'SQL-Kommando um einen Benutzer aus allen Gruppen zu entfernen.';
$lang['updateUser'] = 'SQL-Kommando um das Profil eines Benutzers zu aktualisieren.';
$lang['UpdateLogin'] = 'SQL-Bedingung um den Anmeldenamen eines Benutzers zu ändern.';
$lang['UpdatePass'] = 'SQL-Bedingung um das Passwort eines Benutzers zu ändern.';
$lang['UpdateEmail'] = 'SQL-Bedingung um die E-Mail-Adresse eines Benutzers zu ändern.';
$lang['UpdateName'] = 'SQL-Bedingung um den Namen eines Benutzers zu ändern.';
$lang['UpdateTarget'] = 'SQL-Bedingung zur eindeutigen Identifikation des Benutzers.';
$lang['delUserGroup'] = 'SQL-Kommando um einen Benutzer aus einer angegeben Gruppe zu entfernen.';
$lang['getGroupID'] = 'SQL-Kommando um den Primärschlüssel einer Gruppe auszulesen.';
| gpl-2.0 |
erpcya/adempierePOS | com.kkalice.adempiere.migrate/src/com/kkalice/adempiere/migrate/DBEngine_Postgresql.java | 123199 | /*
* Name: DBEngineInterface_Postgresql.java
* Description: PostgreSQL compatibility class
* Created: Nov 29, 2009
* Vendor: K.K. Alice
* Author: Stefan Christians
*
* FileTarget: ~/development/sandbox/migrate/src/com/kkalice/adempiere/migrate/DBEngineInterface_Postgresql.java
* FileOwner: spc.dvp
* FilePerms: 0644
*
*/
/**
* This file is part of Adempiere ERP Bazaar
* http://www.adempiere.org
*
* Copyright (C) Stefan Christians
* Copyright (C) Contributors
*
* 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.
*
* Contributors:
* - Stefan Christians
*
* Sponsors:
* - K.K. Alice
*
*/
package com.kkalice.adempiere.migrate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* PostgreSQL compatibility class
* @author Stefan Christians
*/
public class DBEngine_Postgresql implements DBEngineInterface {
// database identification
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getVendorNames()
*/
public List<String> getVendorNames () {
return Arrays.asList("PostgreSQL", "Postgres", "pgsql", "pg");
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getSystemCatalogs()
*/
public List<String> getSystemCatalogs() {
return null;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getSystemSchemas()
*/
public List<String> getSystemSchemas() {
return Arrays.asList("information_schema", "pg_catalog", "pg_toast_temp_1");
}
// database access
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDriver(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine)
*/
public String getDBDriver () {
return "org.postgresql.Driver";
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBPort(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String)
*/
public String getDBPort () {
return "5432";
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBName(java.lang.String)
*/
public String getDBName(String vendorName) {
// there is usually no default name for postgres
return null;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#isSourceAndTargetSameDBName()
*/
public boolean isSourceAndTargetSameDBName() {
// in postgres, reference and target are in separate databases
return false;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBUrl(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String)
*/
public String getDBUrl (String host, String port, String name) {
StringBuffer url = new StringBuffer();
if (host==null || host.length()==0 || host.equalsIgnoreCase("localhost"))
host="";
if (port==null || port.length()==0 || port.equalsIgnoreCase("5432"))
port="";
url.append("jdbc:postgresql:");
if (host.length()>0) {
url.append("//").append(host);
if (port.length()>0)
url.append(":").append(port);
url.append("/");
}
if (name!=null)
url.append(name);
return url.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBDefaultSystemUser()
*/
public String getDBSystemUser() {
return "postgres";
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBDefaultSystemPassword()
*/
public String getDBSystemPassword() {
return "postgres";
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBSchemaOrUser(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String getDBSchemaOrUser (String schemaName, String user) {
// in postgresql, schema can be any name
return schemaName;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getSystemOrNormalUser(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String getDBSystemOrNormalUser (String normalUser, String systemUser) {
// in postgresql, normal user has sufficient control for privileged operations
return normalUser;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getSystemOrNormalUser(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String getDBSystemOrNormalPassword (String normalPasswd, String systemPasswd) {
// in postgresql, normal user has sufficient control for privileged operations
return normalPasswd;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDBMaxIdentifierLength()
*/
public int getDBMaxIdentifierLength() {
// maximum length of identifiers is 63 characters
return 63;
}
// data type translation
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#disambiguateDataType(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String)
*/
public String disambiguateDataType (String dataType) {
// no disambigutaion necessary in postgresql
return dataType;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getDataType(int, int, int)
*/
public String getDataType (int dataTypeID, int size, int scale) {
String result = null;
switch (dataTypeID) {
case DBEngine.SMALLINT:
case DBEngine.INT2:
result = "SMALLINT";
break;
case DBEngine.INTEGER:
case DBEngine.INT4:
case DBEngine.INT:
case DBEngine.PLS_INTEGER:
case DBEngine.BINARY_INTEGER:
case DBEngine.NATURAL:
case DBEngine.POSITIVE:
case DBEngine.SIMPLE_INTEGER:
case DBEngine.NATURALN:
case DBEngine.POSITIVEN:
case DBEngine.SIGNTYPE:
result = "INTEGER";
break;
case DBEngine.BIGINT:
case DBEngine.INT8:
result = "BIGINT";
break;
case DBEngine.NUMERIC:
case DBEngine.DECIMAL:
case DBEngine.DEC:
case DBEngine.NUMBER:
result = "NUMERIC";
if (size!=0) {
result = new StringBuffer("NUMERIC (").append(size).append(")").toString();
if (scale != -1 && scale !=0)
result = new StringBuffer("NUMERIC (").append(size).append(",").append(scale).append(")").toString();
if (scale == -1)
result = "NUMERIC";
}
break;
case DBEngine.REAL:
case DBEngine.FLOAT4:
case DBEngine.BINARY_FLOAT:
result = "FLOAT4";
break;
case DBEngine.DOUBLE_PRECISION:
case DBEngine.FLOAT8:
case DBEngine.BINARY_DOUBLE:
case DBEngine.FLOAT:
result = "FLOAT8";
break;
case DBEngine.SERIAL:
case DBEngine.SERIAL4:
result = "SERIAL";
break;
case DBEngine.BIGSERIAL:
case DBEngine.SERIAL8:
result = "BIGSERIAL";
break;
case DBEngine.MONEY:
result = "MONEY";
break;
case DBEngine.CHAR:
case DBEngine.CHARACTER:
case DBEngine.NCHAR:
if (size!=0)
result = new StringBuffer("CHAR (").append(size).append(")").toString();
else
result = "CHAR";
break;
case DBEngine.NAME:
result = "NAME";
break;
case DBEngine.VARCHAR:
case DBEngine.CHARACTER_VARYING:
case DBEngine.CHAR_VARYING:
case DBEngine.VARCHAR2:
case DBEngine.NVARCHAR:
case DBEngine.NCHAR_VARYING:
case DBEngine.NATIONAL_CHAR_VARYING:
case DBEngine.NATIONAL_CHARACTER_VARYING:
case DBEngine.NVARCHAR2:
case DBEngine.STRING:
if (size!=0)
result = new StringBuffer("VARCHAR (").append(size).append(")").toString();
else
result = "VARCHAR";
break;
case DBEngine.LONG:
case DBEngine.TEXT:
case DBEngine.CLOB:
case DBEngine.NCLOB:
result = "TEXT";
break;
case DBEngine.MLSLABEL:
case DBEngine.RAW:
case DBEngine.LONG_RAW:
case DBEngine.BYTEA:
case DBEngine.BLOB:
case DBEngine.BFILE:
result = "BYTEA";
break;
case DBEngine.TIME:
case DBEngine.TIME_WITHOUT_TIME_ZONE:
result = "TIME";
break;
case DBEngine.TIMETZ:
case DBEngine.TIME_WITH_TIME_ZONE:
result = "TIMETZ";
break;
case DBEngine.DATE:
case DBEngine.TIMESTAMP:
case DBEngine.TIMESTAMP_WITHOUT_TIME_ZONE:
result = "TIMESTAMP";
break;
case DBEngine.TIMESTAMPTZ:
case DBEngine.TIMESTAMP_WITH_TIME_ZONE:
case DBEngine.TIMESTAMP_WITH_LOCAL_TIME_ZONE:
result = "TIMESTAMPTZ";
break;
case DBEngine.INTERVAL:
result = "INTERVAL";
break;
case DBEngine.BOOLEAN:
case DBEngine.BOOL:
result = "BOOLEAN";
break;
case DBEngine.ENUM:
result = "ENUM";
break;
case DBEngine.POINT:
result = "POINT";
break;
case DBEngine.LINE:
result = "LINE";
break;
case DBEngine.LSEG:
result = "LSEG";
break;
case DBEngine.BOX:
result = "BOX";
break;
case DBEngine.PATH:
result = "PATH";
break;
case DBEngine.POLYGON:
result = "POLYGON";
break;
case DBEngine.CIRCLE:
result = "CIRCLE";
break;
case DBEngine.CIDR:
result = "CIDR";
break;
case DBEngine.INET:
result = "INET";
break;
case DBEngine.MACADDR:
result = "MACADDR";
break;
case DBEngine.BIT:
if (size!=0)
result = new StringBuffer("BIT (").append(size).append(")").toString();
else
result = "BIT";
break;
case DBEngine.VARBIT:
case DBEngine.BIT_VARYING:
if (size!=0)
result = new StringBuffer("VARBIT (").append(size).append(")").toString();
else
result = "VARBIT";
break;
case DBEngine.TSVECTOR:
result = "TSVECTOR";
break;
case DBEngine.TSQUERY:
result = "TSQUERY";
break;
case DBEngine.UUID:
result = "UUID";
break;
case DBEngine.XML:
result = "XML";
break;
case DBEngine.OID:
result = "OID";
break;
case DBEngine.REGPROC:
result = "REGPROC";
break;
case DBEngine.REGPROCEDURE:
result = "REGPROCEDURE";
break;
case DBEngine.REGOPER:
result = "REGOPER";
break;
case DBEngine.REGOPERATOR:
result = "REGOPERATOR";
break;
case DBEngine.REGCLASS:
result = "REGCLASS";
break;
case DBEngine.REGTYPE:
result = "REGTYPE";
break;
case DBEngine.REGCONFIG:
result = "REGCONFIG";
break;
case DBEngine.REGDICTIONARY:
result = "REGDICTIONARY";
break;
case DBEngine.ANY:
case DBEngine.SYS_ANYDATA:
result = "ANY";
break;
case DBEngine.ANYARRAY:
result = "ANYARRAY";
break;
case DBEngine.ANYELEMENT:
case DBEngine.SYS_ANYTYPE:
result = "ANYELEMENT";
break;
case DBEngine.ANYENUM:
case DBEngine.SYS_ANYDATASET:
result = "ANYENUM";
break;
case DBEngine.ANYNONARRAY:
result = "ANYNONARRAY";
break;
case DBEngine.CSTRING:
result = "CSTRING";
break;
case DBEngine.INTERNAL:
result = "INTERNAL";
break;
case DBEngine.LANGUAGE_HANDLER:
result = "LANGUAGE_HANDLER";
break;
case DBEngine.RECORD:
result = "RECORD";
break;
case DBEngine.TRIGGER:
result = "TRIGGER";
break;
case DBEngine.VOID:
result = "VOID";
break;
case DBEngine.OPAQUE:
result = "OPAQUE";
break;
case DBEngine.TXID_SNAPSHOT:
result = "TXID_SNAPSHOT";
break;
default:
result = null;
break;
}
return result;
}
// expresion translation
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateExpression(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String translateExpression (String sourceVendorName, String expression) {
String result = expression;
if (sourceVendorName.contains("ORACLE")) {
// translate expressions from oracle
// replace SYSDATE with now()
if (expression.equalsIgnoreCase("SYSDATE"))
result = "now()";
}
return result;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateUnnamedParameter(int)
*/
public String translateUnnamedParameter(int paramNum) {
// postgresql supports unnamed parameters
return "";
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#normalizeColumnName(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String)
*/
public String normalizeColumnName (String columnName) {
return new StringBuffer("\"").append(columnName.toLowerCase()).append("\"").toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#normalizeColumnValue(int)
*/
public String normalizeColumnValue(int dataTypeID) {
// use zero
String result = "0";
// or empty string for char types
if (dataTypeID >= DBEngine.CHARTYPE_START && dataTypeID <= DBEngine.CHARTYPE_END)
result = "''";
// or epoch for dates
else if (dataTypeID >= DBEngine.DATETYPE_START && dataTypeID <= DBEngine.DATETYPE_END)
result = "'epoch'";
// or all zero for times
else if (dataTypeID >= DBEngine.TIMETYPE_START && dataTypeID <= DBEngine.TIMETYPE_END)
result = "'allballs'";
// or epoch for timestamps
else if (dataTypeID >= DBEngine.TIMESTAMPTYPE_START && dataTypeID <= DBEngine.TIMESTAMPTYPE_END)
result = "'epoch'";
return result;
}
// function translation
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateFunctionLanguage(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String translateFunctionLanguage (String sourceVendorName, String functionLanguage) {
String result = functionLanguage;
if (sourceVendorName.contains("ORACLE")) {
// translate function languages from oracle
// replace PL/SQL with plpgsql
if (functionLanguage.equalsIgnoreCase("PL/SQL"))
result = "plpgsql";
// replace Java with PL/Java
else if (functionLanguage.equalsIgnoreCase("Java"))
result = "java";
}
return result;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateFunctionType(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String)
*/
public String translateFunctionType (String sourceVendorName, String functionType, String functionReturnType) {
// in postgres, all functions are of type FUNCTION
return "FUNCTION";
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateFunctionReturnType(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String translateFunctionReturnType (DBEngine dbEngine, String sourceVendorName, String functionReturnType) {
String result = functionReturnType;
if (sourceVendorName.contains("ORACLE")) {
// translate funtion return types from oracle
// replace null with void
if (functionReturnType==null || functionReturnType.length()==0 || functionReturnType.equalsIgnoreCase("null") || functionReturnType.equalsIgnoreCase("void"))
result = "void";
else
result = dbEngine.translateDataType(sourceVendorName, getVendorNames().get(0), functionReturnType, 0, 0);
}
return result;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateFunctionBodyFull(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String translateFunctionBodyFull (DBEngine dbEngine, String sourceVendorName, String sourceSchemaName, String functionLanguage, String functionReturnType, String functionBodyText) {
if (sourceVendorName.contains("POSTGRES")) {
// translate function from postgresql to postgresql
// remove schema qualifiers
functionBodyText = functionBodyText.replaceAll(new StringBuffer("(?i)").append(sourceSchemaName).append("\\.").toString(), "");
} else if (sourceVendorName.contains("ORACLE")) {
// translate function from oracle to postgresql
// TODO full translation of functions is not implemented yet.
// call stub translation instead
functionBodyText = translateFunctionBodyStub(dbEngine, sourceVendorName, functionLanguage, functionReturnType, functionBodyText);
}
return functionBodyText;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateFunctionBodyStub(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String translateFunctionBodyStub(DBEngine dbEngine, String sourceVendorName, String functionLanguage, String functionReturnType, String functionBodyText) {
// comment out the text
if (functionBodyText!=null && functionBodyText.length()>0)
functionBodyText = functionBodyText.replaceAll("(?m)^", "-- migrate: ");
// need return type for returning correct return value
int dataType=0;
if (functionReturnType!=null
&& functionReturnType.length()>0
&& ! functionReturnType.equalsIgnoreCase("null")
&& ! functionReturnType.equalsIgnoreCase("void"))
dataType = dbEngine.getDataTypeID(sourceVendorName, functionReturnType);
// default: return nothing
String retVal = " RETURN;";
StringBuffer stub = new StringBuffer();
if (dataType > 0) {
// return empty string for char types
if (dataType >= DBEngine.CHARTYPE_START && dataType <= DBEngine.CHARTYPE_END)
retVal = " RETURN '';";
// return epoch for dates
else if (dataType >= DBEngine.DATETYPE_START && dataType <= DBEngine.DATETYPE_END)
retVal = " RETURN '1970-01-01';";
// return all zero for times
else if (dataType >= DBEngine.TIMETYPE_START && dataType <= DBEngine.TIMETYPE_END)
retVal = " RETURN '00:00:00';";
// return epoch for timestamps
else if (dataType >= DBEngine.TIMESTAMPTYPE_START && dataType <= DBEngine.TIMESTAMPTYPE_END)
retVal = " RETURN '1970-01-01 00:00:00';";
// return NEW recordset for triggers
else if (dataType == DBEngine.TRIGGER)
retVal = " RETURN NEW;";
// otherwise return number zero
else
retVal = " RETURN 0;";
}
stub.append("-- Migration Stub Start --").append(System.getProperty("line.separator"))
.append("BEGIN ").append(System.getProperty("line.separator"))
.append(retVal).append(System.getProperty("line.separator"))
.append("END;").append(System.getProperty("line.separator"))
.append("-- Migration Stub End --").append(System.getProperty("line.separator"))
;
functionBodyText = new StringBuffer(functionBodyText).append(stub).toString();
return functionBodyText;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateOperator(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String translateOperator (String sourceVendorName, String operatorName) {
String result = operatorName;
if (sourceVendorName.contains("ORACLE")) {
// translate operator names from oracle
result = result.replaceAll("(?i)PLUS", "+");
result = result.replaceAll("(?i)ADD", "+");
result = result.replaceAll("(?i)MINUS", "-");
result = result.replaceAll("(?i)HYPHEN", "-");
result = result.replaceAll("(?i)SUBTRACT", "-");
result = result.replaceAll("(?i)ASTERISK", "*");
result = result.replaceAll("(?i)START", "*");
result = result.replaceAll("(?i)TIMES", "*");
result = result.replaceAll("(?i)MULTIPLIEDBY", "*");
result = result.replaceAll("(?i)MULTIPLIED", "*");
result = result.replaceAll("(?i)SLASH", "/");
result = result.replaceAll("(?i)DIVIDEDBY", "/");
result = result.replaceAll("(?i)DIVIDED", "/");
result = result.replaceAll("(?i)LESSTHAN", "<");
result = result.replaceAll("(?i)LESS", "<");
result = result.replaceAll("(?i)SMALLERTHAN", "<");
result = result.replaceAll("(?i)SMALLER", "<");
result = result.replaceAll("(?i)GREATERTHAN", ">");
result = result.replaceAll("(?i)GREATER", ">");
result = result.replaceAll("(?i)BIGGERTHAN", ">");
result = result.replaceAll("(?i)BIGGER", ">");
result = result.replaceAll("(?i)LARGERTHAN", ">");
result = result.replaceAll("(?i)LARGER", ">");
result = result.replaceAll("(?i)MORETHAN", ">");
result = result.replaceAll("(?i)MORE", ">");
result = result.replaceAll("(?i)EQUAL", "=");
result = result.replaceAll("(?i)ABOUT", "~");
result = result.replaceAll("(?i)LIKE", "~");
result = result.replaceAll("(?i)TILDE", "~");
result = result.replaceAll("(?i)EXCLAMATION", "!");
result = result.replaceAll("(?i)NOT", "!");
result = result.replaceAll("(?i)AT", "@");
result = result.replaceAll("(?i)POUND", "#");
result = result.replaceAll("(?i)PERCENT", "%");
result = result.replaceAll("(?i)MOD", "%");
result = result.replaceAll("(?i)XOR", "^");
result = result.replaceAll("(?i)AND", "&");
result = result.replaceAll("(?i)AMPERSAND", "&");
result = result.replaceAll("(?i)OR", "|");
result = result.replaceAll("(?i)BACKTICK", "`");
result = result.replaceAll("(?i)QUESTION", "?");
}
return result;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#isTriggerContainsInlineCode(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine)
*/
public boolean isTriggerContainsInlineCode () {
// postgresql triggers can not contain inline code
return false;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateTriggerType(java.lang.String, java.lang.String)
*/
public String translateTriggerType(String sourceVendorName, String triggerType) {
if (sourceVendorName.contains("ORACLE")) {
// translate trigger types from oracle to postgresql
triggerType = triggerType.replaceAll(" EVENT", "");
triggerType = triggerType.replaceAll(" STATEMENT", "");
triggerType = triggerType.replaceAll(" EACH ROW", "");
}
return triggerType;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateTriggerActionOrientation(java.lang.String, java.lang.String)
*/
public String translateTriggerActionOrientation(String sourceVendorName, String actionOrientation) {
if (actionOrientation.contains("ROW"))
actionOrientation = "FOR EACH ROW";
else
actionOrientation = "FOR EACH STATEMENT";
return actionOrientation;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateTriggerFunction(java.lang.String, java.lang.String)
*/
public String translateTriggerFunction(String sourceVendorName, String triggerFunction) {
if (sourceVendorName.contains("POSTGRES")) {
// translate trigger function from postgresql to postgresql
triggerFunction = triggerFunction.replaceAll("^EXECUTE PROCEDURE ", "");
}
return triggerFunction;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateTriggerCode(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String translateTriggerCode(String sourceVendorName, String actionType, String triggerName, String triggerFunction) {
StringBuffer codeExpr = new StringBuffer();
if (sourceVendorName.contains("POSTGRES")) {
// translate trigger code from postgresql to postgresql
codeExpr.append("EXECUTE PROCEDURE ").append(triggerFunction);
} else if (sourceVendorName.contains("ORACLE")) {
// translate trigger code from oracle to postgresql
if (actionType.equalsIgnoreCase("CALL"))
codeExpr.append("EXECUTE PROCEDURE ").append(triggerFunction);
else
codeExpr.append("EXECUTE PROCEDURE ").append(triggerName.toLowerCase()).append("_trigger()");
}
return codeExpr.toString();
}
// view translation
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateViewDefinitionFull(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String translateViewDefinitionFull(DBEngine dbEngine, String sourceVendorName, String sourceSchemaName, String targetSchemaName, String viewDefinition) {
if (sourceVendorName.contains("POSTGRES")) {
// translate view from postgresql to postgresql
// remove schema qualifiers
viewDefinition = viewDefinition.replaceAll(new StringBuffer("(?i)").append(sourceSchemaName).append("\\.").toString(), "");
} else if (sourceVendorName.contains("ORACLE")) {
// translate view from oracle to postgresql
// sorry, but we need to remove comments to keep parsing manageable
viewDefinition = viewDefinition.replaceAll("(?m)--.*$", "");
// ROWNUM iterator gets replaced with generate_series
viewDefinition = viewDefinition.replaceAll("\\(SELECT ROWNUM (AS )?(\\w+) FROM ALL_OBJECTS WHERE ROWNUM\\s?<=\\s?(\\d+) ORDER BY ROWNUM\\)",
"(SELECT s.a AS $2 FROM generate_series(1,$3) AS s(a)) AS temp$2");
// 'WHERE ROWNUM<=X' becomes 'LIMIT X'
viewDefinition = viewDefinition.replaceAll("(?i)WHERE ROWNUM\\s?<?=\\s?(\\d+)", "LIMIT $1");
viewDefinition = viewDefinition.replaceAll("(?i)AND ROWNUM\\s?<?=\\s?(\\d+)", "LIMIT $1");
// sysdate becomes now()
viewDefinition = viewDefinition.replaceAll("(?i)sysdate", "now()");
// decode function becomes case structure
// (some decodes are nested, so we need a while loop!)
if (viewDefinition!=null) {
while(viewDefinition.toLowerCase().contains("decode")) {
// everything before the decode clause
String prefix = viewDefinition.substring(0, viewDefinition.toLowerCase().indexOf("decode"));
// first opening braces after keyword "decode"
int beginIndex = viewDefinition.indexOf("(", viewDefinition.toLowerCase().indexOf("decode"));
// find closing braces
int endIndex = viewDefinition.length();
Stack<String> stack = new Stack<String>();
for (int i= beginIndex; i < endIndex; i++) {
char charValue = viewDefinition.charAt(i);
switch (charValue) {
case '(':
stack.push(Character.toString(charValue));
break;
case ')':
stack.pop();
}
if (stack.isEmpty())
endIndex = i;
}
// the decode clause
String decode = viewDefinition.substring(beginIndex, endIndex);
// everything after the decode clause
if (endIndex >= viewDefinition.length())
endIndex = viewDefinition.length()-2;
String suffix = viewDefinition.substring(endIndex+1);
// rewrite the decode clause as case structure
// remove opening and closing braces
decode = decode.substring(1, decode.length());
String testValue = "";
ArrayList<String> whenCondition = new ArrayList<String>();
ArrayList<String> thenResult = new ArrayList<String>();
String defaultResult = "ELSE NULL";
int lastIndex=0;
stack = new Stack<String>();
// look for commata outside single quotes, double quotes, braces, curly braces, and square braces
for (int i= 0; i < decode.length(); i++) {
char charValue = decode.charAt(i);
String stringValue = Character.toString(charValue);
String lastOpener = "";
if (! stack.isEmpty())
lastOpener = stack.peek();
switch (charValue) {
case '\'':
if (lastOpener.equals(stringValue))
stack.pop();
else
stack.push(stringValue);
break;
case '"':
if (lastOpener.equals(stringValue))
stack.pop();
else
stack.push(stringValue);
break;
case '(':
case '{':
case '[':
stack.push(stringValue);
break;
case ')':
case '}':
case ']':
stack.pop();
break;
case ',':
// if stack is empty, we are outside of any quotes
if (stack.isEmpty()) {
String subClause = decode.substring(lastIndex, i);
lastIndex = i+1;
// if no test value has been defined yet, this is the test value
if (testValue.length()==0) {
testValue = subClause;
} else {
// otherwise it is a condition or a result
int whenSize = whenCondition.size();
int thenSize = thenResult.size();
// if we have as many conditions as results, this is a new condition
if (whenSize == thenSize) {
whenCondition.add(subClause);
} else {
// otherwise this is a new result
thenResult.add(subClause);
}
}
}
}
}
// one subclause (the last one, not terminating by comma) is still left
// if we have same number of conditions and results, it is the default clause,
// otherwise it is the last result
if (whenCondition.size() == thenResult.size()) {
defaultResult = new StringBuffer("ELSE ").append(decode.substring(lastIndex)).toString();
} else {
thenResult.add(decode.substring(lastIndex));
}
// put together the case structure
// (enclosed in braces for easier human reading)
StringBuffer sb = new StringBuffer();
sb.append("(CASE ").append(testValue).append(" ");
for (int i=0; i<whenCondition.size(); i++) {
sb.append("WHEN ").append(whenCondition.get(i)).append(" THEN ").append(thenResult.get(i)).append(" ");
}
sb.append(defaultResult).append(" END)");
decode = sb.toString();
// remove double spaces
decode = decode.replaceAll("\\s+", " ");
// put everything back together
viewDefinition = new StringBuffer(prefix).append(decode).append(suffix).toString();
}
}
// remove doublequotes from field names
if (viewDefinition!=null) {
Pattern pattern = Pattern.compile("(.*SELECT\\s)((\"[^,\\s]*?\"[,\\s]+)+)(FROM.*)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher matcher = pattern.matcher(viewDefinition);
if (matcher.find()) {
String prefix = matcher.group(1);
String suffix = matcher.group(4);
String phrase = matcher.group(2);
phrase = phrase.replaceAll("(?m)\"", "");
viewDefinition = new StringBuffer(prefix).append(phrase).append(suffix).toString();
}
}
// qualify null as numeric for ID fields
viewDefinition = viewDefinition.replaceAll("(?i)NULL\\s+(AS\\s+\\w+ID\\b)", "NULL::numeric $1");
// column headers need AS keyword in postgresql
// (seems to be sometimes missing after a construct that ends on parenthesis)
if (viewDefinition!=null) {
// if it ends with a comma we know it is a column header
viewDefinition = viewDefinition.replaceAll("\\)\\s(\\w+),", ") AS $1,");
// if it does not end with comma but as end-of-line, it is a bit more
// complicated because we can not be sure the last word is really a
// column header.
// So we check for key-words. If it is a keyword, we assume it is
// not a column header
Pattern pattern = Pattern.compile("\\)\\s(\\w+)$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(viewDefinition);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String lastWord = matcher.group(1);
if (! DBEngine.keyWords.contains(lastWord.toUpperCase()))
matcher.appendReplacement(sb, ") AS " + lastWord);
}
matcher.appendTail(sb);
viewDefinition = sb.toString();
}
// number in oracle is numeric in postgres
viewDefinition = viewDefinition.replaceAll("(?i)AS NUMBER\\b", "AS NUMERIC");
// postgresql has trunc for numbers and date_trunc for dates
viewDefinition = viewDefinition.replaceAll("(?i)\\bTRUNC\\s?\\(([^<=>]*?),\\s?'MM'\\)", "DATE_TRUNC ('month', $1)::date");
viewDefinition = viewDefinition.replaceAll("(?i)\\bTRUNC\\s?\\(([^<=>]*?)(,\\s?'DD')?\\)", "DATE_TRUNC ('day', $1)::date");
// postgresql does not have an add_months function
viewDefinition = viewDefinition.replaceAll("(?i)ADD_MONTHS\\s?\\((.*?),(.*?)\\)", "$1 + ($2 * interval '1 months')");
// postgresql can not add integers to timestamps
viewDefinition = viewDefinition.replaceAll("\\b(.*?date[^\\(]*?)\\s*?\\+\\s*?([^\\(]*?day.*?)\\b", "$1::date + $2");
viewDefinition = viewDefinition.replaceAll("(?i)(firstof\\s?\\([^,]*?,\\s?'.*?'\\))", "$1::date");
// different syntax of type casts
// CAST (xxx AS yyy) becomes xxx::yyy
StringBuffer buffer = new StringBuffer();
Pattern pattern = Pattern.compile("\\bCAST\\s?\\((.*?)\\s+AS\\s+(.*?)\\b\\(?(\\d*?),?(\\d*)\\)?\\)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(viewDefinition);
while (matcher.find()) {
String item = matcher.group(1);
String type = matcher.group(2);
String size = matcher.group(3);
String scale = matcher.group(4);
// if we have only a scale it was supposed to be the size
if (size==null || size.length()==0) {
if (scale!=null) {
size = scale;
scale = "";
}
}
if (size==null || size.length()==0)
size = "0";
if (scale==null || scale.length()==0)
scale="0";
String translatedType = dbEngine.translateDataType(sourceVendorName, getVendorNames().get(0), type, new Integer(size).intValue(), new Integer(scale).intValue());
matcher.appendReplacement(buffer, new StringBuffer(item).append("::").append(translatedType).toString());
}
matcher.appendTail(buffer);
viewDefinition = buffer.toString();
}
return viewDefinition;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#translateViewDefinitionStub(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String translateViewDefinitionStub (String sourceVendorName, String viewDefinition) {
// // comment out actual view definition
// viewDefinition = viewDefinition.replaceAll("(?m)^", "-- migrate: ");
//
// StringBuffer stub = new StringBuffer(viewDefinition);
//
// // add stub
// stub.append(System.getProperty("line.separator")).append("-- Migration Stub Start --").append(System.getProperty("line.separator"));
// stub.append("SELECT 1");
// stub.append(System.getProperty("line.separator")).append("-- Migration Stub End --").append(System.getProperty("line.separator"));
// postgres does not store view definitions as original source code, so comments get lost.
// to remember the original source code, we use it as return value by the stub.
// escape single quotes in original view definition
viewDefinition = viewDefinition.replaceAll("'", "''");
// create stub
StringBuffer stub = new StringBuffer("SELECT '")
.append(System.getProperty("line.separator"))
.append(viewDefinition)
.append(System.getProperty("line.separator"))
.append("'");
return stub.toString();
}
// sql compatibility
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlCreateSchema(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlAdmin_createSchema(int step, String catalogName, String schemaName, String passwd) {
if (step>0)
return null;
return new StringBuffer().append("CREATE SCHEMA ").append(schemaName).toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlDropSchema(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, int, java.lang.String, java.lang.String)
*/
public String sqlAdmin_dropSchema(int step, String catalogName, String schemaName) {
if (step>0)
return null;
return new StringBuffer().append("DROP SCHEMA ").append(schemaName).append(" CASCADE").toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlAdmin_connectSchema(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, int, java.lang.String, java.lang.String)
*/
public String sqlAdmin_connectSchema(int step, String catalogName, String schemaName) {
if (step>0)
return null;
return new StringBuffer("SET search_path TO ").append(schemaName).toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlAdmin_optimizeDatabase(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, int, java.lang.String, java.lang.String)
*/
public String sqlAdmin_optimizeDatabase(int step, String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
switch (step) {
case 0:
sql.append("VACUUM ANALYZE");
break;
}
if (sql.length()>0)
return sql.toString();
else
return null;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlAdmin_prepareDatabaseForTransfer(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, int, java.lang.String, java.lang.String)
*/
public String sqlAdmin_prepareDatabaseForTransfer(int step, String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
// When transferring to PostgreSQL, the source may contain some
// functions or operators which are not native to PostgreSQL.
// Customized objects referencing those functions or operators
// available in source would therefore not compile in PostgreSQL.
// Such functions and operators are temporarily added here for the
// transfer migration
switch (step) {
case 0:
// add_months(timestamp, numeric) from adempiere/db/ddlutils/postgresql/functions/Add_Months.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".add_months (in datetime timestamptz, in months numeric) RETURNS date AS "
+ "$BODY$ "
+ "declare duration varchar; "
+ "BEGIN "
+ "if datetime is null or months is null then "
+ "return null; "
+ "end if; "
+ "duration = months || ' month'; "
+ "return cast(datetime + cast(duration as interval) as date); "
+ "END; "
+ "$BODY$ "
+ "LANGUAGE 'plpgsql' "
+ "; ");
break;
case 1:
// addDays(timestamp, numeric) from adempiere/db/ddlutils/postgresql/functions/addDays.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".addDays(datetime TIMESTAMP WITH TIME ZONE, days Numeric) "
+ "RETURNS DATE AS $$ "
+ "declare duration varchar; "
+ "BEGIN "
+ "if datetime is null or days is null then "
+ "return null; "
+ "end if; "
+ "duration = days || ' day'; "
+ "return cast(date_trunc('day',datetime) + cast(duration as interval) as date); "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 2:
// subtractDays(timestamp, numeric) from adempiere/db/ddlutils/postgresql/functions/addDays.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".subtractdays (day TIMESTAMP WITH TIME ZONE, days NUMERIC) "
+ "RETURNS DATE AS $$ "
+ "BEGIN "
+ "RETURN ").append(schemaName).append(".addDays(day,(days * -1)); "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 3:
// addDays(interval, numeric) from adempiere/db/ddlutils/postgresql/functions/addDays.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".adddays(inter interval, days numeric) "
+ "RETURNS integer AS "
+ "$BODY$ "
+ "BEGIN "
+ "RETURN ( EXTRACT( EPOCH FROM ( inter ) ) / 86400 ) + days; "
+ "END; "
+ "$BODY$ "
+ "LANGUAGE plpgsql VOLATILE "
+ "COST 100;");
break;
case 4:
// subtractDays(interval, numeric) from adempiere/db/ddlutils/postgresql/functions/addDays.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".subtractdays(inter interval, days numeric) "
+ "RETURNS integer AS "
+ "$BODY$ "
+ "BEGIN "
+ "RETURN ( EXTRACT( EPOCH FROM ( inter ) ) / 86400 ) - days; "
+ "END; "
+ "$BODY$ "
+ "LANGUAGE plpgsql VOLATILE "
+ "COST 100; ");
break;
case 5:
// charAt(string, position) from adempiere/db/ddlutils/postgresql/functions/charAt.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".charAt ( "
+ "IN VARCHAR, "
+ "IN INTEGER "
+ ") RETURNS VARCHAR AS "
+ "$$ "
+ "BEGIN "
+ "RETURN SUBSTR($1, $2, 1); "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 6:
// daysBetween(timestamp, timestamp) from adempiere/db/ddlutils/postgresql/functions/daysBetween.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".daysBetween(p_date1 TIMESTAMP WITH TIME ZONE, p_date2 TIMESTAMP WITH TIME ZONE) "
+ "RETURNS INTEGER AS $$ "
+ "BEGIN "
+ "RETURN CAST(p_date1 AS DATE) - CAST(p_date2 as DATE); "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 7:
// firstof(timestamp, string) from adempiere/db/ddlutils/postgresql/functions/firstOf.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".firstOf ( "
+ "IN TIMESTAMP WITH TIME ZONE, "
+ "IN VARCHAR "
+ ") RETURNS DATE AS "
+ "$$ "
+ "DECLARE "
+ "datepart VARCHAR; "
+ "datetime TIMESTAMP WITH TIME ZONE; "
+ "offsetdays INTEGER; "
+ "BEGIN "
+ "datepart = $2; "
+ "offsetdays = 0; "
+ "IF $2 IN ('') THEN "
+ "datepart = 'millennium'; "
+ "ELSEIF $2 IN ('') THEN "
+ "datepart = 'century'; "
+ "ELSEIF $2 IN ('') THEN "
+ "datepart = 'decade'; "
+ "ELSEIF $2 IN ('IYYY','IY','I') THEN "
+ "datepart = 'year'; "
+ "ELSEIF $2 IN ('SYYYY','YYYY','YEAR','SYEAR','YYY','YY','Y') THEN "
+ "datepart = 'year'; "
+ "ELSEIF $2 IN ('Q') THEN "
+ "datepart = 'quarter'; "
+ "ELSEIF $2 IN ('MONTH','MON','MM','RM') THEN "
+ "datepart = 'month'; "
+ "ELSEIF $2 IN ('IW') THEN "
+ "datepart = 'week'; "
+ "ELSEIF $2 IN ('W') THEN "
+ "datepart = 'week'; "
+ "ELSEIF $2 IN ('DDD','DD','J') THEN "
+ "datepart = 'day'; "
+ "ELSEIF $2 IN ('DAY','DY','D') THEN "
+ "datepart = 'week'; "
+ "offsetdays = -1; "
+ "ELSEIF $2 IN ('HH','HH12','HH24') THEN "
+ "datepart = 'hour'; "
+ "ELSEIF $2 IN ('MI') THEN "
+ "datepart = 'minute'; "
+ "ELSEIF $2 IN ('') THEN "
+ "datepart = 'second'; "
+ "ELSEIF $2 IN ('') THEN "
+ "datepart = 'milliseconds'; "
+ "ELSEIF $2 IN ('') THEN "
+ "datepart = 'microseconds'; "
+ "END IF; "
+ "datetime = date_trunc(datepart, $1); "
+ "RETURN cast(datetime as date) + offsetdays; "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 8:
// instr(string, string, int) from adempiere/db/ddlutils/postgresql/functions/INSTR.sql
sql.append("CREATE FUNCTION ").append(schemaName).append(".instr(string varchar, string_to_search varchar, beg_index integer) "
+ "RETURNS integer AS $$ "
+ "DECLARE "
+ "pos integer NOT NULL DEFAULT 0; "
+ "temp_str varchar; "
+ "beg integer; "
+ "length integer; "
+ "ss_length integer; "
+ "BEGIN "
+ "IF beg_index > 0 THEN "
+ "temp_str := substring(string FROM beg_index); "
+ "pos := position(string_to_search IN temp_str); "
+ "IF pos = 0 THEN "
+ "RETURN 0; "
+ "ELSE "
+ "RETURN pos + beg_index - 1; "
+ "END IF; "
+ "ELSE "
+ "ss_length := char_length(string_to_search); "
+ "length := char_length(string); "
+ "beg := length + beg_index - ss_length + 2; "
+ "WHILE beg > 0 LOOP "
+ "temp_str := substring(string FROM beg FOR ss_length); "
+ "pos := position(string_to_search IN temp_str); "
+ "IF pos > 0 THEN "
+ "RETURN beg; "
+ "END IF; "
+ "beg := beg - 1; "
+ "END LOOP; "
+ "RETURN 0; "
+ "END IF; "
+ "END; "
+ "$$ LANGUAGE plpgsql STRICT IMMUTABLE; ");
break;
case 9:
// instr(string, string) from adempiere/db/ddlutils/postgresql/functions/INSTR.sql
sql.append("CREATE FUNCTION ").append(schemaName).append(".instr(varchar, varchar) RETURNS integer AS $$ "
+ "DECLARE "
+ "pos integer; "
+ "BEGIN "
+ "pos:= ").append(schemaName).append(".instr($1, $2, 1); "
+ "RETURN pos; "
+ "END; "
+ "$$ LANGUAGE plpgsql STRICT IMMUTABLE; ");
break;
case 10:
// instr(string, string, int, int) from adempiere/db/ddlutils/postgresql/functions/INSTR.sql
sql.append("CREATE FUNCTION ").append(schemaName).append(".instr(string varchar, string_to_search varchar, "
+ "beg_index integer, occur_index integer) "
+ "RETURNS integer AS $$ "
+ "DECLARE "
+ "pos integer NOT NULL DEFAULT 0; "
+ "occur_number integer NOT NULL DEFAULT 0; "
+ "temp_str varchar; "
+ "beg integer; "
+ "i integer; "
+ "length integer; "
+ "ss_length integer; "
+ "BEGIN "
+ "IF beg_index > 0 THEN "
+ "beg := beg_index; "
+ "temp_str := substring(string FROM beg_index); "
+ "FOR i IN 1..occur_index LOOP "
+ "pos := position(string_to_search IN temp_str); "
+ "IF i = 1 THEN "
+ "beg := beg + pos - 1; "
+ "ELSE "
+ "beg := beg + pos; "
+ "END IF; "
+ "temp_str := substring(string FROM beg + 1); "
+ "END LOOP; "
+ "IF pos = 0 THEN "
+ "RETURN 0; "
+ "ELSE "
+ "RETURN beg; "
+ "END IF; "
+ "ELSE "
+ "ss_length := char_length(string_to_search); "
+ "length := char_length(string); "
+ "beg := length + beg_index - ss_length + 2; "
+ "WHILE beg > 0 LOOP "
+ "temp_str := substring(string FROM beg FOR ss_length); "
+ "pos := position(string_to_search IN temp_str); "
+ "IF pos > 0 THEN "
+ "occur_number := occur_number + 1; "
+ "IF occur_number = occur_index THEN "
+ "RETURN beg; "
+ "END IF; "
+ "END IF; "
+ "beg := beg - 1; "
+ "END LOOP; "
+ "RETURN 0; "
+ "END IF; "
+ "END; "
+ "$$ LANGUAGE plpgsql STRICT IMMUTABLE; ");
break;
case 11:
// round(numeric, numeric) from adempiere/db/ddlutils/postgresql/functions/round.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".round ( "
+ "IN NUMERIC, "
+ "IN NUMERIC "
+ ") RETURNS NUMERIC AS "
+ "$$ "
+ "BEGIN "
+ "RETURN ROUND($1, cast($2 as integer)); "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 12:
// trunc(timestamp) from adempiere/db/ddlutils/postgresql/functions/trunc.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".trunc(datetime timestamp with time zone) "
+ "RETURNS timestamp with time zone AS "
+ "$BODY$ "
+ "BEGIN "
+ "RETURN CAST(datetime AS DATE); "
+ "END; "
+ "$BODY$ "
+ "LANGUAGE plpgsql VOLATILE "
+ "COST 100; ");
break;
case 13:
// trunc(timestamp, string) from adempiere/db/ddlutils/postgresql/functions/trunc.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".trunc(datetime TIMESTAMP WITH TIME ZONE, format varchar) "
+ "RETURNS DATE AS $$ "
+ "BEGIN "
+ "IF format = 'Q' THEN "
+ "RETURN CAST(DATE_Trunc('quarter',datetime) as DATE); "
+ "ELSIF format = 'Y' or format = 'YEAR' THEN "
+ "RETURN CAST(DATE_Trunc('year',datetime) as DATE); "
+ "ELSIF format = 'MM' or format = 'MONTH' THEN "
+ "RETURN CAST(DATE_Trunc('month',datetime) as DATE); "
+ "ELSIF format = 'DD' THEN "
+ "RETURN CAST(DATE_Trunc('day',datetime) as DATE); "
+ "ELSIF format = 'DY' THEN "
+ "RETURN CAST(DATE_Trunc('day',datetime) as DATE); "
+ "ELSE "
+ "RETURN CAST(datetime AS DATE); "
+ "END IF; "
+ "END; "
+ "$$ LANGUAGE plpgsql; ");
break;
case 14:
// trunc(interval) from adempiere/db/ddlutils/postgresql/functions/trunc.sql
sql.append("CREATE OR REPLACE FUNCTION ").append(schemaName).append(".trunc(i interval) "
+ "RETURNS integer AS "
+ "$BODY$ "
+ "BEGIN "
+ "RETURN EXTRACT(DAY FROM i); "
+ "END; "
+ "$BODY$ "
+ "LANGUAGE plpgsql VOLATILE "
+ "COST 100; ");
break;
case 15:
// operator + (timestamp, numeric) from adempiere/db/ddlutils/postgresql/operators.sql
sql.append("CREATE OPERATOR ").append(schemaName).append(".+ ( PROCEDURE = ").append(schemaName).append(".adddays, "
+ "LEFTARG = TIMESTAMPTZ, RIGHTARG = NUMERIC, "
+ "COMMUTATOR = +); ");
break;
case 16:
// operator - (timestamp, numeric) from adempiere/db/ddlutils/postgresql/operators.sql
sql.append("CREATE OPERATOR ").append(schemaName).append(".- ( PROCEDURE = ").append(schemaName).append(".subtractdays, "
+ "LEFTARG = TIMESTAMPTZ, RIGHTARG = NUMERIC, "
+ "COMMUTATOR = -); ");
break;
}
if (sql.length()>0)
return sql.toString();
else
return null;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_avilableDatabases()
*/
public String sqlMetadata_availableDatabases() {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "datname AS DATABASE_NAME "
+ "FROM pg_database "
+ "WHERE datname NOT LIKE 'template%' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_closeCharSetTest(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_closeCharSetTest(String catalogName, String schemaName, String tableName) {
// no character set test needed in postgresql
return null;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_openCharSetTest(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_openCharSetTest(String catalogName, String schemaName, String tableName) {
// no character set test needed in postgresql
return null;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_tableNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_tableNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "table_name AS OBJECT_NAME "
+ "FROM information_schema.tables "
+ "WHERE table_type = 'BASE TABLE' "
+ "AND table_catalog = '").append(catalogName).append("' "
+ "AND table_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_tableColumns(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_tableColumns(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "table_name AS TABLE_NAME, "
+ "ordinal_position AS COLUMN_SEQUENCE, "
+ "column_name AS COLUMN_NAME, "
+ "data_type AS COLUMN_TYPE, "
+ "COALESCE (character_maximum_length, numeric_precision) AS COLUMN_SIZE, "
+ "numeric_scale AS COLUMN_PRECISION, "
+ "column_default AS COLUMN_DEFAULT, "
+ "is_nullable AS COLUMN_NULLABLE "
+ "FROM information_schema.columns "
+ "WHERE table_name = ? "
+ "AND table_catalog = '").append(catalogName).append("' "
+ "AND table_schema = '").append(schemaName).append("' "
+ "ORDER BY 2 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetaData_viewNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_viewNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "table_name AS OBJECT_NAME "
+ "FROM information_schema.tables "
+ "WHERE table_type = 'VIEW' "
+ "AND table_catalog = '").append(catalogName).append("' "
+ "AND table_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_viewDefinitions(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_viewDefinitions(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "table_name AS VIEW_NAME, "
+ "view_definition AS VIEW_DEFINITION "
+ "FROM information_schema.views "
+ "WHERE table_name = ? "
+ "AND table_catalog = '").append(catalogName).append("' "
+ "AND table_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_functionNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_functionNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
// postgres has overloaded functions, and adempiere uses them, so we need unique signatures and use specific_name
sql.append("SELECT "
+ "specific_name AS OBJECT_NAME "
+ "FROM information_schema.routines "
+ "WHERE specific_catalog = '").append(catalogName).append("' "
+ "AND specific_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_functionArguments(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_functionArguments(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "rt.routine_name AS FUNC_NAME, "
+ "rt.routine_type AS FUNC_TYPE, "
+ "rt.external_language AS FUNC_LANG, "
+ "rt.data_type AS RET_TYPE, "
+ "pr.ordinal_position AS SEQ_NUM, "
+ "pr.parameter_mode AS ARG_DIR, "
+ "pr.parameter_name AS ARG_NAME, "
+ "pr.data_type AS ARG_TYPE "
+ "FROM information_schema.routines rt "
+ "LEFT JOIN information_schema.parameters pr ON (rt.specific_name = pr.specific_name) "
+ "WHERE rt.specific_name = ? "
+ "AND rt.specific_catalog = '").append(catalogName).append("' "
+ "AND rt.specific_schema = '").append(schemaName).append("' "
+ "ORDER BY 1,5 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_functionBodies(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_functionBodies(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "rt.routine_name AS FUNC_NAME, "
+ "0 AS SEQ_NUM, "
+ "rt.routine_definition AS FUNC_DEF "
+ "FROM information_schema.routines rt "
+ "WHERE rt.specific_name = ? "
+ "AND rt.specific_catalog = '").append(catalogName).append("' "
+ "AND rt.specific_schema = '").append(schemaName).append("' "
+ "ORDER BY 2 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_operatorNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_operatorNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "op.oprname || ' (' || "
+ "CASE op.oprleft "
+ "WHEN 0 THEN '' || "
+ "CASE op.oprright "
+ "WHEN 0 THEN '' "
+ "ELSE rt.typname "
+ "END "
+ "ELSE lt.typname || "
+ "CASE op.oprright "
+ "WHEN 0 THEN '' "
+ "ELSE ', ' || rt.typname "
+ "END "
+ "END "
+ "|| ')' AS OBJECT_NAME, "
+ "lt.typname, "
+ "rt.typname "
+ "FROM pg_operator op "
+ "LEFT JOIN pg_type lt ON (op.oprleft = lt.oid) "
+ "LEFT JOIN pg_type rt ON (op.oprright = rt.oid) "
+ "WHERE op.oprnamespace IN "
+ "(SELECT oid FROM pg_namespace WHERE nspname LIKE '").append(schemaName).append("') "
+ "ORDER BY 1,2,3 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_operatorSignatures(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_operatorSignatures(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "op.oprname AS OPERATOR_NAME, "
+ "lt.typname AS LEFT_ARG, "
+ "rt.typname AS RIGHT_ARG, "
+ "tr.typname AS RETURN_TYPE "
+ "FROM pg_operator op "
+ "LEFT JOIN pg_type lt ON (op.oprleft = lt.oid) "
+ "LEFT JOIN pg_type rt ON (op.oprright = rt.oid) "
+ "LEFT JOIN pg_type tr ON (op.oprresult = tr.oid) "
+ "WHERE op.oprnamespace IN "
+ "(SELECT oid FROM pg_namespace WHERE nspname LIKE '").append(schemaName).append("')"
+ "AND ("
+ "op.oprname || ' (' || "
+ "CASE op.oprleft "
+ "WHEN 0 THEN '' || "
+ "CASE op.oprright "
+ "WHEN 0 THEN '' "
+ "ELSE rt.typname "
+ "END "
+ "ELSE lt.typname || "
+ "CASE op.oprright "
+ "WHEN 0 THEN '' "
+ "ELSE ', ' || rt.typname "
+ "END "
+ "END "
+ "|| ')') = ? "
+ "ORDER BY 1,2,3 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_operatorDefinitions(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_operatorDefinitions(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "op.oprname AS OPERATOR_NAME, "
+ "CASE op.oprcode "
+ "WHEN 0 THEN null "
+ "ELSE op.oprcode "
+ "END AS FUNCTION_NAME, "
+ "com.oprname AS OP_COMMUTATOR, "
+ "neg.oprname AS OP_NEGATOR, "
+ "CASE op.oprrest "
+ "WHEN 0 THEN null "
+ "ELSE op.oprrest "
+ "END AS OP_RESTRICT, "
+ "CASE op.oprjoin "
+ "WHEN 0 THEN null "
+ "ELSE op.oprjoin "
+ "END AS OP_JOIN, "
+ "op.oprcanhash AS OP_HASHABLE, "
+ "op.oprcanmerge AS OP_MERGEABLE "
+ "FROM pg_operator op "
+ "LEFT JOIN pg_type lt ON (op.oprleft = lt.oid) "
+ "LEFT JOIN pg_type rt ON (op.oprright = rt.oid) "
+ "LEFT JOIN pg_operator com ON (op.oprcom = com.oid) "
+ "LEFT JOIN pg_operator neg ON (op.oprnegate = neg.oid) "
+ "WHERE op.oprnamespace IN "
+ "(SELECT oid FROM pg_namespace WHERE nspname LIKE '").append(schemaName).append("')"
+ "AND ("
+ "op.oprname || ' (' || "
+ "CASE op.oprleft "
+ "WHEN 0 THEN '' || "
+ "CASE op.oprright "
+ "WHEN 0 THEN '' "
+ "ELSE rt.typname "
+ "END "
+ "ELSE lt.typname || "
+ "CASE op.oprright "
+ "WHEN 0 THEN '' "
+ "ELSE ', ' || rt.typname "
+ "END "
+ "END "
+ "|| ')') = ? "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_triggerNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_triggerNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "trigger_name AS OBJECT_NAME "
+ "FROM information_schema.triggers "
+ "WHERE trigger_catalog = '").append(catalogName).append("' "
+ "AND trigger_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_triggerTables(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_triggerTables(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "trigger_name AS TRIG_NAME, "
+ "condition_timing AS TRIG_TYPE, "
+ "event_manipulation AS TRIG_EVENT, "
+ "event_object_table AS TABLE_NAME, "
+ "'CALL' AS ACTION_TYPE, "
+ "action_orientation AS ACTION_ORIENTATION "
+ "FROM information_schema.triggers "
+ "WHERE trigger_name = ? "
+ "AND trigger_catalog = '").append(catalogName).append("' "
+ "AND trigger_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_triggerDefinitions(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_triggerDefinitions(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "trigger_name AS TRIG_NAME, "
+ "action_statement AS TRIG_BODY "
+ "FROM information_schema.triggers "
+ "WHERE trigger_name = ? "
+ "AND trigger_catalog = '").append(catalogName).append("' "
+ "AND trigger_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_sequenceNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_sequenceNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT relname AS OBJECT_NAME "
+ "FROM pg_class "
+ "WHERE relkind='S' "
+ "AND relnamespace IN ("
+ "SELECT oid FROM pg_namespace "
+ "WHERE nspname LIKE '").append(schemaName).append("') "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_sequenceDefinitions(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlMetadata_sequenceDefinitions(String catalogName, String schemaName, String sequenceName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "min_value AS MIN_VALUE, "
+ "max_value AS MAX_VALUE, "
+ "increment_by AS INCREMENT_BY, "
+ "is_cycled AS IS_CYCLED, "
+ "cache_value AS CACHE_SIZE, "
+ "last_value AS LAST_VALUE "
+ "FROM ").append(schemaName).append(".").append(sequenceName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetdata_primaryKeyNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_primaryKeyNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "constraint_name AS OBJECT_NAME "
+ "FROM information_schema.table_constraints tc "
+ "WHERE constraint_type = 'PRIMARY KEY' "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_primaryKeyTables(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_primaryKeyTables(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "tc.constraint_name AS PK_NAME, "
+ "tc.table_name AS TABLE_NAME, "
+ "tc.is_deferrable AS IS_DEFERRABLE, "
+ "tc.initially_deferred AS INITIALLY_DEFERRED "
+ "FROM information_schema.table_constraints tc "
+ "WHERE constraint_type = 'PRIMARY KEY' "
+ "AND constraint_name = ? "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_primaryKeyColumns(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_primaryKeyColumns(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "constraint_name AS PK_NAME, "
+ "ordinal_position AS PK_SEQ, "
+ "table_name AS TABLE_NAME, "
+ "column_name AS COLUMN_NAME "
+ "FROM information_schema.key_column_usage "
+ "WHERE constraint_name = ? "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 2 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_foreignKeyNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_foreignKeyNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "constraint_name AS OBJECT_NAME "
+ "FROM information_schema.table_constraints tc "
+ "WHERE constraint_type = 'FOREIGN KEY' "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_foreignKeyTables(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlMetadata_foreignKeyTables(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT DISTINCT "
+ "tc.constraint_name AS FK_NAME, "
+ "tc.table_name AS TABLE_NAME, "
+ "ccu.table_name AS FTABLE_NAME, "
+ "tc.is_deferrable AS IS_DEFERRABLE, "
+ "tc.initially_deferred AS INITIALLY_DEFERRED, "
+ "rc.match_option AS MATCH_TYPE, "
+ "rc.update_rule AS ON_UPDATE, "
+ "rc.delete_rule AS ON_DELETE "
+ "FROM information_schema.table_constraints tc "
+ "LEFT JOIN information_schema.referential_constraints rc "
+ "ON tc.constraint_catalog = rc.constraint_catalog "
+ "AND tc.constraint_schema = rc.constraint_schema "
+ "AND tc.constraint_name = rc.constraint_name "
+ "LEFT JOIN information_schema.constraint_column_usage ccu "
+ "ON tc.constraint_catalog = ccu.constraint_catalog "
+ "AND tc.constraint_schema = ccu.constraint_schema "
+ "AND tc.constraint_name = ccu.constraint_name "
+ "WHERE tc.constraint_type = 'FOREIGN KEY' "
+ "AND tc.constraint_name = ? "
+ "AND tc.constraint_catalog = '").append(catalogName).append("' "
+ "AND tc.constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_foreignKeyColumns(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_foreignKeyColumns(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT DISTINCT "
+ "kcu.constraint_name AS FK_NAME, "
+ "kcu.ordinal_position AS FK_SEQ, "
+ "kcu.table_name AS TABLE_NAME, "
+ "kcu.column_name AS COLUMN_NAME, "
+ "ft.relname AS FTABLE_NAME, "
+ "attr.attname AS FCOLUMN_NAME "
+ "FROM information_schema.key_column_usage kcu "
+ "LEFT JOIN pg_constraint c "
+ "ON kcu.constraint_name = c.conname "
+ "LEFT JOIN pg_namespace nsp "
+ "ON c.connamespace = nsp.oid "
+ "AND kcu.constraint_schema = nsp.nspname "
+ "LEFT JOIN pg_class ft "
+ "ON c.confrelid = ft.oid "
+ "LEFT JOIN pg_attribute attr "
+ "ON c.confrelid = attr.attrelid "
+ "AND c.confkey[kcu.ordinal_position]=attr.attnum "
+ "WHERE kcu.constraint_name = ? "
+ "AND kcu.constraint_catalog = '").append(catalogName).append("' "
+ "AND kcu.constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1,2 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_checkNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_checkNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT cns.conname AS OBJECT_NAME "
+ "FROM pg_constraint cns "
+ "LEFT JOIN pg_namespace nmspc ON cns.connamespace = nmspc.oid "
+ "WHERE cns.contype = 'c' "
+ "AND nmspc.nspname = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_checkTables(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_checkTables(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "cns.conname AS CHECK_NAME, "
+ "cls.relname AS TABLE_NAME, "
+ "cns.condeferrable AS IS_DEFERRABLE, "
+ "cns.condeferred AS INITIALLY_DEFERRED "
+ "FROM pg_constraint cns "
+ "LEFT JOIN pg_class cls "
+ "ON (cns.conrelid = cls.oid) "
+ "LEFT JOIN pg_namespace nmspc "
+ "ON (cns.connamespace = nmspc.oid) "
+ "WHERE cns.contype = 'c' "
+ "AND nmspc.nspname = '").append(schemaName).append("' "
+ "AND cns.conname = ? "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_checkRules(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_checkRules(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "cns.conname AS CHECK_NAME, "
+ "cls.relname AS TABLE_NAME, "
+ "cns.consrc AS CHECK_CLAUSE "
+ "FROM pg_constraint cns "
+ "LEFT JOIN pg_class cls "
+ "ON (cns.conrelid = cls.oid) "
+ "LEFT JOIN pg_namespace nmspc "
+ "ON (cns.connamespace = nmspc.oid) "
+ "WHERE cns.contype = 'c' "
+ "AND nmspc.nspname = '").append(schemaName).append("' "
+ "AND cns.conname = ? "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_uniqueNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_uniqueNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "constraint_name AS OBJECT_NAME "
+ "FROM information_schema.table_constraints tc "
+ "WHERE constraint_type = 'UNIQUE' "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_uniqueTables(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_uniqueTables(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "tc.constraint_name AS UNIQUE_NAME, "
+ "tc.table_name AS TABLE_NAME, "
+ "tc.is_deferrable AS IS_DEFERRABLE, "
+ "tc.initially_deferred AS INITIALLY_DEFERRED "
+ "FROM information_schema.table_constraints tc "
+ "WHERE constraint_type = 'UNIQUE' "
+ "AND constraint_name = ? "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_uniqueColumns(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_uniqueColumns(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "constraint_name AS UNIQUE_NAME, "
+ "ordinal_position AS UNIQUE_SEQ, "
+ "table_name AS TABLE_NAME, "
+ "column_name AS COLUMN_NAME "
+ "FROM information_schema.key_column_usage "
+ "WHERE constraint_name = ? "
+ "AND constraint_catalog = '").append(catalogName).append("' "
+ "AND constraint_schema = '").append(schemaName).append("' "
+ "ORDER BY 2 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_indexNames(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_indexNames(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "pgc.relname AS OBJECT_NAME "
+ "FROM pg_class pgc "
+ "LEFT JOIN pg_index pgi "
+ "ON pgc.oid = pgi.indexrelid "
+ "LEFT JOIN pg_namespace nmspc "
+ "ON pgc.relnamespace = nmspc.oid "
+ "WHERE pgi.indisprimary != 't' "
+ "AND nmspc.nspname = '").append(schemaName).append("' "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_indexTables(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_indexTables(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT "
+ "pgc.relname AS INDEX_NAME, "
+ "pgctbl.relname AS TABLE_NAME, "
+ "pgi.indisunique AS IS_UNIQUE "
+ "FROM pg_class pgc "
+ "LEFT JOIN pg_index pgi "
+ "ON pgc.oid = pgi.indexrelid "
+ "LEFT JOIN pg_namespace nmspc "
+ "ON pgc.relnamespace = nmspc.oid "
+ "LEFT JOIN pg_class pgctbl "
+ "ON pgi.indrelid = pgctbl.oid "
+ "WHERE nmspc.nspname = '").append(schemaName).append("' "
+ "AND pgc.relname = ? "
+ "ORDER BY 1 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlMetadata_indexColumns(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String)
*/
public String sqlMetadata_indexColumns(String catalogName, String schemaName) {
StringBuffer sql = new StringBuffer();
// postgresql returns any expression as column name, so we can just always return NULL
// as expression value
sql.append("SELECT "
+ "(SELECT pgc.relname "
+ "FROM pg_class pgc "
+ "LEFT JOIN pg_index pgi ON pgc.oid = pgi.indexrelid "
+ "LEFT JOIN pg_namespace nmspc ON pgc.relnamespace = nmspc.oid "
+ "WHERE nmspc.nspname = '").append(schemaName).append("' "
+ "AND pgc.relname = ? "
+ ") AS INDEX_NAME, "
+ "s.a AS INDEX_SEQ, "
+ "(SELECT pgt.relname "
+ "FROM pg_class pgt "
+ "LEFT JOIN pg_index pgi ON pgt.oid = pgi.indrelid "
+ "LEFT JOIN pg_class pgc ON pgi.indexrelid = pgc.oid "
+ "LEFT JOIN pg_namespace nmspc ON pgc.relnamespace = nmspc.oid "
+ "WHERE nmspc.nspname = '").append(schemaName).append("' "
+ "AND pgc.relname = ? "
+ ") AS TABLE_NAME, "
+ "pg_get_indexdef((SELECT pgc.oid "
+ "FROM pg_class pgc "
+ "LEFT JOIN pg_namespace nmspc ON pgc.relnamespace = nmspc.oid "
+ "WHERE nmspc.nspname = '").append(schemaName).append("' "
+ "AND pgc.relname = ?), "
+ "s.a, "
+ "false"
+ ") AS COLUMN_NAME, "
+ "NULL AS EXPRESSION, "
+ "CASE ( "
+ "SELECT pgi.indoption[s.a-1] "
+ "FROM pg_index pgi "
+ "LEFT JOIN pg_class pgc ON pgi.indexrelid = pgc.oid "
+ "LEFT JOIN pg_namespace nmspc ON pgc.relnamespace = nmspc.oid "
+ "WHERE nmspc.nspname = '").append(schemaName).append("' "
+ "AND pgc.relname = ? "
+ ") "
+ "WHEN 0 THEN 'ASC' "
+ "WHEN 1 THEN 'DESC' "
+ "WHEN 2 THEN 'ASC' "
+ "WHEN 3 THEN 'DESC' "
+ "END AS SORT_ORDER, "
+ "CASE ( "
+ "SELECT pgi.indoption[s.a-1] "
+ "FROM pg_index pgi "
+ "LEFT JOIN pg_class pgc ON pgi.indexrelid = pgc.oid "
+ "LEFT JOIN pg_namespace nmspc ON pgc.relnamespace = nmspc.oid "
+ "WHERE nmspc.nspname = '").append(schemaName).append("' "
+ "AND pgc.relname = ? "
+ ") "
+ "WHEN 0 THEN 'LAST' "
+ "WHEN 1 THEN 'LAST' "
+ "WHEN 2 THEN 'FIRST' "
+ "WHEN 3 THEN 'FIRST' "
+ "END AS SORT_NULLS "
+ "FROM generate_series(1, "
+ "(SELECT indnatts FROM pg_index inline_pgi "
+ "LEFT JOIN pg_class inline_pgc ON inline_pgi.indexrelid = inline_pgc.oid "
+ "LEFT JOIN pg_namespace inline_nmspc ON inline_pgc.relnamespace = inline_nmspc.oid "
+ "WHERE inline_nmspc.nspname = '").append(schemaName).append("' "
+ "AND inline_pgc.relname = ? "
+ ") "
+ ") as s(a) "
+ "ORDER BY 1,2 ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#correctIndexFunction(java.lang.String)
*/
public String correctQuotedFieldNames(String expression) {
// nothing needs to be corrected in PostgreSQL
return expression;
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createTable(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList)
*/
public String sqlObject_createTable(String catalogName, String schemaName, String tableName, ArrayList<String> columnNames, ArrayList<String> columnTypes, ArrayList<Boolean> columnNullables, ArrayList<String> columnDefaults) {
StringBuffer sql = new StringBuffer();
// prefix
sql.append("CREATE TABLE ").append(schemaName).append(".").append(tableName).append(" (");
// column list
for (int i = 0; i < columnNames.size(); i++) {
String columnName = columnNames.get(i);
String dataType = columnTypes.get(i);
boolean isNullable = columnNullables.get(i);
String defaultValue = columnDefaults.get(i);
String sqlNullable = "";
if (! isNullable)
sqlNullable = " NOT NULL";
String sqlDefault = "";
if (defaultValue!=null && !defaultValue.equalsIgnoreCase("null") && defaultValue.length()>0)
sqlDefault = " DEFAULT " + defaultValue;
if (i>0)
sql.append(", ");
sql.append(columnName).append(" ").append(dataType).append(sqlNullable).append(sqlDefault);
}
// suffix
sql.append(")");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropTable(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropTable(String catalogName, String schemaName, String tableName) {
StringBuffer sql = new StringBuffer();
sql.append("DROP TABLE ").append(schemaName).append(".").append(tableName);
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createView(com.kkalice.adempiere.migrate.Parameters, com.kkalice.adempiere.migrate.Logger, com.kkalice.adempiere.migrate.DBEngine, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_createView(String catalogName, String schemaName, String viewName, String viewDefinition) {
StringBuffer sql = new StringBuffer();
sql.append("CREATE OR REPLACE VIEW ")
.append(schemaName).append(".").append(viewName).append(" "
+ "AS ").append(System.getProperty("line.separator"))
.append(viewDefinition).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getSQLDropView(java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropView(String catalogName, String schemaName, String viewName) {
StringBuffer sql = new StringBuffer();
sql.append("DROP VIEW IF EXISTS ").append(schemaName).append(".").append(viewName).append(" CASCADE ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createFunction(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.lang.String)
*/
public String sqlObject_createFunction(String catalogName, String schemaName, String functionType, String functionName, String functionReturnType, boolean hasOutParameters, String functionLanguage, ArrayList<String> argDirs, ArrayList<String> argNames, ArrayList<String> argTypes, String bodyText) {
StringBuffer sql = new StringBuffer();
// prefix
sql.append("CREATE OR REPLACE ")
.append(functionType).append(" ")
.append(schemaName).append(".").append(functionName).append(" (");
// header
for (int i=0; i<argNames.size(); i++) {
String argName = argNames.get(i);
String argType = argTypes.get(i);
String argDir = argDirs.get(i);
if (i>0)
sql.append(", ");
sql.append(argDir).append(" ").append(argName).append(" ").append(argType);
}
// middle
StringBuffer returnExpr = new StringBuffer();
if (!hasOutParameters)
returnExpr.append("RETURNS ").append(functionReturnType).append(" ");
sql.append(") ")
.append(returnExpr)
.append("LANGUAGE ").append(functionLanguage).append(" "
+ "AS ").append(System.getProperty("line.separator"))
.append("$BODY$ ").append(System.getProperty("line.separator"));
// body
sql.append(bodyText);
// suffix
sql.append(System.getProperty("line.separator"))
.append("$BODY$ ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropFunction(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropFunction(String catalogName, String schemaName, String functionType, String functionName, String functionSignature) {
StringBuffer sql = new StringBuffer();
// postgresql uses overloaded functions, so we need to identify the function to drop with its signature
sql.append("DROP ").append(functionType).append(" IF EXISTS ").append(schemaName).append(".").append(functionSignature).append(" CASCADE ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createOperator(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, boolean)
*/
public String sqlObject_createOperator(String catalogName, String schemaName, String operatorName, String leftArg, String rightArg, String returnType, String functionName, String commutator, String negator, String restrictor, String joiner, boolean isHashable, boolean isMergeable) {
StringBuffer sql = new StringBuffer();
StringBuffer function = new StringBuffer();
StringBuffer left = new StringBuffer();
StringBuffer right = new StringBuffer();
StringBuffer com = new StringBuffer();
StringBuffer neg = new StringBuffer();
StringBuffer res = new StringBuffer();
StringBuffer join = new StringBuffer();
StringBuffer hashes = new StringBuffer();
StringBuffer merges = new StringBuffer();
if (functionName!=null)
function.append("PROCEDURE = ").append(schemaName).append(".").append(functionName);
if (leftArg!=null)
left.append(", LEFTARG = ").append(leftArg);
if (rightArg!=null)
right.append(", RIGHTARG = ").append(rightArg);
if (commutator!=null)
com.append(", COMMUTATOR = ").append(commutator);
if (negator!=null)
neg.append(", NEGATOR = ").append(negator);
if (restrictor!=null)
res.append(", RESTRICT = ").append(restrictor);
if (joiner!=null)
join.append(", JOIN = ").append(joiner);
if (isHashable)
hashes.append(", HASHES");
if (isMergeable)
merges.append(", MERGES");
sql.append("CREATE OPERATOR ").append(schemaName).append(".").append(operatorName).append(" (")
.append(function)
.append(left).append(right)
.append(com).append(neg)
.append(res).append(join)
.append(hashes).append(merges)
.append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropOperator(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropOperator(String catalogName, String schemaName, String operatorName, String leftArg, String rightArg) {
StringBuffer sql = new StringBuffer();
String left = "NONE";
if (leftArg!=null)
left = leftArg;
String right = "NONE";
if (rightArg!=null)
right = rightArg;
sql.append("DROP OPERATOR IF EXISTS ").append(schemaName).append(".").append(operatorName).append(" "
+ "(").append(left).append(", ").append(right).append(") "
+ "CASCADE ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createTrigger(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_createTrigger(String catalogName, String schemaName, String triggerName, String tableName, String triggerType, String triggerEvent, String actionOrientation, String triggerCode) {
StringBuffer sql = new StringBuffer();
sql.append("CREATE TRIGGER ").append(triggerName).append(" ")
.append(triggerType).append(" ")
.append(triggerEvent).append(" "
+ "ON ").append(schemaName).append(".").append(tableName).append(" ")
.append(actionOrientation).append(" ")
.append(triggerCode).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropTrigger(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropTrigger(String catalogName, String schemaName, String triggerName, String tableName) {
StringBuffer sql = new StringBuffer();
sql.append("DROP TRIGGER ").append(schemaName).append(".").append(triggerName)
.append(" ON ").append(schemaName).append(".").append(tableName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createSequence(java.lang.String, java.lang.String, java.lang.String, long, long, long, boolean, long, long)
*/
public String sqlObject_createSequence(String catalogName, String schemaName, String sequenceName, long min, long max, long incr, boolean isCycled, long cache, long start) {
StringBuffer sql = new StringBuffer();
String strCycle = null;
if (isCycled)
strCycle = "CYCLE";
else
strCycle = "NO CYCLE";
sql.append("CREATE SEQUENCE ").append(schemaName).append(".").append(sequenceName).append(" "
+ "INCREMENT BY ").append(incr).append(" "
+ "MINVALUE ").append(min).append(" "
+ "MAXVALUE ").append(max).append(" "
+ "START WITH ").append(start).append(" "
+ "CACHE ").append(cache).append(" ")
.append(strCycle).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropSequence(java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropSequence(String catalogName, String schemaName, String sequenceName) {
StringBuffer sql = new StringBuffer();
sql.append("DROP SEQUENCE ").append(schemaName).append(".").append(sequenceName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createPrimaryKey(java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, boolean, java.util.ArrayList)
*/
public String sqlObject_createPrimaryKey(String catalogName, String schemaName, String tableName, String keyName, boolean isDeferrable, boolean isDeferred, ArrayList<String> keyColumns) {
StringBuffer sql = new StringBuffer();
// prefix
sql.append("ALTER TABLE ")
.append(schemaName).append(".").append(tableName).append(" "
+ "ADD CONSTRAINT ").append(keyName).append( " "
+ "PRIMARY KEY (");
// columns
for (int i = 0; i < keyColumns.size() ; i++) {
String columnName = keyColumns.get(i);
if (i>0)
sql.append(", ");
sql.append(columnName);
}
// suffix
// (postgresql can not defer primary keys)
sql.append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createForeignKey(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.lang.String, java.util.ArrayList, java.lang.String, java.lang.String, java.lang.String, boolean, boolean)
*/
public String sqlObject_createForeignKey(String catalogName, String schemaName, String keyName, String localTable, ArrayList<String> localColumns, String foreignTable, ArrayList<String> foreignColumns, String matchType, String onDelete, String onUpdate, boolean isDeferrable, boolean isDeferred) {
StringBuffer sql = new StringBuffer();
// prefix
sql.append("ALTER TABLE ")
.append(schemaName).append(".").append(localTable).append(" "
+ "ADD CONSTRAINT ").append(keyName).append(" "
+ "FOREIGN KEY (");
// column lists
StringBuffer localKeys = new StringBuffer();
StringBuffer foreignKeys = new StringBuffer();
for (int i = 0; i < localColumns.size(); i++) {
String localKey = localColumns.get(i);
String foreignKey = foreignColumns.get(i);
if (i>0) {
localKeys.append(", ");
foreignKeys.append(", ");
}
localKeys.append(localKey);
foreignKeys.append(foreignKey);
}
sql.append(localKeys).append(") REFERENCES ").append(foreignTable).append(" (").append(foreignKeys);
// suffix
StringBuffer matchClause = new StringBuffer();
StringBuffer deleteClause = new StringBuffer();
StringBuffer updateClause = new StringBuffer();
String deferrable = "";
String deferred = "";
if (matchType!=null) {
if (matchType.equalsIgnoreCase("NONE"))
matchType = "SIMPLE";
matchClause.append("MATCH ").append(matchType).append(" ");
}
if (onDelete!=null)
deleteClause.append("ON DELETE ").append(onDelete).append(" ");
if (onUpdate!=null)
updateClause.append("ON UPDATE ").append(onUpdate).append(" ");
if (isDeferrable) {
deferrable = "DEFERRABLE ";
if (isDeferred)
deferred="INITIALLY DEFERRED ";
else
deferred="INITIALLY IMMEDIATE ";
} else {
deferrable = "NOT DEFERRABLE ";
}
sql.append(") ").append(matchClause).append(deleteClause).append(updateClause).append(deferrable).append(deferred);
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createCheck(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, boolean, boolean)
*/
public String sqlObject_createCheck(String catalogName, String schemaName, String tableName, String constraintName, ArrayList<String> expressions, boolean isDeferrable, boolean isDeferred) {
StringBuffer sql = new StringBuffer();
// prefix
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" ADD CONSTRAINT ").append(constraintName).append(" CHECK (");
// expressions
for (int i = 0; i < expressions.size(); i++) {
String expression = expressions.get(i);
if (i>0)
sql.append(", ");
sql.append(expression);
}
// suffix
// (postgresql can not defer check constraints)
sql.append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createUnique(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, boolean, boolean)
*/
public String sqlObject_createUnique(String catalogName, String schemaName, String tableName, String constraintName, ArrayList<String> columns, boolean isDeferrable, boolean isDeferred) {
StringBuffer sql = new StringBuffer();
// prefix
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" ADD CONSTRAINT ").append(constraintName). append(" UNIQUE (");
// column list
for (int i = 0; i < columns.size(); i++) {
String column = columns.get(i);
if (i>0)
sql.append(", ");
sql.append(column);
}
// suffix
// postgresql can not defer unique constraints
sql.append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropConstraint(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropConstraint(String catalogName, String schemaName, String constraintName, String tableName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName)
.append(" DROP CONSTRAINT ").append(constraintName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createIndex(java.lang.String, java.lang.String, java.lang.String, boolean, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList)
*/
public String sqlObject_createIndex(String catalogName, String schemaName, String tableName, boolean isUnique, String indexName, ArrayList<String> columnNames, ArrayList<String> directions, ArrayList<String> nullTreatments) {
StringBuffer sql = new StringBuffer();
// prefix
String unique="";
if (isUnique)
unique = "UNIQUE";
sql.append("CREATE ").append(unique).append(" INDEX ").append(indexName).append(" ON ").append(schemaName).append(".").append(tableName).append(" (");
// columns
for (int i = 0; i < columnNames.size(); i++) {
String columnName = columnNames.get(i);
String direction = directions.get(i);
String nullTreatment = nullTreatments.get(i);
StringBuffer nullExpression = new StringBuffer();
if (i>0)
sql.append(", ");
if (nullTreatment!=null)
nullExpression.append("NULLS ").append(nullTreatment).append(" ");
sql.append(columnName).append(" ").append(direction).append(" ").append(nullExpression);
}
// suffix
sql.append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropIndex(java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObject_dropIndex(String catalogName, String schemaName, String indexName) {
StringBuffer sql = new StringBuffer();
sql.append("DROP INDEX ").append(schemaName).append(".").append(indexName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_createTableColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_createColumn(String catalogName, String schemaName, String tableName, String columnName, String dataType, boolean isNullable, String defaultValue) {
StringBuffer sql = new StringBuffer();
String sqlNullable = "";
if (! isNullable)
sqlNullable = " NOT NULL";
StringBuffer sqlDefault = new StringBuffer();
if (defaultValue!=null)
sqlDefault.append(" DEFAULT ").append(defaultValue);
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ADD COLUMN ").append(columnName).append(" ")
.append(dataType).append(sqlDefault).append(sqlNullable).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropTableColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_dropColumn(String catalogName, String schemaName, String tableName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "DROP COLUMN ").append(columnName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_setTableColumnDefault(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_setColumnDefault(String catalogName, String schemaName, String tableName, String columnName, String defaultValue) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ALTER COLUMN ").append(columnName).append(" "
+ "SET DEFAULT ").append(defaultValue).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_dropTableColumnDefault(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_dropColumnDefault(String catalogName, String schemaName, String tableName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ALTER COLUMN ").append(columnName).append(" "
+ "DROP DEFAULT ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_setTableColumnNullable(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_setColumnNullable(String catalogName, String schemaName, String tableName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ALTER COLUMN ").append(columnName).append(" "
+ "DROP NOT NULL ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_setTableColumnNullable(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_dropColumnNullable(String catalogName, String schemaName, String tableName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ALTER COLUMN ").append(columnName).append(" "
+ "SET NOT NULL ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObject_prepareTableColumnNotNullable(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_prepareColumnNotNullable(String catalogName, String schemaName, String tableName, String columnName, String dataType, String defaultValue) {
StringBuffer sql = new StringBuffer();
sql.append("UPDATE ").append(schemaName).append(".").append(tableName).append(" "
+ "SET ").append(columnName).append(" = ").append(defaultValue).append(" "
+ "WHERE ").append(columnName).append(" IS NULL ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObjectDetail_modifyColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_modifyColumnType(String catalogName, String schemaName, String tableName, String columnName, String dataType) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ALTER COLUMN ").append(columnName).append(" "
+ "TYPE ").append(dataType).append(" "
+ "USING NULL ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObjectDetail_renameColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_renameColumn(String catalogName, String schemaName, String tableName, String columnName, String newName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "RENAME COLUMN ").append(columnName).append(" "
+ "TO ").append(newName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#getSQLColumnTempCreate(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_createTemporaryColumn(String catalogName, String schemaName, String tableName, String columnName, String dataType) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "ADD COLUMN ").append(columnName).append(" ")
.append(dataType).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObjectDetail_dropTemporaryColumn(java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_dropTemporaryColumn(String catalogName, String schemaName, String tableName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("ALTER TABLE ").append(schemaName).append(".").append(tableName).append(" "
+ "DROP COLUMN ").append(columnName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObjectDetail_saveTemporaryColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_saveTemporaryColumn(String catalogName, String schemaName, String tableName, String temporaryColumnName, String columnName, String dataType) {
StringBuffer sql = new StringBuffer();
sql.append("UPDATE ").append(schemaName).append(".").append(tableName).append(" "
+ "SET ").append(temporaryColumnName).append(" = "
+ "CAST (").append(columnName).append(" AS ").append(dataType).append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObjectDetail_restoreTemporaryColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_restoreTemporaryColumn(String vendorName, String catalogName, String schemaName, String tableName, String temporaryColumnName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("UPDATE ").append(schemaName).append(".").append(tableName).append(" "
+ "SET ").append(columnName).append(" = ").append(temporaryColumnName).append(" ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlObjectDetail_eraseColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlObjectDetail_eraseColumn(String catalogName, String schemaName, String tableName, String columnName) {
StringBuffer sql = new StringBuffer();
sql.append("UPDATE ").append(schemaName).append(".").append(tableName).append(" "
+ "SET ").append(columnName).append(" = NULL ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sql_select(java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList)
*/
public String sql_select(String catalogName, String schemaName, String tableName, String tableAlias, ArrayList<String> columnNames, ArrayList<String> aliasNames, ArrayList<String> joinTypes, ArrayList<String> joinTables, ArrayList<String> joinAliases, ArrayList<String> joinConditions, ArrayList<String> conditions, ArrayList<String> sortColumns, boolean isDistinct) {
StringBuffer sql = new StringBuffer() ;
// prefix
sql.append("SELECT ");
if (isDistinct)
sql.append("DISTINCT ");
// column list
if (columnNames == null)
sql.append("* ");
else {
for (int i = 0; i < columnNames.size(); i++) {
if (i>0)
sql.append(", ");
sql.append(columnNames.get(i));
if (aliasNames.get(i)!=null)
sql.append(" AS ").append(aliasNames.get(i));
}
sql.append(" ");
}
// table
sql.append("FROM ").append(schemaName).append(".").append(tableName).append(" ").append(tableAlias).append(" ");
// JOIN clause
if (joinTypes!=null && joinTypes.size()>0) {
for (int i = 0; i < joinTypes.size(); i++) {
String joinType = joinTypes.get(i);
String joinTable = joinTables.get(i);
String joinAlias = joinAliases.get(i);
String joinCondition = joinConditions.get(i);
if (sql!=null && sql.length()>0) {
sql.append(joinType).append(" ").append(schemaName).append(".").append(joinTable).append(" ")
.append(joinAlias).append(" ON (").append(joinCondition).append(") ");
}
}
}
// conditions
if (conditions!=null) {
for (int i = 0; i < conditions.size(); i++) {
if (i==0)
sql.append("WHERE ");
else
sql.append("AND ");
sql.append(conditions.get(i)).append(" ");
}
}
// order
if (sortColumns!=null) {
for (int i = 0; i < sortColumns.size(); i++) {
if (i==0)
sql.append("ORDER BY ");
else
sql.append(", ");
sql.append(sortColumns.get(i));
}
sql.append(" ");
}
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sql_update(java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList)
*/
public String sql_update(String catalogName, String schemaName, String tableName, String tableAlias, ArrayList<String> columnNames, ArrayList<String> values, ArrayList<String> conditions) {
StringBuffer sql = new StringBuffer();
for (int i = 0; i < columnNames.size(); i++) {
if (i==0)
sql.append("UPDATE ").append(schemaName).append(".").append(tableName).append(" ").append(tableAlias).append(" SET ");
else
sql.append(", ");
sql.append(columnNames.get(i)).append(" = ").append(values.get(i));
}
sql.append(" ");
StringBuffer condition = new StringBuffer();
if (conditions!=null) {
for (int i = 0; i < conditions.size(); i++) {
if (i==0)
condition.append("WHERE ");
else
condition.append("AND ");
condition.append(conditions.get(i));
}
}
if (sql!=null && sql.length()>0)
sql.append(condition);
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sql_delete(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Integer)
*/
public String sql_delete(String catalogName, String schemaName, String tableName, String tableAlias, ArrayList<String> conditions, Integer daysOld) {
StringBuffer sql = new StringBuffer();
sql.append("DELETE FROM ").append(schemaName).append(".").append(tableName).append(" ").append(tableAlias).append(" ");
// condition
if (conditions!=null && conditions.size()>0) {
for (int i = 0; i < conditions.size(); i++) {
if (i==0)
sql.append("WHERE ");
else
sql.append("AND ");
sql.append(conditions.get(i)).append(" ");
}
}
// age clause
if (daysOld!=null) {
if (conditions == null || conditions.size()==0)
sql.append("WHERE ");
else
sql.append("AND ");
sql.append("date_trunc('day', updated) < (date_trunc('day', now())::date - ").append(daysOld.toString()).append("::integer) ");
}
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sql_insert(java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList)
*/
public String sql_insert(String catalogName, String schemaName, String tableName, ArrayList<String> columnNames, ArrayList<String> columnValues) {
StringBuffer sql = new StringBuffer();
StringBuffer sqlValues = new StringBuffer();
for (int i = 0; i < columnNames.size(); i++) {
if (i==0) {
sql.append("INSERT INTO ").append(schemaName).append(".").append(tableName).append(" (");
sqlValues = new StringBuffer();
} else {
sql.append(", ");
sqlValues.append(", ");
}
sql.append(columnNames.get(i));
sqlValues.append(columnValues.get(i));
}
if (sql!=null && sql.length()>0) {
sql.append(") VALUES (").append(sqlValues).append(") ");
}
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sql_insertFromTable(java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.lang.String)
*/
public String sql_insertFromTable(String catalogName, String schemaName, String tableName, ArrayList<String> columnNames, ArrayList<String> columnValues, String sourceTableName, ArrayList<String> joinTypes, ArrayList<String> joinTables, ArrayList<String> joinConditions, String whereClause) {
StringBuffer sql = new StringBuffer();
// columns and values
StringBuffer sqlColumns = new StringBuffer();
StringBuffer sqlValues = new StringBuffer();
if (columnNames!=null && columnNames.size()>0) {
for (int i = 0; i < columnNames.size(); i++) {
if (i>0) {
sqlColumns.append(", ");
sqlValues.append(", ");
}
sqlColumns.append(columnNames.get(i));
sqlValues.append(columnValues.get(i));
}
}
// INSERT clause
sql.append("INSERT INTO ").append(schemaName).append(".").append(tableName).append(" (").append(sqlColumns).append(") ");
// SELECT clause
if (sql!=null && sql.length()>0) {
sql.append("SELECT DISTINCT ").append(sqlValues).append(" "
+ "FROM ").append(schemaName).append(".").append(sourceTableName).append(" t ");
}
// JOIN clause
if (joinTypes!=null && joinTypes.size()>0) {
for (int i = 0; i < joinTypes.size(); i++) {
String joinType = joinTypes.get(i);
String joinTable = joinTables.get(i);
String joinCondition = joinConditions.get(i);
if (sql!=null && sql.length()>0) {
sql.append(joinType).append(" ").append(schemaName).append(".").append(joinTable).append(" "
+ "t").append(i).append(" ON (").append(joinCondition).append(") ");
}
}
}
// WHERE clause
if (whereClause != null) {
if (sql!=null && sql.length()>0) {
sql.append("WHERE ").append(whereClause).append(" ");
}
}
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlADAction_updateTerminology(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, boolean, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList)
*/
public String sqlADAction_updateTerminology(
String catalogName, String schemaName, String targetTableName,
String sourceTableName, String targetTranslationName,
String sourceTranslationName, ArrayList<String> joinTableNames,
ArrayList<String> linkConditions,
ArrayList<String> extraTableNames,
ArrayList<String> extraConditions, boolean hasCentrallyMaintained,
ArrayList<String> updateColumns, ArrayList<String> updateValues,
ArrayList<String> updateConditions) {
StringBuffer sql = new StringBuffer();
StringBuffer whereClause = new StringBuffer();
// UPDATE clause
if (targetTranslationName==null) {
// base synchronization
sql.append("UPDATE ").append(schemaName).append(".").append(targetTableName).append(" tt ");
} else {
// translation synchronization
sql.append("UPDATE ").append(schemaName).append(".").append(targetTranslationName).append(" ttl ");
}
// SET clause
if ((updateColumns!=null && updateColumns.size()>0) && (updateValues!=null && updateValues.size()==updateColumns.size())) {
for (int i=0; i<updateColumns.size(); i++) {
if (i==0)
sql.append("SET ");
else
sql.append(", ");
sql.append(updateColumns.get(i)).append(" = ").append(updateValues.get(i));
}
sql.append(" ");
}
// FROM clause
if (targetTranslationName==null) {
// base synchronization
sql.append("FROM ").append(schemaName).append(".").append(sourceTableName).append(" ts");
} else {
// translation synchronization
sql.append("FROM ").append(schemaName).append(".").append(targetTableName).append(" tt, ")
.append(schemaName).append(".").append(sourceTableName).append(" ts, ")
.append(schemaName).append(".").append(sourceTranslationName).append(" tsl");
}
// JOIN tables
if (joinTableNames!=null && joinTableNames.size()>0) {
for (int index=0; index<joinTableNames.size(); index++) {
sql.append(", ").append(schemaName).append(".").append(joinTableNames.get(index)).append(" tj").append(index);
}
}
// EXTRA tables
if (extraTableNames!=null && extraTableNames.size()>0) {
for (int index=0; index<extraTableNames.size(); index++) {
sql.append(", ").append(schemaName).append(".").append(extraTableNames.get(index)).append(" tx").append(index);
}
}
sql.append(" ");
// WHERE clause
// JOIN conditions
if (linkConditions!=null && linkConditions.size()>0) {
for (int index = 0; index<linkConditions.size(); index++) {
if (whereClause.length()>0)
whereClause.append("AND ");
whereClause.append(linkConditions.get(index));
}
}
// EXTRA conditions
if (extraConditions!=null && extraConditions.size()>0) {
for (int index = 0; index<extraConditions.size(); index++) {
if (whereClause.length()>0)
whereClause.append("AND ");
whereClause.append(extraConditions.get(index));
}
}
// is centrally maintained?
if (hasCentrallyMaintained) {
if (whereClause.length()>0)
whereClause.append("AND ");
whereClause.append("tt.IsCentrallyMaintained = 'Y' ");
}
// update conditions
if (updateConditions!=null && updateConditions.size()>0) {
if (whereClause.length()>0)
whereClause.append("AND (");
else
whereClause.append("(");
for (int i=0; i<updateConditions.size(); i++) {
if (i>0)
whereClause.append("OR ");
whereClause.append(updateConditions.get(i));
}
whereClause.append(") ");
}
// append WHERE clause to SQL command
if (whereClause.length()>0)
sql.append("WHERE ").append(whereClause);
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlAction_purgeOrphans(java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList, java.util.ArrayList)
*/
public String sqlAction_purgeOrphans(String catalogName, String schemaName,
String localTableName, ArrayList<String> localColumnNames,
ArrayList<String> foreignKeyNames,
ArrayList<String> foreignTableNames,
ArrayList<String> foreignColumnNames) {
StringBuffer sql = new StringBuffer();
String lastForeignKeyName = "";
for (int i = 0; i < foreignColumnNames.size(); i++) {
String foreignKeyName = foreignKeyNames.get(i);
String foreignTableName = foreignTableNames.get(i);
String foreignColName = foreignColumnNames.get(i);
String localColName = localColumnNames.get(i);
if (foreignKeyName.equalsIgnoreCase(lastForeignKeyName)) {
sql.append(" AND ");
} else {
if (i==0) {
sql.append("DELETE FROM ").append(schemaName).append(".").append(localTableName).append(" lcltbl WHERE ");
} else {
sql.append(") OR ");
}
sql.append("NOT EXISTS (SELECT 1 FROM ").append(schemaName).append(".").append(foreignTableName).append( " frntbl WHERE ");
lastForeignKeyName = foreignKeyName;
}
sql.append("lcltbl.").append(localColName).append(" = frntbl.").append(foreignColName);
}
if (sql!=null && sql.length()>0)
sql.append(") ");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlAction_dropDuplicates(java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList)
*/
public String sqlAction_dropDuplicates(String catalogName,
String schemaName, String tableName,
ArrayList<String> keyColumnNames) {
StringBuffer sql = new StringBuffer();
sql.append("DELETE FROM ").append(schemaName).append(".").append(tableName)
.append(" t1 WHERE EXISTS (SELECT 1 FROM ")
.append(schemaName).append(".").append(tableName)
.append(" t2 WHERE ");
for (int i = 0; i < keyColumnNames.size(); i++) {
String columnName = keyColumnNames.get(i);
if (i>0)
sql.append("AND ");
sql.append("t2.").append(columnName).append(" = t1.").append(columnName).append(" ");
}
sql.append(" AND t2.ctid < t1.ctid)");
return sql.toString();
}
/* (non-Javadoc)
* @see com.kkalice.adempiere.migrate.DBEngineInterface#sqlAction_enforceCheckConstraints(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public String sqlAction_enforceCheckConstraints(String catalogName, String schemaName, String tableName, String checkExpression) {
StringBuffer sql = new StringBuffer();
// extract column name, operator, and value
String pattern = "(?i).*?(\\b\\w*\\b).*?([<=>!]+|(\\bNOT\\s+)?LIKE\\b).*?('\\w*'|\\d+|\\bNULL\\b).*";
// extract the last word before first operator as column name
String columnName = checkExpression.replaceAll(pattern, "$1");
if (columnName.equalsIgnoreCase(checkExpression))
columnName=null;
// extract the first operator
String operator = checkExpression.replaceAll(pattern, "$2").toUpperCase();
if (operator.equalsIgnoreCase(checkExpression))
operator=null;
// extract the first string or number or NULL after first operator as value
String value = checkExpression.replaceAll(pattern, "$4");
if (value.equalsIgnoreCase(checkExpression))
value=null;
// only continue if extraction of column name, operator and value was successful
if (columnName!=null && operator!=null && value!=null) {
// we can only determine default values for equality operators
// (< or > are permissible only as <= or >=)
if (operator.contains("=") || operator.contains("LIKE")) {
// we can not dtermine default values for NOT operators
// (!= or NOT LIKE are not permissable)
if (! (operator.contains("!") || operator.contains("NOT"))) {
// build the sql string
sql.append("UPDATE ").append(schemaName).append(".").append(tableName).append(" "
+ "SET ").append(columnName).append(" = ").append(value).append(" "
+ "WHERE NOT (").append(checkExpression).append(") ");
}
}
}
if (sql!=null && sql.length()>0)
return sql.toString();
else
return null;
}
}
| gpl-2.0 |
lichtl/darkstar | scripts/zones/Lufaise_Meadows/mobs/Kurrea.lua | 574 | -----------------------------------
-- Area: Lufaise Meadows
-- MOB: Kurrea
-----------------------------------
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- OnMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
GetNPCByID(16875886):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME);
end; | gpl-3.0 |
iproduct/course-angular2 | 05-webstore-lab6/src/app/products/products.service.spec.ts | 343 | import { TestBed } from '@angular/core/testing';
import { ProductsService } from './products.service';
describe('ProductsService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: ProductsService = TestBed.get(ProductsService);
expect(service).toBeTruthy();
});
});
| gpl-3.0 |
vins-87/Skynet3DAnetA8 | Marlin/watchdog.cpp | 2091 | /**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
#include "Marlin.h"
#if ENABLED(USE_WATCHDOG)
#include "watchdog.h"
// Initialize watchdog with a 4 sec interrupt time
void watchdog_init() {
#if ENABLED(WATCHDOG_RESET_MANUAL)
// We enable the watchdog timer, but only for the interrupt.
// Take care, as this requires the correct order of operation, with interrupts disabled. See the datasheet of any AVR chip for details.
wdt_reset();
_WD_CONTROL_REG = _BV(_WD_CHANGE_BIT) | _BV(WDE);
_WD_CONTROL_REG = _BV(WDIE) | WDTO_4S;
#else
wdt_enable(WDTO_4S);
#endif
}
//===========================================================================
//=================================== ISR ===================================
//===========================================================================
// Watchdog timer interrupt, called if main program blocks >4sec and manual reset is enabled.
#if ENABLED(WATCHDOG_RESET_MANUAL)
ISR(WDT_vect) {
SERIAL_ERROR_START;
SERIAL_ERRORLNPGM("Something is wrong, please turn off the printer.");
kill(PSTR("ERR:Please Reset")); //kill blocks //16 characters so it fits on a 16x2 display
while (1); //wait for user or serial reset
}
#endif // WATCHDOG_RESET_MANUAL
#endif // USE_WATCHDOG
| gpl-3.0 |
alexanderturner/ansible | lib/ansible/modules/cloud/smartos/vmadm.py | 24627 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Jasper Lievisse Adriaanse <j@jasper.la>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: vmadm
short_description: Manage SmartOS virtual machines and zones.
description:
- Manage SmartOS virtual machines through vmadm(1M).
version_added: "2.3"
author: Jasper Lievisse Adriaanse (@jasperla)
options:
archive_on_delete:
required: false
description:
- When enabled, the zone dataset will be mounted on C(/zones/archive)
upon removal.
autoboot:
required: false
description:
- Whether or not a VM is booted when the system is rebooted.
brand:
required: true
choices: [ joyent, joyent-minimal, kvm, lx ]
default: joyent
description:
- Type of virtual machine.
boot:
required: false
description:
- Set the boot order for KVM VMs.
cpu_cap:
required: false
description:
- Sets a limit on the amount of CPU time that can be used by a VM.
Use C(0) for no cap.
cpu_shares:
required: false
description:
- Sets a limit on the number of fair share scheduler (FSS) CPU shares for
a VM. This limit is relative to all other VMs on the system.
cpu_type:
required: false
choices: [ qemu64, host ]
default: qemu64
description:
- Control the type of virtual CPU exposed to KVM VMs.
customer_metadata:
required: false
description:
- Metadata to be set and associated with this VM, this contain customer
modifiable keys.
delegate_dataset:
required: false
description:
- Whether to delegate a ZFS dataset to an OS VM.
disk_driver:
required: false
description:
- Default value for a virtual disk model for KVM guests.
disks:
required: false
description:
- A list of disks to add, valid properties are documented in vmadm(1M).
dns_domain:
required: false
description:
- Domain value for C(/etc/hosts).
filesystems:
required: false
description:
- Mount additional filesystems into an OS VM.
firewall_enabled:
required: false
description:
- Enables the firewall, allowing fwadm(1M) rules to be applied.
force:
required: false
description:
- Force a particular action (i.e. stop or delete a VM).
fs_allowed:
required: false
description:
- Comma separated list of filesystem types this zone is allowed to mount.
hostname:
required: false
description:
- Zone/VM hostname.
image_uuid:
required: false
description:
- Image UUID.
indestructible_delegated:
required: false
description:
- Adds an C(@indestructible) snapshot to delegated datasets.
indestructible_zoneroot:
required: false
description:
- Adds an C(@indestructible) snapshot to zoneroot.
internal_metadata:
required: false
description:
- Metadata to be set and associated with this VM, this contains operator
generated keys.
internal_metadata_namespace:
required: false
description:
- List of namespaces to be set as I(internal_metadata-only); these namespaces
will come from I(internal_metadata) rather than I(customer_metadata).
kernel_version:
required: false
description:
- Kernel version to emulate for LX VMs.
limit_priv:
required: false
description:
- Set (comma separated) list of privileges the zone is allowed to use.
maintain_resolvers:
required: false
description:
- Resolvers in C(/etc/resolv.conf) will be updated when updating
the I(resolvers) property.
max_locked_memory:
required: false
description:
- Total amount of memory (in MiBs) on the host that can be locked by this VM.
max_lwps:
required: false
description:
- Maximum number of lightweight processes this VM is allowed to have running.
max_physical_memory:
required: false
description:
- Maximum amount of memory (in MiBs) on the host that the VM is allowed to use.
max_swap:
required: false
description:
- Maximum amount of virtual memory (in MiBs) the VM is allowed to use.
mdata_exec_timeout:
required: false
description:
- Timeout in seconds (or 0 to disable) for the C(svc:/smartdc/mdata:execute) service
that runs user-scripts in the zone.
name:
required: false
aliases: [ alias ]
description:
- Name of the VM. vmadm(1M) uses this as an optional name.
nic_driver:
required: false
description:
- Default value for a virtual NIC model for KVM guests.
nics:
required: false
description:
- A list of nics to add, valid properties are documented in vmadm(1M).
nowait:
required: false
description:
- Consider the provisioning complete when the VM first starts, rather than
when the VM has rebooted.
qemu_opts:
required: false
description:
- Additional qemu arguments for KVM guests. This overwrites the default arguments
provided by vmadm(1M) and should only be used for debugging.
qemu_extra_opts:
required: false
description:
- Additional qemu cmdline arguments for KVM guests.
quota:
required: false
description:
- Quota on zone filesystems (in MiBs).
ram:
required: false
description:
- Amount of virtual RAM for a KVM guest (in MiBs).
resolvers:
required: false
description:
- List of resolvers to be put into C(/etc/resolv.conf).
routes:
required: false
description:
- Dictionary that maps destinations to gateways, these will be set as static
routes in the VM.
spice_opts:
required: false
description:
- Addition options for SPICE-enabled KVM VMs.
spice_password:
required: false
description:
- Password required to connect to SPICE. By default no password is set.
Please note this can be read from the Global Zone.
state:
required: true
choices: [ present, absent, stopped, restarted ]
description:
- States for the VM to be in. Please note that C(present), C(stopped) and C(restarted)
operate on a VM that is currently provisioned. C(present) means that the VM will be
created if it was absent, and that it will be in a running state. C(absent) will
shutdown the zone before removing it.
C(stopped) means the zone will be created if it doesn't exist already, before shutting
it down.
tmpfs:
required: false
description:
- Amount of memory (in MiBs) that will be available in the VM for the C(/tmp) filesystem.
uuid:
required: false
description:
- UUID of the VM. Can either be a full UUID or C(*) for all VMs.
vcpus:
required: false
description:
- Number of virtual CPUs for a KVM guest.
vga:
required: false
description:
- Specify VGA emulation used by KVM VMs.
virtio_txburst:
required: false
description:
- Number of packets that can be sent in a single flush of the tx queue of virtio NICs.
virtio_txtimer:
required: false
description:
- Timeout (in nanoseconds) for the TX timer of virtio NICs.
vnc_password:
required: false
description:
- Password required to connect to VNC. By default no password is set.
Please note this can be read from the Global Zone.
vnc_port:
required: false
description:
- TCP port to listen of the VNC server. Or set C(0) for random,
or C(-1) to disable.
zfs_data_compression:
required: false
description:
- Specifies compression algorithm used for this VMs data dataset. This option
only has effect on delegated datasets.
zfs_data_recsize:
required: false
description:
- Suggested block size (power of 2) for files in the delegated dataset's filesystem.
zfs_filesystem_limit:
required: false
description:
- Maximum number of filesystems the VM can have.
zfs_io_priority:
required: false
description:
- IO throttle priority value relative to other VMs.
zfs_root_compression:
required: false
description:
- Specifies compression algorithm used for this VMs root dataset. This option
only has effect on the zoneroot dataset.
zfs_root_recsize:
required: false
description:
- Suggested block size (power of 2) for files in the zoneroot dataset's filesystem.
zfs_snapshot_limit:
required: false
description:
- Number of snapshots the VM can have.
zpool:
required: false
description:
- ZFS pool the VM's zone dataset will be created in.
requirements:
- python >= 2.6
'''
EXAMPLES = '''
- name: create SmartOS zone
vmadm:
brand: joyent
state: present
alias: fw_zone
image_uuid: 95f265b8-96b2-11e6-9597-972f3af4b6d5
firewall_enabled: yes
indestructible_zoneroot: yes
nics:
- nic_tag: admin
ip: dhcp
primary: true
internal_metadata:
root_pw: 'secret'
quota: 1
- name: Delete a zone
vmadm:
alias: test_zone
state: deleted
- name: Stop all zones
vmadm:
uuid: '*'
state: stopped
'''
RETURN = '''
uuid:
description: UUID of the managed VM.
returned: always
type: string
sample: 'b217ab0b-cf57-efd8-cd85-958d0b80be33'
alias:
description: Alias of the managed VM.
returned: When addressing a VM by alias.
type: string
sample: 'dns-zone'
state:
description: State of the target, after execution.
returned: success
type: string
sample: 'running'
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils._text import to_native
import os
import re
import tempfile
import traceback
try:
import json
except ImportError:
import simplejson as json
# While vmadm(1M) supports a -E option to return any errors in JSON, the
# generated JSON does not play well with the JSON parsers of Python.
# The returned message contains '\n' as part of the stacktrace,
# which breaks the parsers.
def get_vm_prop(module, uuid, prop):
# Lookup a property for the given VM.
# Returns the property, or None if not found.
cmd = '{0} lookup -j -o {1} uuid={2}'.format(module.vmadm, prop, uuid)
(rc, stdout, stderr) = module.run_command(cmd)
if rc != 0:
module.fail_json(
msg='Could not perform lookup of {0} on {1}'.format(prop, uuid), exception=stderr)
try:
stdout_json = json.loads(stdout)
except:
e = get_exception()
module.fail_json(
msg='Invalid JSON returned by vmadm for uuid lookup of {0}'.format(alias),
details=to_native(e))
if len(stdout_json) > 0 and prop in stdout_json[0]:
return stdout_json[0][prop]
else:
return None
def get_vm_uuid(module, alias):
# Lookup the uuid that goes with the given alias.
# Returns the uuid or '' if not found.
cmd = '{0} lookup -j -o uuid alias={1}'.format(module.vmadm, alias)
(rc, stdout, stderr) = module.run_command(cmd)
if rc != 0:
module.fail_json(
msg='Could not retrieve UUID of {0}'.format(alias), exception=stderr)
# If no VM was found matching the given alias, we get back an empty array.
# That is not an error condition as we might be explicitly checking it's
# absence.
if stdout.strip() == '[]':
return None
else:
try:
stdout_json = json.loads(stdout)
except:
e = get_exception()
module.fail_json(
msg='Invalid JSON returned by vmadm for uuid lookup of {0}'.format(alias),
details=to_native(e))
if len(stdout_json) > 0 and 'uuid' in stdout_json[0]:
return stdout_json[0]['uuid']
def get_all_vm_uuids(module):
# Retrieve the UUIDs for all VMs.
cmd = '{0} lookup -j -o uuid'.format(module.vmadm)
(rc, stdout, stderr) = module.run_command(cmd)
if rc != 0:
module.fail_json(msg='Failed to get VMs list', exception=stderr)
try:
stdout_json = json.loads(stdout)
return [v['uuid'] for v in stdout_json]
except:
e = get_exception()
module.fail_json(msg='Could not retrieve VM UUIDs', details=to_native(e))
def new_vm(module, uuid, vm_state):
payload_file = create_payload(module, uuid)
(rc, stdout, stderr) = vmadm_create_vm(module, payload_file)
if rc != 0:
changed = False
module.fail_json(msg='Could not create VM', exception=stderr)
else:
changed = True
# 'vmadm create' returns all output to stderr...
match = re.match('Successfully created VM (.*)', stderr)
if match:
vm_uuid = match.groups()[0]
if not is_valid_uuid(vm_uuid):
module.fail_json(msg='Invalid UUID for VM {0}?'.format(vm_uuid))
else:
module.fail_json(msg='Could not retrieve UUID of newly created(?) VM')
# Now that the VM is created, ensure it is in the desired state (if not 'running')
if vm_state != 'running':
ret = set_vm_state(module, vm_uuid, vm_state)
if not ret:
module.fail_json(msg='Could not set VM {0} to state {1}'.format(vm_uuid, vm_state))
try:
os.unlink(payload_file)
except Exception as e:
# Since the payload may contain sensitive information, fail hard
# if we cannot remove the file so the operator knows about it.
module.fail_json(
msg='Could not remove temporary JSON payload file {0}'.format(payload_file),
exception=traceback.format_exc(e))
return changed, vm_uuid
def vmadm_create_vm(module, payload_file):
# Create a new VM using the provided payload.
cmd = '{0} create -f {1}'.format(module.vmadm, payload_file)
return module.run_command(cmd)
def set_vm_state(module, vm_uuid, vm_state):
p = module.params
# Check if the VM is already in the desired state.
state = get_vm_prop(module, vm_uuid, 'state')
if state and (state == vm_state):
return None
# Lookup table for the state to be in, and which command to use for that.
# vm_state: [vmadm commandm, forceable?]
cmds = {
'stopped': ['stop', True],
'running': ['start', False],
'deleted': ['delete', True],
'rebooted': ['reboot', False]
}
if p['force'] and cmds[vm_state][1]:
force = '-F'
else:
force = ''
cmd = 'vmadm {0} {1} {2}'.format(cmds[vm_state][0], force, vm_uuid)
(rc, stdout, stderr) = module.run_command(cmd)
match = re.match('^Successfully.*', stderr)
if match:
return True
else:
return False
def create_payload(module, uuid):
# Create the JSON payload (vmdef) and return the filename.
p = module.params
# Filter out the few options that are not valid VM properties.
module_options = ['debug', 'force', 'state']
vmattrs = filter(lambda prop: prop not in module_options, p)
vmdef = {}
for attr in vmattrs:
if p[attr]:
vmdef[attr] = p[attr]
try:
vmdef_json = json.dumps(vmdef)
except Exception as e:
module.fail_json(
msg='Could not create valid JSON payload', exception=traceback.format_exc(e))
# Create the temporary file that contains our payload, and set tight
# permissions for it may container sensitive information.
try:
# XXX: When there's a way to get the current ansible temporary directory
# drop the mkstemp call and rely on ANSIBLE_KEEP_REMOTE_FILES to retain
# the payload (thus removing the `save_payload` option).
fname = tempfile.mkstemp()[1]
fh = open(fname, 'w')
os.chmod(fname, 0o400)
fh.write(vmdef_json)
fh.close()
except Exception as e:
module.fail_json(
msg='Could not save JSON payload', exception=traceback.format_exc(e))
return fname
def vm_state_transition(module, uuid, vm_state):
ret = set_vm_state(module, uuid, vm_state)
# Whether the VM changed state.
if ret is None:
return False
elif ret:
return True
else:
module.fail_json(msg='Failed to set VM {0} to state {1}'.format(uuid, vm_state))
def is_valid_uuid(uuid):
if re.match('^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$', uuid, re.IGNORECASE):
return True
else:
return False
def validate_uuids(module):
# Perform basic UUID validation.
failed = []
for u in [['uuid', module.params['uuid']],
['image_uuid', module.params['image_uuid']]]:
if u[1] and u[1] != '*':
if not is_valid_uuid(u[1]):
failed.append(u[0])
if len(failed) > 0:
module.fail_json(msg='No valid UUID(s) found for: {0}'.format(", ".join(failed)))
def manage_all_vms(module, vm_state):
# Handle operations for all VMs, which can by definition only
# be state transitions.
state = module.params['state']
if state == 'created':
module.fail_json(msg='State "created" is only valid for tasks with a single VM')
# If any of the VMs has a change, the task as a whole has a change.
any_changed = False
# First get all VM uuids and for each check their state, and adjust it if needed.
for uuid in get_all_vm_uuids(module):
current_vm_state = get_vm_prop(module, uuid, 'state')
if not current_vm_state and vm_state == 'deleted':
any_changed = False
else:
if module.check_mode:
if (not current_vm_state) or (get_vm_prop(module, uuid, 'state') != state):
any_changed = True
else:
any_changed = (vm_state_transition(module, uuid, vm_state) | any_changed)
return any_changed
def main():
# In order to reduce the clutter and boilerplate for trivial options,
# abstract the vmadm properties and build the dict of arguments later.
# Dict of all options that are simple to define based on their type.
# They're not required and have a default of None.
properties = {
'str': [
'boot', 'disk_driver', 'dns_domain', 'fs_allowed', 'hostname',
'image_uuid', 'internal_metadata_namespace', 'kernel_version',
'limit_priv', 'nic_driver', 'qemu_opts', 'qemu_extra_opts',
'spice_opts', 'uuid', 'vga', 'zfs_data_compression',
'zfs_root_compression', 'zpool'
],
'bool': [
'archive_on_delete', 'autoboot', 'debug', 'delegate_dataset',
'firewall_enabled', 'force', 'indestructible_delegated',
'indestructible_zoneroot', 'maintain_resolvers', 'nowait'
],
'int': [
'cpu_cap', 'cpu_shares', 'max_locked_memory', 'max_lwps',
'max_physical_memory', 'max_swap', 'mdata_exec_timeout',
'quota', 'ram', 'tmpfs', 'vcpus', 'virtio_txburst',
'virtio_txtimer', 'vnc_port', 'zfs_data_recsize',
'zfs_filesystem_limit', 'zfs_io_priority', 'zfs_root_recsize',
'zfs_snapshot_limit'
],
'dict': ['customer_metadata', 'internal_metadata', 'routes'],
'list': ['disks', 'nics', 'resolvers', 'filesystems']
}
# Start with the options that are not as trivial as those above.
options = dict(
state=dict(
default='running',
type='str',
choices=['present', 'running', 'absent', 'deleted', 'stopped', 'created', 'restarted', 'rebooted']
),
name=dict(
default=None, type='str',
aliases=['alias']
),
brand=dict(
default='joyent',
type='str',
choices=['joyent', 'joyent-minimal', 'kvm', 'lx']
),
cpu_type=dict(
default='qemu64',
type='str',
choices=['host','qemu64']
),
# Regular strings, however these require additional options.
spice_password=dict(type='str', no_log=True),
vnc_password=dict(type='str', no_log=True),
)
# Add our 'simple' options to options dict.
for type in properties:
for p in properties[type]:
option = dict(default=None, type=type)
options[p] = option
module = AnsibleModule(
argument_spec=options,
supports_check_mode=True,
required_one_of=[['name', 'uuid']]
)
module.vmadm = module.get_bin_path('vmadm', required=True)
p = module.params
uuid = p['uuid']
state = p['state']
# Translate the state paramter into something we can use later on.
if state in ['present', 'running']:
vm_state = 'running'
elif state in ['stopped', 'created']:
vm_state = 'stopped'
elif state in ['absent', 'deleted']:
vm_state = 'deleted'
elif state in ['restarted', 'rebooted']:
vm_state = 'rebooted'
result = {'state': state}
# While it's possible to refer to a given VM by it's `alias`, it's easier
# to operate on VMs by their UUID. So if we're not given a `uuid`, look
# it up.
if not uuid:
uuid = get_vm_uuid(module, p['name'])
# Bit of a chicken and egg problem here for VMs with state == deleted.
# If they're going to be removed in this play, we have to lookup the
# uuid. If they're already deleted there's nothing to looup.
# So if state == deleted and get_vm_uuid() returned '', the VM is already
# deleted and there's nothing else to do.
if uuid is None and vm_state == 'deleted':
result['name'] = p['name']
module.exit_json(**result)
validate_uuids(module)
if p['name']:
result['name'] = p['name']
result['uuid'] = uuid
if uuid == '*':
result['changed'] = manage_all_vms(module, vm_state)
module.exit_json(**result)
# The general flow is as follows:
# - first the current state of the VM is obtained by it's UUID.
# - If the state was not found and the desired state is 'deleted', return.
# - If the state was not found, it means the VM has to be created.
# Subsequently the VM will be set to the desired state (i.e. stopped)
# - Otherwise, it means the VM exists already and we operate on it's
# state (i.e. reboot it.)
#
# In the future it should be possible to query the VM for a particular
# property as a valid state (i.e. queried) so the result can be
# registered.
# Also, VMs should be able to get their properties updated.
# Managing VM snapshots should be part of a standalone module.
# First obtain the VM state to determine what needs to be done with it.
current_vm_state = get_vm_prop(module, uuid, 'state')
# First handle the case where the VM should be deleted and is not present.
if not current_vm_state and vm_state == 'deleted':
result['changed'] = False
elif module.check_mode:
# Shortcut for check mode, if there is no VM yet, it will need to be created.
# Or, if the VM is not in the desired state yet, it needs to transition.
if (not current_vm_state) or (get_vm_prop(module, uuid, 'state') != state):
result['changed'] = True
else:
result['changed'] = False
module.exit_json(**result)
# No VM was found that matched the given ID (alias or uuid), so we create it.
elif not current_vm_state:
result['changed'], result['uuid'] = new_vm(module, uuid, vm_state)
else:
# VM was found, operate on its state directly.
result['changed'] = vm_state_transition(module, uuid, vm_state)
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
sourcefabric/airtime | python_apps/media-monitor/mm2/media/monitor/config.py | 1072 | # -*- coding: utf-8 -*-
import os
import copy
from configobj import ConfigObj
from exceptions import NoConfigFile, ConfigAccessViolation
import pure as mmp
class MMConfig(object):
def __init__(self, path):
if not os.path.exists(path): raise NoConfigFile(path)
self.cfg = ConfigObj(path)
def __getitem__(self, key):
""" We always return a copy of the config item to prevent
callers from doing any modifications through the returned
objects methods """
return copy.deepcopy(self.cfg[key])
def __setitem__(self, key, value):
""" We use this method not to allow anybody to mess around with
config file any settings made should be done through MMConfig's
instance methods """
raise ConfigAccessViolation(key)
def save(self): self.cfg.write()
def last_ran(self):
""" Returns the last time media monitor was ran by looking at
the time when the file at 'index_path' was modified """
return mmp.last_modified(self.cfg['media-monitor']['index_path'])
| agpl-3.0 |
soul2zimate/wildfly-core | patching/src/main/java/org/jboss/as/patching/installation/AddOn.java | 2083 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.patching.installation;
/**
*
* Add-on target info layout:
*
* <pre><code>
*
* ${JBOSS_HOME}
* |-- bundles
* | `-- system
* | `-- add-ons
* | `-- <name> => {@link org.jboss.as.patching.DirectoryStructure#getBundleRepositoryRoot()}
* | `-- patches
* | `-- <patchId> => {@link org.jboss.as.patching.DirectoryStructure#getBundlesPatchDirectory(String)}
* |-- modules
* | `-- system
* | `-- add-ons
* | `-- <name> => {@link org.jboss.as.patching.DirectoryStructure#getModuleRoot()}
* | `-- patches
* | `-- <patchId> => {@link org.jboss.as.patching.DirectoryStructure#getModulePatchDirectory(String)}
* `-- .installation
* `-- patches
* `-- add-ons
* `-- <name>
* `-- layers.conf => {@link org.jboss.as.patching.DirectoryStructure#getInstallationInfo()}
* <code>
* </pre>
*
* @author Emanuel Muckenhuber
*/
public interface AddOn extends PatchableTarget {
}
| lgpl-2.1 |
sunblithe/qt-everywhere-opensource-src-4.7.1 | src/3rdparty/webkit/WebCore/bindings/js/JSDebugWrapperSet.cpp | 1884 | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSDebugWrapperSet.h"
#include <wtf/StdLibExtras.h>
#if ENABLE(WORKERS)
#include <wtf/ThreadSpecific.h>
#endif
namespace WebCore {
JSDebugWrapperSet& JSDebugWrapperSet::shared()
{
#if ENABLE(WORKERS)
DEFINE_STATIC_LOCAL(WTF::ThreadSpecific<JSDebugWrapperSet>, staticWrapperSet, ());
return *staticWrapperSet;
#else
DEFINE_STATIC_LOCAL(JSDebugWrapperSet, staticWrapperSet, ());
return staticWrapperSet;
#endif
}
JSDebugWrapperSet::JSDebugWrapperSet()
{
}
} // namespace WebCore
| lgpl-2.1 |
elgambitero/FreeCAD_sf_master | src/Mod/Fem/Gui/Resources/translations/Fem_pl.ts | 37373 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="pl" sourcelanguage="en">
<context>
<name>CmdFemAddPart</name>
<message>
<location filename="../../Command.cpp" line="+183"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Add a part to the Analysis</source>
<translation type="unfinished">Dodaj część do analizy</translation>
</message>
</context>
<context>
<name>CmdFemConstraintBearing</name>
<message>
<location line="+65"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM bearing constraint</source>
<translation type="unfinished">Utwórz wiązania MES łożysk</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a bearing</source>
<translation type="unfinished">Stwórz wiązania MES dla łożyska</translation>
</message>
</context>
<context>
<name>CmdFemConstraintFixed</name>
<message>
<location line="+36"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM fixed constraint</source>
<translation type="unfinished">Stwórz stałe wiązanie MES</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a fixed geometric entity</source>
<translation type="unfinished">Utwórz wiązanie MES dla stałego obiektu geometrycznego</translation>
</message>
</context>
<context>
<name>CmdFemConstraintForce</name>
<message>
<location line="+36"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM force constraint</source>
<translation type="unfinished">Utwórz wiązania MES siły</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a force acting on a geometric entity</source>
<translation type="unfinished">Stwórz wiązanie MES dla siły oddziaływającej na obiekt geometryczny</translation>
</message>
</context>
<context>
<name>CmdFemConstraintGear</name>
<message>
<location line="+37"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM gear constraint</source>
<translation type="unfinished">Utwórz wiązania MES przekładni</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a gear</source>
<translation type="unfinished">Utwórz wiązania MES dla przekładni</translation>
</message>
</context>
<context>
<name>CmdFemConstraintPulley</name>
<message>
<location line="+36"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM pulley constraint</source>
<translation type="unfinished">Utwórz wiązania MES koła pasowego</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM constraint for a pulley</source>
<translation type="unfinished">Utwórz wiązania MES dla koła pasowego</translation>
</message>
</context>
<context>
<name>CmdFemCreateAnalysis</name>
<message>
<location line="-286"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Create a FEM analysis</source>
<translation type="unfinished">Utwórz analizę metodą FEM</translation>
</message>
</context>
<context>
<name>CmdFemCreateFromShape</name>
<message>
<location line="-31"/>
<source>Fem</source>
<translation>Mes</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM mesh</source>
<translation>Tworzenie siatki MES</translation>
</message>
<message>
<location line="+1"/>
<source>Create FEM mesh from shape</source>
<translation>Tworzenie siatki MES z kształtu</translation>
</message>
</context>
<context>
<name>CmdFemCreateNodesSet</name>
<message>
<location line="+500"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Define/create a nodes set...</source>
<translation type="unfinished">Zdefiniuj/utwórz system węzłów...</translation>
</message>
</context>
<context>
<name>CmdFemDefineNodesSet</name>
<message>
<location line="-59"/>
<source>Fem</source>
<translation type="unfinished">Mes</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<location line="+2"/>
<source>Create node set by Poly</source>
<translation type="unfinished">Utwórz system węzłów metodą Poly</translation>
</message>
</context>
<context>
<name>FemGui::HypothesisWidget</name>
<message>
<location filename="../../Hypothesis.ui" line="+14"/>
<source>Hypothesis</source>
<translation>Hipoteza</translation>
</message>
<message>
<location line="+8"/>
<source>Quadrangle</source>
<translation>Kwadratura</translation>
</message>
<message>
<location line="+10"/>
<source>Maximum length</source>
<translation>Maksymalna długość</translation>
</message>
<message>
<location line="+20"/>
<source>Local length</source>
<translation>Długość lokalna</translation>
</message>
<message>
<location line="+20"/>
<source>Maximum element area</source>
<translation>Maksymalny obszar elementu</translation>
</message>
</context>
<context>
<name>FemGui::TaskAnalysisInfo</name>
<message>
<location filename="../../TaskAnalysisInfo.cpp" line="+45"/>
<source>Nodes set</source>
<translation type="unfinished">System węzłów</translation>
</message>
</context>
<context>
<name>FemGui::TaskCreateNodeSet</name>
<message>
<location filename="../../TaskCreateNodeSet.cpp" line="+63"/>
<source>Nodes set</source>
<translation type="unfinished">System węzłów</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraint</name>
<message>
<location filename="../../TaskFemConstraint.cpp" line="+184"/>
<location line="+11"/>
<source>Input error</source>
<translation type="unfinished">Błąd danych wejściowych</translation>
</message>
<message>
<location line="-11"/>
<source>You must specify at least one reference</source>
<translation type="unfinished">Należy określić co najmniej jedno odniesienie</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintBearing</name>
<message>
<location filename="../../TaskFemConstraintBearing.cpp" line="+349"/>
<source>Input error</source>
<translation type="unfinished">Błąd danych wejściowych</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintForce</name>
<message>
<location filename="../../TaskFemConstraintForce.cpp" line="+365"/>
<source>Input error</source>
<translation type="unfinished">Błąd danych wejściowych</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintGear</name>
<message>
<location filename="../../TaskFemConstraintGear.cpp" line="+308"/>
<source>Input error</source>
<translation type="unfinished">Błąd danych wejściowych</translation>
</message>
</context>
<context>
<name>FemGui::TaskDlgFemConstraintPulley</name>
<message>
<location filename="../../TaskFemConstraintPulley.cpp" line="+203"/>
<source>Input error</source>
<translation type="unfinished">Błąd danych wejściowych</translation>
</message>
</context>
<context>
<name>FemGui::TaskDriver</name>
<message>
<location filename="../../TaskDriver.cpp" line="+51"/>
<source>Nodes set</source>
<translation type="unfinished">System węzłów</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraint</name>
<message>
<location filename="../../TaskFemConstraint.cpp" line="-120"/>
<source>FEM constraint parameters</source>
<translation type="unfinished">Parametry ograniczeń FEM</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintBearing</name>
<message>
<location filename="../../TaskFemConstraintBearing.cpp" line="-274"/>
<source>Delete</source>
<translation type="unfinished">Usuń</translation>
</message>
<message>
<location line="+98"/>
<location line="+4"/>
<location line="+7"/>
<location line="+16"/>
<location line="+6"/>
<location line="+4"/>
<source>Selection error</source>
<translation type="unfinished">Selekcja błedów</translation>
</message>
<message>
<location line="-37"/>
<source>Please use only a single reference for bearing constraint</source>
<translation type="unfinished">Proszę użyć tylko jednego odniesienia dla punktu podparcia</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie</translation>
</message>
<message>
<location line="+7"/>
<source>Only cylindrical faces can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie cylindryczne</translation>
</message>
<message>
<location line="+16"/>
<source>Only planar faces can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie płaskie</translation>
</message>
<message>
<location line="+6"/>
<source>Only linear edges can be picked</source>
<translation type="unfinished">Wybrać można tylko krawędzie liniowe</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces and edges can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie i krawędzie</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintFixed</name>
<message>
<location filename="../../TaskFemConstraintFixed.cpp" line="+74"/>
<source>Delete</source>
<translation type="unfinished">Usuń</translation>
</message>
<message>
<location line="+61"/>
<location line="+5"/>
<source>Selection error</source>
<translation type="unfinished">Selekcja błedów</translation>
</message>
<message>
<location line="-5"/>
<source>Mixed shape types are not possible. Use a second constraint instead</source>
<translation type="unfinished">Kształty typu mieszanego nie są możliwe do użycia. Użyj drugiego ograniczenia</translation>
</message>
<message>
<location line="+5"/>
<source>Only faces, edges and vertices can be picked</source>
<translation type="unfinished">Tylko powierzchnie, krawędzie i wierzchołki mogą być wybrane</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintForce</name>
<message>
<location filename="../../TaskFemConstraintForce.cpp" line="-291"/>
<source>Delete</source>
<translation type="unfinished">Usuń</translation>
</message>
<message>
<source>Point load [N]</source>
<translation type="obsolete">Point load [N]</translation>
</message>
<message>
<source>Line load [N/mm]</source>
<translation type="obsolete">Line load [N/mm]</translation>
</message>
<message utf8="true">
<source>Area load [N/mm²]</source>
<translation type="obsolete">Area load [N/mm²]</translation>
</message>
<message>
<location line="+67"/>
<source>Point load</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Line load</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Area load</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+30"/>
<location line="+5"/>
<location line="+27"/>
<location line="+6"/>
<location line="+4"/>
<source>Selection error</source>
<translation type="unfinished">Selekcja błedów</translation>
</message>
<message>
<location line="-42"/>
<source>Mixed shape types are not possible. Use a second constraint instead</source>
<translation type="unfinished">Kształty typu mieszanego nie są możliwe do użycia. Użyj drugiego ograniczenia</translation>
</message>
<message>
<location line="+5"/>
<source>Only faces, edges and vertices can be picked</source>
<translation type="unfinished">Tylko powierzchnie, krawędzie i wierzchołki mogą być wybrane</translation>
</message>
<message>
<location line="+27"/>
<source>Only planar faces can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie płaskie</translation>
</message>
<message>
<location line="+6"/>
<source>Only linear edges can be picked</source>
<translation type="unfinished">Wybrać można tylko krawędzie liniowe</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces and edges can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie i krawędzie</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintGear</name>
<message>
<location filename="../../TaskFemConstraintGear.cpp" line="-155"/>
<location line="+6"/>
<location line="+4"/>
<source>Selection error</source>
<translation type="unfinished">Selekcja błedów</translation>
</message>
<message>
<location line="-10"/>
<source>Only planar faces can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie płaskie</translation>
</message>
<message>
<location line="+6"/>
<source>Only linear edges can be picked</source>
<translation type="unfinished">Wybrać można tylko krawędzie liniowe</translation>
</message>
<message>
<location line="+4"/>
<source>Only faces and edges can be picked</source>
<translation type="unfinished">Wybrać można tylko powierzchnie i krawędzie</translation>
</message>
</context>
<context>
<name>FemGui::TaskFemConstraintPulley</name>
<message>
<location filename="../../TaskFemConstraintPulley.cpp" line="-110"/>
<source>Pulley diameter</source>
<translation type="unfinished">Średnica koła pasowego</translation>
</message>
<message>
<location line="+1"/>
<source>Torque [Nm]</source>
<translation type="unfinished">Moment obrotowy [Nm]</translation>
</message>
</context>
<context>
<name>FemGui::TaskObjectName</name>
<message>
<location filename="../../TaskObjectName.cpp" line="+48"/>
<source>TaskObjectName</source>
<translation type="unfinished">Zadaj nazwę obiektu</translation>
</message>
</context>
<context>
<name>FemGui::TaskTetParameter</name>
<message>
<location filename="../../TaskTetParameter.cpp" line="+52"/>
<source>Tet Parameter</source>
<translation type="unfinished">Parametr Tet</translation>
</message>
</context>
<context>
<name>MechanicalMaterial</name>
<message>
<location filename="../../../MechanicalAnalysis.ui" line="+14"/>
<source>Mechanical analysis</source>
<translation type="unfinished">Analiza mechaniczna</translation>
</message>
<message>
<location line="+21"/>
<source>...</source>
<translation type="unfinished">...</translation>
</message>
<message>
<location line="+9"/>
<source>Write Calculix Input File</source>
<translation type="unfinished">Write Calculix Input File</translation>
</message>
<message>
<location line="+7"/>
<source>Edit Calculix Input File</source>
<translation type="unfinished">Edit Calculix Input File</translation>
</message>
<message>
<location line="+7"/>
<source>Run Calculix</source>
<translation type="unfinished">Uruchom Calculix</translation>
</message>
<message>
<location line="+19"/>
<source>Time:</source>
<translation type="unfinished">Czas:</translation>
</message>
<message>
<location filename="../../../MechanicalMaterial.ui" line="+14"/>
<source>Mechanical material</source>
<translation type="unfinished">Materiał mechaniczny</translation>
</message>
<message>
<location line="+7"/>
<source>choose...</source>
<translation type="unfinished">Wybierz...</translation>
</message>
<message>
<location line="+10"/>
<source>MatWeb database...</source>
<translation type="unfinished">Baza danych MatWeb...</translation>
</message>
<message>
<location line="+11"/>
<source>Young's Modulus:</source>
<translation type="unfinished">Moduł Younga:</translation>
</message>
<message>
<location line="+22"/>
<source>Pa</source>
<translation type="unfinished">Paskal [Pa]</translation>
</message>
<message>
<location line="+19"/>
<source>Poisson Ratio:</source>
<translation type="unfinished">Współczynnik Poisson'a:</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../../Command.cpp" line="-468"/>
<source>No active Analysis</source>
<translation type="unfinished">Brak aktywnej analizy</translation>
</message>
<message>
<location line="+1"/>
<source>You need to create or activate a Analysis</source>
<translation type="unfinished">Należy stworzyć lub aktywować analizę</translation>
</message>
<message>
<location line="+58"/>
<location line="+8"/>
<location line="+56"/>
<location line="+8"/>
<source>Wrong selection</source>
<translation type="unfinished">Niewłaściwy wybór</translation>
</message>
<message>
<location line="-71"/>
<location line="+64"/>
<source>Your FreeCAD is build without NETGEN support. Meshing will not work....</source>
<translation type="unfinished">Twój FreeCAD jest zainstalowany bez wsparcia dla NETGEN. Siatka nie będzie działać...</translation>
</message>
<message>
<location line="-56"/>
<location line="+64"/>
<source>Select an edge, face or body. Only one body is allowed.</source>
<translation type="unfinished">Wybierz krawędź, powierzchnię lub bryłę. Tylko jedna bryłą jest dozwolona.</translation>
</message>
<message>
<location line="-59"/>
<location line="+64"/>
<source>Wrong object type</source>
<translation type="unfinished">Niewłaściwy typ obiektu</translation>
</message>
<message>
<location line="-63"/>
<location line="+64"/>
<source>Fillet works only on parts</source>
<translation type="unfinished">Zaokrąglenie działa tylko na częściach</translation>
</message>
<message>
<location filename="../../TaskFemConstraint.cpp" line="+16"/>
<source>Ok</source>
<translation type="unfinished">Ok</translation>
</message>
<message>
<location line="+1"/>
<source>Cancel</source>
<translation type="unfinished">Anuluj</translation>
</message>
<message>
<location filename="../../ViewProviderFemConstraint.cpp" line="+144"/>
<source>Edit constraint</source>
<translation type="unfinished">Edytuj ograniczenia</translation>
</message>
<message>
<location line="+280"/>
<location line="+2"/>
<source>Combo View</source>
<translation type="unfinished">Widok połączony</translation>
</message>
<message>
<location line="+2"/>
<source>combiTab</source>
<translation type="unfinished">combiTab</translation>
</message>
<message>
<location line="+2"/>
<source>qt_tabwidget_stackedwidget</source>
<translation type="unfinished">qt_tabwidget_stackedwidget</translation>
</message>
<message>
<location line="+6"/>
<source>ShaftWizard</source>
<translation type="unfinished">Kreator wałów</translation>
</message>
<message>
<location line="+3"/>
<source>ShaftWizardLayout</source>
<translation type="unfinished">Kreator układów wałów</translation>
</message>
<message>
<location filename="../../ViewProviderFemConstraintBearing.cpp" line="+74"/>
<location filename="../../ViewProviderFemConstraintFixed.cpp" line="+74"/>
<location filename="../../ViewProviderFemConstraintForce.cpp" line="+72"/>
<location filename="../../ViewProviderFemConstraintGear.cpp" line="+73"/>
<location filename="../../ViewProviderFemConstraintPulley.cpp" line="+72"/>
<source>A dialog is already open in the task panel</source>
<translation type="unfinished">Okno dialogowe jest już otwarte w panelu zadań</translation>
</message>
<message>
<location line="+1"/>
<location filename="../../ViewProviderFemConstraintFixed.cpp" line="+1"/>
<location filename="../../ViewProviderFemConstraintForce.cpp" line="+1"/>
<location filename="../../ViewProviderFemConstraintGear.cpp" line="+1"/>
<location filename="../../ViewProviderFemConstraintPulley.cpp" line="+1"/>
<source>Do you want to close this dialog?</source>
<translation type="unfinished">Czy chcesz zamknąć to okno dialogowe?</translation>
</message>
<message>
<location filename="../../ViewProviderFemMeshShapeNetgen.cpp" line="+57"/>
<source>Meshing</source>
<translation type="unfinished">Tworzenie siatki</translation>
</message>
<message>
<location filename="../../TaskFemConstraintForce.cpp" line="+119"/>
<source>Constraint force</source>
<translation type="unfinished">Constraint force</translation>
</message>
</context>
<context>
<name>ShowDisplacement</name>
<message>
<location filename="../../../ShowDisplacement.ui" line="+14"/>
<source>Show result</source>
<translation type="unfinished">Pokaż wynik</translation>
</message>
<message>
<location line="+8"/>
<source>Colors</source>
<translation type="unfinished">Kolory</translation>
</message>
<message>
<location line="+73"/>
<source>Displacement</source>
<translation type="unfinished">Wyporność</translation>
</message>
<message>
<location line="-39"/>
<source>Max:</source>
<translation type="unfinished">Maks:</translation>
</message>
<message>
<location line="+17"/>
<source>Min:</source>
<translation type="unfinished">Min:</translation>
</message>
<message>
<location line="-44"/>
<source>None</source>
<translation type="unfinished">Żaden</translation>
</message>
<message>
<location line="+10"/>
<source>Avg:</source>
<translation type="unfinished">Średnio:</translation>
</message>
<message>
<location line="+10"/>
<location line="+17"/>
<location line="+17"/>
<source>mm</source>
<translation type="unfinished">mm</translation>
</message>
<message>
<location line="+18"/>
<source>Show</source>
<translation type="unfinished">Pokaż</translation>
</message>
<message>
<location line="+12"/>
<source>Factor:</source>
<translation type="unfinished">Współczynnik:</translation>
</message>
<message>
<location line="+27"/>
<source>Slider max:</source>
<translation type="unfinished">Suwak max:</translation>
</message>
</context>
<context>
<name>TaskAnalysisInfo</name>
<message>
<location filename="../../TaskAnalysisInfo.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+12"/>
<source>Meshes:</source>
<translation type="unfinished">Oczka siatki:</translation>
</message>
<message>
<location line="+16"/>
<source>Constraints</source>
<translation type="unfinished">Ograniczenia</translation>
</message>
</context>
<context>
<name>TaskCreateNodeSet</name>
<message>
<location filename="../../TaskCreateNodeSet.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+7"/>
<source>Volume</source>
<translation type="unfinished">Objętość</translation>
</message>
<message>
<location line="+5"/>
<source>Surface</source>
<translation type="unfinished">Powierzchnia</translation>
</message>
<message>
<location line="+17"/>
<source>Nodes: 0</source>
<translation type="unfinished">Węzły: 0</translation>
</message>
<message>
<location line="+11"/>
<source>Poly</source>
<translation type="unfinished">Poli</translation>
</message>
<message>
<location line="+10"/>
<source>Box</source>
<translation type="unfinished">Sześcian</translation>
</message>
<message>
<location line="+10"/>
<source>Pick</source>
<translation type="unfinished">Wybierz</translation>
</message>
<message>
<location line="+7"/>
<source>Add</source>
<translation type="unfinished">Dodaj</translation>
</message>
<message>
<location line="+9"/>
<source>Angle-search</source>
<translation type="unfinished">Szukaj kąt</translation>
</message>
<message>
<location line="+6"/>
<source>Collect adjancent nodes</source>
<translation type="unfinished">Zbierz przylegające węzły</translation>
</message>
<message>
<location line="+9"/>
<source>Stop angle:</source>
<translation type="unfinished">Kąt zatrzymania:</translation>
</message>
</context>
<context>
<name>TaskDriver</name>
<message>
<location filename="../../TaskDriver.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
</context>
<context>
<name>TaskFemConstraint</name>
<message>
<location filename="../../TaskFemConstraint.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+9"/>
<source>Add reference</source>
<translation type="unfinished">Dodaj odniesienie</translation>
</message>
<message>
<location line="+12"/>
<source>Load [N]</source>
<translation type="unfinished">Obciążenie [N]</translation>
</message>
<message>
<location line="+24"/>
<source>Diameter</source>
<translation type="unfinished">Średnica</translation>
</message>
<message>
<location line="+27"/>
<source>Other diameter</source>
<translation type="unfinished">Inna średnica</translation>
</message>
<message>
<location line="+27"/>
<source>Center distance</source>
<translation type="unfinished">Odległość od środka</translation>
</message>
<message>
<location line="+24"/>
<source>Direction</source>
<translation type="unfinished">Kierunek</translation>
</message>
<message>
<location line="+12"/>
<source>Reverse direction</source>
<translation type="unfinished">Odwróć kierunek</translation>
</message>
<message>
<location line="+9"/>
<source>Location</source>
<translation type="unfinished">Lokalizacja</translation>
</message>
<message>
<location line="+14"/>
<source>Distance</source>
<translation type="unfinished">Odległość</translation>
</message>
</context>
<context>
<name>TaskFemConstraintBearing</name>
<message>
<location filename="../../TaskFemConstraintBearing.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+6"/>
<source>Add reference</source>
<translation type="unfinished">Dodaj odniesienie</translation>
</message>
<message>
<location line="+15"/>
<source>Gear diameter</source>
<translation type="unfinished">Średnica koła zębatego</translation>
</message>
<message>
<location line="+27"/>
<source>Other pulley dia</source>
<translation type="unfinished">Inna średnica koła pasowego</translation>
</message>
<message>
<location line="+24"/>
<source>Center distance</source>
<translation type="unfinished">Odległość od środka</translation>
</message>
<message>
<location line="+24"/>
<source>Force</source>
<translation type="unfinished">Siła</translation>
</message>
<message>
<location line="+24"/>
<source>Belt tension force</source>
<translation type="unfinished">Siła naciągu paska</translation>
</message>
<message>
<location line="+22"/>
<source>Driven pulley</source>
<translation type="unfinished">Napędzane koło pasowe</translation>
</message>
<message>
<location line="+9"/>
<source>Force location [deg]</source>
<translation type="unfinished">Położenie siły [deg]</translation>
</message>
<message>
<location line="+27"/>
<source>Force Direction</source>
<translation type="unfinished">Kierunek siły</translation>
</message>
<message>
<location line="+12"/>
<source>Reversed direction</source>
<translation type="unfinished">Odwrócone kierunki</translation>
</message>
<message>
<location line="+7"/>
<source>Axial free</source>
<translation type="unfinished">Wolne osiowo</translation>
</message>
<message>
<location line="+9"/>
<source>Location</source>
<translation type="unfinished">Lokalizacja</translation>
</message>
<message>
<location line="+14"/>
<source>Distance</source>
<translation type="unfinished">Odległość</translation>
</message>
</context>
<context>
<name>TaskFemConstraintFixed</name>
<message>
<location filename="../../TaskFemConstraintFixed.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+6"/>
<source>Add reference</source>
<translation type="unfinished">Dodaj odniesienie</translation>
</message>
</context>
<context>
<name>TaskFemConstraintForce</name>
<message>
<location filename="../../TaskFemConstraintForce.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+6"/>
<source>Add reference</source>
<translation type="unfinished">Dodaj odniesienie</translation>
</message>
<message>
<location line="+12"/>
<source>Load [N]</source>
<translation type="unfinished">Obciążenie [N]</translation>
</message>
<message>
<location line="+24"/>
<source>Direction</source>
<translation type="unfinished">Kierunek</translation>
</message>
<message>
<location line="+12"/>
<source>Reverse direction</source>
<translation type="unfinished">Odwróć kierunek</translation>
</message>
</context>
<context>
<name>TaskObjectName</name>
<message>
<location filename="../../TaskObjectName.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
</context>
<context>
<name>TaskTetParameter</name>
<message>
<location filename="../../TaskTetParameter.ui" line="+20"/>
<source>Form</source>
<translation type="unfinished">Formularz</translation>
</message>
<message>
<location line="+8"/>
<source>Max. Size:</source>
<translation type="unfinished">Rozmiar max.:</translation>
</message>
<message>
<location line="+16"/>
<source>Second order</source>
<translation type="unfinished">Drugiego rzędu</translation>
</message>
<message>
<location line="+9"/>
<source>Fineness:</source>
<translation type="unfinished">Stopień rozdrobnienia:</translation>
</message>
<message>
<location line="+11"/>
<source>VeryCoarse</source>
<translation type="unfinished">Bardzo zgrubnie</translation>
</message>
<message>
<location line="+5"/>
<source>Coarse</source>
<translation type="unfinished">Zgrubnie</translation>
</message>
<message>
<location line="+5"/>
<source>Moderate</source>
<translation type="unfinished">Umiarkowanie</translation>
</message>
<message>
<location line="+5"/>
<source>Fine</source>
<translation type="unfinished">Drobno</translation>
</message>
<message>
<location line="+5"/>
<source>VeryFine</source>
<translation type="unfinished">Bardzo drobno</translation>
</message>
<message>
<location line="+5"/>
<source>UserDefined</source>
<translation type="unfinished">Zdefiniowane przez użytkownika</translation>
</message>
<message>
<location line="+8"/>
<source>Growth Rate:</source>
<translation type="unfinished">Współczynnik wzrostu:</translation>
</message>
<message>
<location line="+14"/>
<source>Nbr. Segs per Edge:</source>
<translation type="unfinished">Liczba segmentów na krawędź:</translation>
</message>
<message>
<location line="+17"/>
<source>Nbr. Segs per Radius:</source>
<translation type="unfinished">Liczba segmentów na promień:</translation>
</message>
<message>
<location line="+16"/>
<source>Optimize</source>
<translation type="unfinished">Optymalizacji</translation>
</message>
<message>
<location line="+22"/>
<source>Node count: </source>
<translation type="unfinished">Liczba węzłów:</translation>
</message>
<message>
<location line="+14"/>
<source>Triangle count:</source>
<translation type="unfinished">Liczba trójkątów:</translation>
</message>
<message>
<location line="+14"/>
<source>Tetraeder count:</source>
<translation type="unfinished">Liczba tetraedrów:</translation>
</message>
</context>
<context>
<name>Workbench</name>
<message>
<location filename="../../Workbench.cpp" line="+38"/>
<source>FEM</source>
<translation>MES</translation>
</message>
<message>
<location line="+1"/>
<source>&FEM</source>
<translation>&MES</translation>
</message>
</context>
</TS>
| lgpl-2.1 |
llaville/phing | test/classes/phing/tasks/ext/GitTasks/GitInitTaskTest.php | 3367 | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/BuildFileTest.php';
require_once '../classes/phing/tasks/ext/git/GitInitTask.php';
require_once dirname(__FILE__) . '/GitTestsHelper.php';
/**
* @author Victor Farazdagi <simple.square@gmail.com>
* @version $Id$
* @package phing.tasks.ext
*/
class GitInitTaskTest extends BuildFileTest
{
public function setUp()
{
// the pear git package hardcodes the path to git to /usr/bin/git and will therefore
// not work on Windows.
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$this->markTestSkipped('Testing not on a windows os.');
}
// set temp directory used by test cases
mkdir(PHING_TEST_BASE . '/tmp/git');
$this->configureProject(
PHING_TEST_BASE
. '/etc/tasks/ext/git/GitInitTaskTest.xml'
);
}
public function tearDown()
{
GitTestsHelper::rmdir(PHING_TEST_BASE . '/tmp/git');
}
public function testWrongRepository()
{
$this->expectBuildExceptionContaining(
'wrongRepository',
'Repository directory not readable',
'You must specify readable directory as repository.'
);
}
public function testGitInit()
{
$repository = PHING_TEST_BASE . '/tmp/git';
$gitFilesDir = $repository . '/.git';
$this->executeTarget('gitInit');
$this->assertInLogs('git-init: initializing "' . $repository . '" repository');
$this->assertTrue(is_dir($repository));
$this->assertTrue(is_dir($gitFilesDir));
}
public function testGitInitBare()
{
$repository = PHING_TEST_BASE . '/tmp/git';
$gitFilesDir = $repository . '/.git';
$this->executeTarget('gitInitBare');
$this->assertInLogs('git-init: initializing (bare) "' . $repository . '" repository');
$this->assertTrue(is_dir($repository));
$this->assertTrue(is_dir($repository . '/branches'));
$this->assertTrue(is_dir($repository . '/info'));
$this->assertTrue(is_dir($repository . '/hooks'));
$this->assertTrue(is_dir($repository . '/refs'));
}
public function testNoRepositorySpecified()
{
$this->expectBuildExceptionContaining(
'noRepository',
'Repo dir is required',
'"repository" is required parameter'
);
}
}
| lgpl-3.0 |
socialengineers/phing | test/classes/phing/components/TargetTest.php | 6020 | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/BuildFileTest.php';
/**
* UTs for Target component
*
* @author Victor Farazdagi <simple.square@gmail.com>
* @author Daniel Holmes
* @package phing.system
*/
class TargetTest extends BuildFileTest
{
/** @var Target */
private $target;
public function setUp()
{
$this->configureProject(
PHING_TEST_BASE
. "/etc/components/Target/Target.xml"
);
$this->target = new Target();
$this->target->setProject($this->project);
$this->target->setName('MyTarget');
}
public function testHiddenTargets()
{
$phingExecutable = '"' . PHING_TEST_BASE . '/../bin/phing"';
$buildFile = '"' . PHING_TEST_BASE . '/etc/components/Target/HiddenTargets.xml"';
$cmd = $phingExecutable . ' -l -f ' . $buildFile;
exec($cmd, $out);
$out = implode("\n", $out);
$offset = strpos($out, 'Subtargets:');
$this->assertFalse(strpos($out, 'HideInListTarget', $offset));
$this->assertTrue(strpos($out, 'ShowInListTarget', $offset) !== false);
}
/**
* @dataProvider setDependsValidDataProvider
* @param array $expectedDepends
* @param string $depends
*/
public function testSetDependsValid(array $expectedDepends, $depends)
{
$this->target->setDepends($depends);
$this->assertEquals($expectedDepends, $this->target->getDependencies());
}
public function setDependsValidDataProvider()
{
return array(
array(array('target1'), 'target1'),
array(array('target1', 'target2'), 'target1,target2')
);
}
/**
* @dataProvider setDependsInvalidDataProvider
* @param string $depends
*/
public function testSetDependsInvalid($depends)
{
$this->setExpectedException(
'BuildException',
'Syntax Error: Depend attribute for target MyTarget is malformed.'
);
$this->target->setDepends($depends);
}
public function setDependsInvalidDataProvider()
{
return array(
array(''),
array('target1,')
);
}
public function testGetTasksReturnsCorrectTasks()
{
$task = new EchoTask();
$task->setMessage('Hello World');
$this->target->addTask($task);
$this->target->addDataType('dataType');
$tasks = $this->target->getTasks();
$this->assertEquals(array($task), $tasks);
}
public function testGetTasksClonesTasks()
{
$task = new EchoTask();
$task->setMessage('Hello World');
$this->target->addTask($task);
$tasks = $this->target->getTasks();
$this->assertNotSame($task, $tasks[0]);
}
public function testMainAppliesConfigurables()
{
$configurable = $this->getMockBuilder('RuntimeConfigurable')
->disableOriginalConstructor()
->getMock();
$configurable->expects($this->once())->method('maybeConfigure')->with($this->project);
$this->target->addDataType($configurable);
$this->target->main();
}
public function testMainFalseIfDoesntApplyConfigurable()
{
$this->project->setProperty('ifProperty', null);
$this->target->setIf('ifProperty');
$configurable = $this->getMockBuilder('RuntimeConfigurable')
->disableOriginalConstructor()
->getMock();
$configurable->expects($this->never())->method('maybeConfigure');
$this->target->addDataType($configurable);
$this->target->main();
}
public function testMainTrueUnlessDoesntApplyConfigurable()
{
$this->project->setProperty('unlessProperty', 'someValue');
$this->target->setUnless('unlessProperty');
$configurable = $this->getMockBuilder('RuntimeConfigurable')
->disableOriginalConstructor()
->getMock();
$configurable->expects($this->never())->method('maybeConfigure');
$this->target->addDataType($configurable);
$this->target->main();
}
public function testMainPerformsTasks()
{
$task = $this->getMock('Task');
$task->expects($this->once())->method('perform');
$this->target->addTask($task);
$this->target->main();
}
public function testMainFalseIfDoesntPerformTasks()
{
$this->project->setProperty('ifProperty', null);
$this->target->setIf('ifProperty');
$task = $this->getMock('Task');
$task->expects($this->never())->method('perform');
$this->target->addTask($task);
$this->target->main();
}
public function testMainTrueUnlessDoesntPerformTasks()
{
$this->project->setProperty('unlessProperty', 'someValue');
$this->target->setUnless('unlessProperty');
$task = $this->getMock('Task');
$task->expects($this->never())->method('perform');
$this->target->addTask($task);
$this->target->main();
}
}
| lgpl-3.0 |
bitshares/bitshares-0.x | programs/utils/web_update_utility/update_utility.hpp | 487 | #pragma once
#include <fc/filesystem.hpp>
#include <WebUpdates.hpp>
class update_utility
{
fc::path _manifest_path;
WebUpdateManifest _manifest;
public:
void open_manifest(fc::path path);
void write_manifest();
WebUpdateManifest& manifest() { return _manifest; }
void pack_web(fc::path path, std::string output_file);
void sign_update(WebUpdateManifest::UpdateDetails& update, fc::path update_package, bts::blockchain::private_key_type signing_key);
};
| unlicense |
ykbarros/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_Android/Amazon.CloudWatch/Model/DescribeAlarmsResult.cs | 2281 | /*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudWatch.Model
{
/// <summary>
/// The output for the <a>DescribeAlarms</a> action.
/// </summary>
public partial class DescribeAlarmsResult : AmazonWebServiceResponse
{
private List<MetricAlarm> _metricAlarms = new List<MetricAlarm>();
private string _nextToken;
/// <summary>
/// Gets and sets the property MetricAlarms.
/// <para>
/// A list of information for the specified alarms.
/// </para>
/// </summary>
public List<MetricAlarm> MetricAlarms
{
get { return this._metricAlarms; }
set { this._metricAlarms = value; }
}
// Check to see if MetricAlarms property is set
internal bool IsSetMetricAlarms()
{
return this._metricAlarms != null && this._metricAlarms.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A string that marks the start of the next batch of returned results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | apache-2.0 |
jsdosa/TizenRT | external/libcxx-test/std/strings/basic.string/string.access/index.pass.cpp | 2032 | /****************************************************************************
*
* Copyright 2018 Samsung Electronics 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.
*
****************************************************************************/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <string>
// const_reference operator[](size_type pos) const;
// reference operator[](size_type pos);
#ifdef _LIBCPP_DEBUG
#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
#endif
#include <string>
#include <cassert>
#include "test_macros.h"
#include "libcxx_tc_common.h"
int tc_libcxx_strings_string_access_index(void)
{
{
typedef std::string S;
S s("0123456789");
const S& cs = s;
for (S::size_type i = 0; i < cs.size(); ++i)
{
TC_ASSERT_EXPR(s[i] == static_cast<char>('0' + i));
TC_ASSERT_EXPR(cs[i] == s[i]);
}
TC_ASSERT_EXPR(cs[cs.size()] == '\0');
const S s2 = S();
TC_ASSERT_EXPR(s2[0] == '\0');
}
#ifdef _LIBCPP_DEBUG
{
std::string s;
char c = s[0];
TC_ASSERT_EXPR(c == '\0');
c = s[1];
TC_ASSERT_EXPR(false);
}
#endif
TC_SUCCESS_RESULT();
return 0;
}
| apache-2.0 |
westhood/etcd | auth/range_perm_cache.go | 5375 | // Copyright 2016 The etcd 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 auth
import (
"bytes"
"sort"
"github.com/coreos/etcd/auth/authpb"
"github.com/coreos/etcd/mvcc/backend"
)
// isSubset returns true if a is a subset of b
func isSubset(a, b *rangePerm) bool {
switch {
case len(a.end) == 0 && len(b.end) == 0:
// a, b are both keys
return bytes.Equal(a.begin, b.begin)
case len(b.end) == 0:
// b is a key, a is a range
return false
case len(a.end) == 0:
return 0 <= bytes.Compare(a.begin, b.begin) && bytes.Compare(a.begin, b.end) <= 0
default:
return 0 <= bytes.Compare(a.begin, b.begin) && bytes.Compare(a.end, b.end) <= 0
}
}
func isRangeEqual(a, b *rangePerm) bool {
return bytes.Equal(a.begin, b.begin) && bytes.Equal(a.end, b.end)
}
// removeSubsetRangePerms removes any rangePerms that are subsets of other rangePerms.
// If there are equal ranges, removeSubsetRangePerms only keeps one of them.
func removeSubsetRangePerms(perms []*rangePerm) []*rangePerm {
// TODO(mitake): currently it is O(n^2), we need a better algorithm
var newp []*rangePerm
for i := range perms {
skip := false
for j := range perms {
if i == j {
continue
}
if isRangeEqual(perms[i], perms[j]) {
// if ranges are equal, we only keep the first range.
if i > j {
skip = true
break
}
} else if isSubset(perms[i], perms[j]) {
// if a range is a strict subset of the other one, we skip the subset.
skip = true
break
}
}
if skip {
continue
}
newp = append(newp, perms[i])
}
return newp
}
// mergeRangePerms merges adjacent rangePerms.
func mergeRangePerms(perms []*rangePerm) []*rangePerm {
var merged []*rangePerm
perms = removeSubsetRangePerms(perms)
sort.Sort(RangePermSliceByBegin(perms))
i := 0
for i < len(perms) {
begin, next := i, i
for next+1 < len(perms) && bytes.Compare(perms[next].end, perms[next+1].begin) != -1 {
next++
}
merged = append(merged, &rangePerm{begin: perms[begin].begin, end: perms[next].end})
i = next + 1
}
return merged
}
func getMergedPerms(tx backend.BatchTx, userName string) *unifiedRangePermissions {
user := getUser(tx, userName)
if user == nil {
plog.Errorf("invalid user name %s", userName)
return nil
}
var readPerms, writePerms []*rangePerm
for _, roleName := range user.Roles {
role := getRole(tx, roleName)
if role == nil {
continue
}
for _, perm := range role.KeyPermission {
rp := &rangePerm{begin: perm.Key, end: perm.RangeEnd}
switch perm.PermType {
case authpb.READWRITE:
readPerms = append(readPerms, rp)
writePerms = append(writePerms, rp)
case authpb.READ:
readPerms = append(readPerms, rp)
case authpb.WRITE:
writePerms = append(writePerms, rp)
}
}
}
return &unifiedRangePermissions{
readPerms: mergeRangePerms(readPerms),
writePerms: mergeRangePerms(writePerms),
}
}
func checkKeyPerm(cachedPerms *unifiedRangePermissions, key, rangeEnd []byte, permtyp authpb.Permission_Type) bool {
var tocheck []*rangePerm
switch permtyp {
case authpb.READ:
tocheck = cachedPerms.readPerms
case authpb.WRITE:
tocheck = cachedPerms.writePerms
default:
plog.Panicf("unknown auth type: %v", permtyp)
}
requiredPerm := &rangePerm{begin: key, end: rangeEnd}
for _, perm := range tocheck {
if isSubset(requiredPerm, perm) {
return true
}
}
return false
}
func (as *authStore) isRangeOpPermitted(tx backend.BatchTx, userName string, key, rangeEnd []byte, permtyp authpb.Permission_Type) bool {
// assumption: tx is Lock()ed
_, ok := as.rangePermCache[userName]
if !ok {
perms := getMergedPerms(tx, userName)
if perms == nil {
plog.Errorf("failed to create a unified permission of user %s", userName)
return false
}
as.rangePermCache[userName] = perms
}
return checkKeyPerm(as.rangePermCache[userName], key, rangeEnd, permtyp)
}
func (as *authStore) clearCachedPerm() {
as.rangePermCache = make(map[string]*unifiedRangePermissions)
}
func (as *authStore) invalidateCachedPerm(userName string) {
delete(as.rangePermCache, userName)
}
type unifiedRangePermissions struct {
// readPerms[i] and readPerms[j] (i != j) don't overlap
readPerms []*rangePerm
// writePerms[i] and writePerms[j] (i != j) don't overlap, too
writePerms []*rangePerm
}
type rangePerm struct {
begin, end []byte
}
type RangePermSliceByBegin []*rangePerm
func (slice RangePermSliceByBegin) Len() int {
return len(slice)
}
func (slice RangePermSliceByBegin) Less(i, j int) bool {
switch bytes.Compare(slice[i].begin, slice[j].begin) {
case 0: // begin(i) == begin(j)
return bytes.Compare(slice[i].end, slice[j].end) == -1
case -1: // begin(i) < begin(j)
return true
default:
return false
}
}
func (slice RangePermSliceByBegin) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
| apache-2.0 |
medicayun/medicayundicom | dcm4jboss-all/tags/DCM4JBOSS_0_9_2/dcm4jboss-ejb/src/java/org/dcm4chex/archive/ejb/jdbc/AECmd.java | 2012 | /*
* Copyright (c) 2002,2003 by TIANI MEDGRAPH AG
*
* This file is part of dcm4che.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.dcm4chex.archive.ejb.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
/**
* @author Gunter.Zeilinger@tiani.com
* @version $Revision: 1023 $
* @since 22.11.2003
*/
public final class AECmd extends BaseCmd
{
private static final String[] ENTITY = { "AE" };
private static final String[] SELECT_ATTRIBUTE =
{ "AE.pk", "AE.title", "AE.hostName", "AE.port", "AE.cipherSuites" };
private final SqlBuilder sqlBuilder = new SqlBuilder();
public AECmd(DataSource ds, String aet) throws SQLException
{
super(ds);
sqlBuilder.setSelect(SELECT_ATTRIBUTE);
sqlBuilder.setFrom(ENTITY);
sqlBuilder.addSingleValueMatch("AE.title", SqlBuilder.TYPE1, aet);
}
public AEData execute() throws SQLException
{
try
{
execute(sqlBuilder.getSql());
return next()
? new AEData(
rs.getInt(1),
rs.getString(2),
rs.getString(3),
rs.getInt(4),
rs.getString(5))
: null;
} finally
{
close();
}
}
}
| apache-2.0 |
treasure-data/presto | presto-rcfile/src/main/java/io/prestosql/rcfile/binary/LongEncoding.java | 2792 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.rcfile.binary;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceOutput;
import io.prestosql.rcfile.ColumnData;
import io.prestosql.rcfile.EncodeOutput;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.BlockBuilder;
import io.prestosql.spi.type.Type;
import static io.prestosql.rcfile.RcFileDecoderUtils.decodeVIntSize;
import static io.prestosql.rcfile.RcFileDecoderUtils.readVInt;
import static io.prestosql.rcfile.RcFileDecoderUtils.writeVLong;
public class LongEncoding
implements BinaryColumnEncoding
{
private final Type type;
public LongEncoding(Type type)
{
this.type = type;
}
@Override
public void encodeColumn(Block block, SliceOutput output, EncodeOutput encodeOutput)
{
for (int position = 0; position < block.getPositionCount(); position++) {
if (!block.isNull(position)) {
writeVLong(output, type.getLong(block, position));
}
encodeOutput.closeEntry();
}
}
@Override
public void encodeValueInto(Block block, int position, SliceOutput output)
{
writeVLong(output, type.getLong(block, position));
}
@Override
public Block decodeColumn(ColumnData columnData)
{
int size = columnData.rowCount();
BlockBuilder builder = type.createBlockBuilder(null, size);
Slice slice = columnData.getSlice();
for (int i = 0; i < size; i++) {
int offset = columnData.getOffset(i);
int length = columnData.getLength(i);
if (length == 0) {
builder.appendNull();
}
else {
type.writeLong(builder, readVInt(slice, offset, length));
}
}
return builder.build();
}
@Override
public int getValueOffset(Slice slice, int offset)
{
return 0;
}
@Override
public int getValueLength(Slice slice, int offset)
{
return decodeVIntSize(slice, offset);
}
@Override
public void decodeValueInto(BlockBuilder builder, Slice slice, int offset, int length)
{
type.writeLong(builder, readVInt(slice, offset, length));
}
}
| apache-2.0 |
jkorab/camel | platforms/spring-boot/components-starter/camel-base64-starter/src/main/java/org/apache/camel/dataformat/base64/springboot/Base64DataFormatAutoConfiguration.java | 5260 | /**
* 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.dataformat.base64.springboot;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.dataformat.base64.Base64DataFormat;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatFactory;
import org.apache.camel.util.IntrospectionSupport;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Configuration
@ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@Conditional(Base64DataFormatAutoConfiguration.Condition.class)
@AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@EnableConfigurationProperties(Base64DataFormatConfiguration.class)
public class Base64DataFormatAutoConfiguration {
@Bean(name = "base64-dataformat-factory")
@ConditionalOnClass(CamelContext.class)
@ConditionalOnMissingBean(Base64DataFormat.class)
public DataFormatFactory configureBase64DataFormatFactory(
final CamelContext camelContext,
final Base64DataFormatConfiguration configuration) {
return new DataFormatFactory() {
public DataFormat newInstance() {
Base64DataFormat dataformat = new Base64DataFormat();
if (CamelContextAware.class
.isAssignableFrom(Base64DataFormat.class)) {
CamelContextAware contextAware = CamelContextAware.class
.cast(dataformat);
if (contextAware != null) {
contextAware.setCamelContext(camelContext);
}
}
try {
Map<String, Object> parameters = new HashMap<>();
IntrospectionSupport.getProperties(configuration,
parameters, null, false);
IntrospectionSupport.setProperties(camelContext,
camelContext.getTypeConverter(), dataformat,
parameters);
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
return dataformat;
}
};
}
public static class Condition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(
ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean groupEnabled = isEnabled(conditionContext,
"camel.dataformat.", true);
ConditionMessage.Builder message = ConditionMessage
.forCondition("camel.dataformat.base64");
if (isEnabled(conditionContext, "camel.dataformat.base64.",
groupEnabled)) {
return ConditionOutcome.match(message.because("enabled"));
}
return ConditionOutcome.noMatch(message.because("not enabled"));
}
private boolean isEnabled(
org.springframework.context.annotation.ConditionContext context,
java.lang.String prefix, boolean defaultValue) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), prefix);
return resolver.getProperty("enabled", Boolean.class, defaultValue);
}
}
} | apache-2.0 |
vrozov/incubator-apex-core | engine/src/main/java/org/apache/apex/engine/plugin/AbstractDAGExecutionPluginContext.java | 3908 | /**
* 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.apex.engine.plugin;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import org.apache.apex.engine.api.plugin.DAGExecutionEvent;
import org.apache.apex.engine.api.plugin.DAGExecutionPlugin;
import org.apache.hadoop.conf.Configuration;
import com.datatorrent.api.Attribute;
import com.datatorrent.api.DAG;
import com.datatorrent.api.StatsListener;
import com.datatorrent.common.util.Pair;
import com.datatorrent.stram.StramAppContext;
import com.datatorrent.stram.StreamingContainerManager;
import com.datatorrent.stram.plan.physical.PTOperator;
import com.datatorrent.stram.util.VersionInfo;
import com.datatorrent.stram.webapp.AppInfo;
import com.datatorrent.stram.webapp.LogicalOperatorInfo;
/**
* @since 3.6.0
*/
public abstract class AbstractDAGExecutionPluginContext<E extends DAGExecutionEvent> implements DAGExecutionPlugin.Context<E>
{
private final StreamingContainerManager dnmgr;
private final Configuration launchConf;
private final StramAppContext appContext;
private final AppInfo.AppStats stats;
public AbstractDAGExecutionPluginContext(StramAppContext appContext, StreamingContainerManager dnmgr, AppInfo.AppStats stats, Configuration launcConf)
{
this.appContext = appContext;
this.dnmgr = dnmgr;
this.launchConf = launcConf;
this.stats = stats;
}
@Override
public abstract DAG getDAG();
@Override
public StramAppContext getApplicationContext()
{
return appContext;
}
@Override
public AppInfo.AppStats getApplicationStats()
{
return stats;
}
@Override
public String getOperatorName(int id)
{
PTOperator ptOperator = dnmgr.getPhysicalPlan().getAllOperators().get(id);
if (ptOperator != null) {
return ptOperator.getName();
}
return null;
}
@Override
public VersionInfo getEngineVersion()
{
return VersionInfo.APEX_VERSION;
}
@Override
public Configuration getLaunchConfig()
{
return launchConf;
}
@Override
public StatsListener.BatchedOperatorStats getPhysicalOperatorStats(int id)
{
PTOperator ptOperator = dnmgr.getPhysicalPlan().getAllOperators().get(id);
if (ptOperator != null) {
return ptOperator.stats;
}
return null;
}
@Override
public List<LogicalOperatorInfo> getLogicalOperatorInfoList()
{
return dnmgr.getLogicalOperatorInfoList();
}
@Override
public Queue<Pair<Long, Map<String, Object>>> getWindowMetrics(String operatorName)
{
return dnmgr.getWindowMetrics(operatorName);
}
@Override
public long windowIdToMillis(long windowId)
{
return dnmgr.windowIdToMillis(windowId);
}
@Override
public Attribute.AttributeMap getAttributes()
{
return appContext.getAttributes();
}
@Override
public <T> T getValue(Attribute<T> key)
{
return appContext.getValue(key);
}
@Override
public void setCounters(Object counters)
{
appContext.setCounters(counters);
}
@Override
public void sendMetrics(Collection<String> metricNames)
{
appContext.sendMetrics(metricNames);
}
}
| apache-2.0 |
ariel-bentu/java-buildpack | spec/java_buildpack/util/configuration_utils_spec.rb | 4450 | # Cloud Foundry Java Buildpack
# Copyright 2013-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.
require 'java_buildpack/util'
require 'java_buildpack/util/configuration_utils'
require 'fileutils'
require 'logging_helper'
require 'pathname'
require 'spec_helper'
require 'yaml'
describe JavaBuildpack::Util::ConfigurationUtils do
include_context 'logging_helper'
let(:test_data) do
{ 'foo' => { 'one' => '1', 'two' => 2 },
'bar' => { 'alpha' => { 'one' => 'cat', 'two' => 'dog' } },
'version' => '1.7.1',
'not_here' => nil }
end
it 'not load absent configuration file' do
pathname = instance_double(Pathname)
allow(Pathname).to receive(:new).and_return(pathname)
allow(pathname).to receive(:exist?).and_return(false)
expect(described_class.load('test')).to eq({})
end
it 'write configuration file' do
test_file = Pathname.new(File.expand_path('../../../config/open_jdk_jre.yml', File.dirname(__FILE__)))
original_content = file_contents test_file
loaded_content = described_class.load('open_jdk_jre', false)
described_class.write('open_jdk_jre', loaded_content)
expect(described_class.load('open_jdk_jre', false)).to eq(loaded_content)
expect(file_contents(test_file)).to eq(original_content)
end
context do
before do
pathname = instance_double(Pathname)
allow(Pathname).to receive(:new).and_return(pathname)
allow(pathname).to receive(:exist?).and_return(true)
allow(YAML).to receive(:load_file).and_return(test_data)
end
it 'load configuration file' do
expect(described_class.load('test', false)).to eq(test_data)
end
it 'load configuration file and clean nil values' do
expect(described_class.load('test', true)).to eq('foo' => { 'one' => '1', 'two' => 2 },
'bar' => { 'alpha' => { 'one' => 'cat', 'two' => 'dog' } },
'version' => '1.7.1')
end
context do
let(:environment) do
{ 'JBP_CONFIG_TEST' => '{bar: {alpha: {one: 3, two: {one: 3}}, bravo: newValue}, foo: lion}' }
end
it 'overlays matching environment variables' do
expect(described_class.load('test')).to eq('foo' => { 'one' => '1', 'two' => 2 },
'bar' => { 'alpha' => { 'one' => 3, 'two' => 'dog' } },
'version' => '1.7.1')
end
end
context do
let(:environment) do
{ 'JBP_CONFIG_TEST' => '{version: 1.8.+}' }
end
it 'overlays simple matching environment variable' do
expect(described_class.load('test')).to eq('foo' => { 'one' => '1', 'two' => 2 },
'bar' => { 'alpha' => { 'one' => 'cat', 'two' => 'dog' } },
'version' => '1.8.+')
end
end
context do
let(:environment) do
{ 'JBP_CONFIG_TEST' => 'Not an array or a hash' }
end
it 'raises an exception when invalid override value is specified' do
expect { described_class.load('test') }
.to raise_error(/User configuration value in environment variable JBP_CONFIG_TEST is not valid/)
end
end
context do
let(:environment) do
{ 'JBP_CONFIG_TEST' => '{version:1.8.+}' }
end
it 'diagnoses invalid YAML syntax' do
expect { described_class.load('test') }
.to raise_error(/User configuration value in environment variable JBP_CONFIG_TEST has invalid syntax/)
end
end
end
private
def file_contents(file)
header = []
File.open(file, 'r') do |f|
f.each do |line|
break if line =~ /^---/
header << line
end
end
header
end
end
| apache-2.0 |
joewitt/incubator-nifi | nifi-nar-bundles/nifi-jms-bundle/nifi-jms-processors/src/main/java/org/apache/nifi/jms/processors/MessageBodyToBytesConverter.java | 4042 | /*
* 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.nifi.jms.processors;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import org.apache.commons.io.IOUtils;
/**
*
*/
abstract class MessageBodyToBytesConverter {
/**
*
* @param message instance of {@link TextMessage}
* @return byte array representing the {@link TextMessage}
*/
public static byte[] toBytes(TextMessage message) {
return MessageBodyToBytesConverter.toBytes(message, null);
}
/**
*
* @param message instance of {@link TextMessage}
* @param charset character set used to interpret the TextMessage
* @return byte array representing the {@link TextMessage}
*/
public static byte[] toBytes(TextMessage message, Charset charset) {
try {
if (charset == null) {
return message.getText().getBytes();
} else {
return message.getText().getBytes(charset);
}
} catch (JMSException e) {
throw new MessageConversionException("Failed to convert BytesMessage to byte[]", e);
}
}
/**
*
* @param message instance of {@link BytesMessage}
* @return byte array representing the {@link BytesMessage}
*/
public static byte[] toBytes(BytesMessage message){
try {
InputStream is = new BytesMessageInputStream(message);
return IOUtils.toByteArray(is);
} catch (Exception e) {
throw new MessageConversionException("Failed to convert BytesMessage to byte[]", e);
}
}
private static class BytesMessageInputStream extends InputStream {
private BytesMessage message;
public BytesMessageInputStream(BytesMessage message) {
this.message = message;
}
@Override
public int read() throws IOException {
try {
return this.message.readByte();
} catch (JMSException e) {
throw new IOException(e.toString());
}
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
try {
if (offset == 0) {
return this.message.readBytes(buffer, length);
} else {
return super.read(buffer, offset, length);
}
} catch (JMSException e) {
throw new IOException(e.toString());
}
}
@Override
public int read(byte[] buffer) throws IOException {
try {
return this.message.readBytes(buffer);
} catch (JMSException e) {
throw new IOException(e.toString());
}
}
}
static class MessageConversionException extends RuntimeException {
private static final long serialVersionUID = -1464448549601643887L;
public MessageConversionException(String msg) {
super(msg);
}
public MessageConversionException(String msg, Throwable cause) {
super(msg, cause);
}
}
}
| apache-2.0 |
shahrzadmn/vaadin | uitest/src/com/vaadin/tests/components/grid/GridSubPixelProblemWrappingTest.java | 2018 | /*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.components.grid;
import org.junit.Assert;
import org.junit.Test;
import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.testbench.elements.GridElement;
import com.vaadin.testbench.elements.GridElement.GridRowElement;
import com.vaadin.testbench.parallel.TestCategory;
import com.vaadin.tests.tb3.MultiBrowserTest;
@TestCategory("grid")
public class GridSubPixelProblemWrappingTest extends MultiBrowserTest {
@Test
public void addedRowShouldNotWrap() {
openTestURL();
GridElement grid = $(GridElement.class).first();
// Cells in first row should be at the same y coordinate as the row
assertRowAndCellTops(grid, 0);
// Add a row
$(ButtonElement.class).first().click();
// Cells in the first row should be at the same y coordinate as the row
assertRowAndCellTops(grid, 0);
// Cells in the second row should be at the same y coordinate as the row
assertRowAndCellTops(grid, 1);
}
private void assertRowAndCellTops(GridElement grid, int rowIndex) {
GridRowElement row = grid.getRow(rowIndex);
int rowTop = row.getLocation().y;
int cell0Top = grid.getCell(rowIndex, 0).getLocation().y;
int cell1Top = grid.getCell(rowIndex, 1).getLocation().y;
Assert.assertEquals(rowTop, cell0Top);
Assert.assertEquals(rowTop, cell1Top);
}
}
| apache-2.0 |
adeelmahmood/ignite | examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/QueryWords.java | 3406 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.examples.streaming.wordcount;
import java.util.List;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.affinity.AffinityUuid;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.examples.ExampleNodeStartup;
import org.apache.ignite.examples.ExamplesUtils;
/**
* Periodically query popular numbers from the streaming cache.
* To start the example, you should:
* <ul>
* <li>Start a few nodes using {@link ExampleNodeStartup}.</li>
* <li>Start streaming using {@link StreamWords}.</li>
* <li>Start querying popular words using {@link QueryWords}.</li>
* </ul>
*/
public class QueryWords {
/**
* Schedules words query execution.
*
* @param args Command line arguments (none required).
* @throws Exception If failed.
*/
public static void main(String[] args) throws Exception {
// Mark this cluster member as client.
Ignition.setClientMode(true);
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
if (!ExamplesUtils.hasServerNodes(ignite))
return;
// The cache is configured with sliding window holding 1 second of the streaming data.
IgniteCache<AffinityUuid, String> stmCache = ignite.getOrCreateCache(CacheConfig.wordCache());
// Select top 10 words.
SqlFieldsQuery top10Qry = new SqlFieldsQuery(
"select _val, count(_val) as cnt from String group by _val order by cnt desc limit 10",
true /*collocated*/
);
// Select average, min, and max counts among all the words.
SqlFieldsQuery statsQry = new SqlFieldsQuery(
"select avg(cnt), min(cnt), max(cnt) from (select count(_val) as cnt from String group by _val)");
// Query top 10 popular numbers every 5 seconds.
while (true) {
// Execute queries.
List<List<?>> top10 = stmCache.query(top10Qry).getAll();
List<List<?>> stats = stmCache.query(statsQry).getAll();
// Print average count.
List<?> row = stats.get(0);
if (row.get(0) != null)
System.out.printf("Query results [avg=%.2f, min=%d, max=%d]%n", row.get(0), row.get(1), row.get(2));
// Print top 10 words.
ExamplesUtils.printQueryResults(top10);
Thread.sleep(5000);
}
}
}
} | apache-2.0 |
akromm/azure-sdk-tools | WindowsAzurePowershell/src/Management.Test/Websites/RestoreAzureWebsiteDeploymentTests.cs | 5896 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Test.Websites
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Management.Test.Utilities.Common;
using Microsoft.WindowsAzure.Management.Test.Utilities.Websites;
using Microsoft.WindowsAzure.Management.Utilities.Common;
using Microsoft.WindowsAzure.Management.Utilities.Websites.Services.DeploymentEntities;
using Microsoft.WindowsAzure.Management.Utilities.Websites.Services.WebEntities;
using Microsoft.WindowsAzure.Management.Websites;
using VisualStudio.TestTools.UnitTesting;
[TestClass]
public class RestoreAzureWebsiteDeploymentTests : WebsitesTestBase
{
[TestMethod]
public void RestoreAzureWebsiteDeploymentTest()
{
// Setup
SimpleWebsitesManagement channel = new SimpleWebsitesManagement();
channel.GetWebSpacesThunk = ar => new WebSpaces(new List<WebSpace> { new WebSpace { Name = "webspace1" }, new WebSpace { Name = "webspace2" } });
channel.GetSitesThunk = ar =>
{
if (ar.Values["webspaceName"].Equals("webspace1"))
{
return new Sites(new List<Site> { new Site { Name = "website1", WebSpace = "webspace1", SiteProperties = new SiteProperties
{
Properties = new List<NameValuePair>
{
new NameValuePair { Name = "repositoryuri", Value = "http" },
new NameValuePair { Name = "PublishingUsername", Value = "user1" },
new NameValuePair { Name = "PublishingPassword", Value = "password1" }
}
}}
});
}
return new Sites(new List<Site> { new Site { Name = "website2", WebSpace = "webspace2" } });
};
SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement();
var deployments = new List<DeployResult> { new DeployResult { Id = "id1", Current = false }, new DeployResult { Id = "id2", Current = true } };
deploymentChannel.GetDeploymentsThunk = ar => deployments;
deploymentChannel.DeployThunk = ar =>
{
// Keep track of currently deployed id
DeployResult newDeployment = deployments.FirstOrDefault(d => d.Id.Equals(ar.Values["commitId"]));
if (newDeployment != null)
{
// Make all inactive
deployments.ForEach(d => d.Complete = false);
// Set new to active
newDeployment.Complete = true;
}
};
// Test
RestoreAzureWebsiteDeploymentCommand restoreAzureWebsiteDeploymentCommand =
new RestoreAzureWebsiteDeploymentCommand(channel, deploymentChannel)
{
Name = "website1",
CommitId = "id2",
ShareChannel = true,
CommandRuntime = new MockCommandRuntime(),
CurrentSubscription = new SubscriptionData { SubscriptionId = base.subscriptionId }
};
restoreAzureWebsiteDeploymentCommand.ExecuteCmdlet();
Assert.AreEqual(1, ((MockCommandRuntime) restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.Count);
var responseDeployments = (IEnumerable<DeployResult>)((MockCommandRuntime) restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.FirstOrDefault();
Assert.IsNotNull(responseDeployments);
Assert.AreEqual(2, responseDeployments.Count());
Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id2") && d.Complete));
Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id1") && !d.Complete));
// Change active deployment to id1
restoreAzureWebsiteDeploymentCommand = new RestoreAzureWebsiteDeploymentCommand(channel, deploymentChannel)
{
Name = "website1",
CommitId = "id1",
ShareChannel = true,
CommandRuntime = new MockCommandRuntime(),
CurrentSubscription = new SubscriptionData { SubscriptionId = base.subscriptionId }
};
restoreAzureWebsiteDeploymentCommand.ExecuteCmdlet();
Assert.AreEqual(1, ((MockCommandRuntime)restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.Count);
responseDeployments = (IEnumerable<DeployResult>)((MockCommandRuntime)restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.FirstOrDefault();
Assert.IsNotNull(responseDeployments);
Assert.AreEqual(2, responseDeployments.Count());
Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id1") && d.Complete));
Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id2") && !d.Complete));
}
}
}
| apache-2.0 |
ern/elasticsearch | server/src/test/java/org/elasticsearch/rest/RestHttpResponseHeadersTests.java | 6347 | /*
* 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.rest;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService;
import org.elasticsearch.rest.RestHandler.Route;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.rest.FakeRestChannel;
import org.elasticsearch.test.rest.FakeRestRequest;
import org.elasticsearch.usage.UsageService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
public class RestHttpResponseHeadersTests extends ESTestCase {
/**
* For requests to a valid REST endpoint using an unsupported HTTP method,
* verify that a 405 HTTP response code is returned, and that the response
* 'Allow' header includes a list of valid HTTP methods for the endpoint
* (see
* <a href="https://tools.ietf.org/html/rfc2616#section-10.4.6">HTTP/1.1 -
* 10.4.6 - 405 Method Not Allowed</a>).
*/
public void testUnsupportedMethodResponseHttpHeader() throws Exception {
/*
* Generate a random set of candidate valid HTTP methods to register
* with the test RestController endpoint. Enums are returned in the
* order they are declared, so the first step is to shuffle the HTTP
* method list, passing in the RandomizedContext's Random instance,
* before picking out a candidate sublist.
*/
List<RestRequest.Method> validHttpMethodArray = new ArrayList<>(Arrays.asList(RestRequest.Method.values()));
validHttpMethodArray.remove(RestRequest.Method.OPTIONS);
Collections.shuffle(validHttpMethodArray, random());
/*
* The upper bound of the potential sublist is one less than the size of
* the array, so we are guaranteed at least one invalid method to test.
*/
validHttpMethodArray = validHttpMethodArray.subList(0, randomIntBetween(1, validHttpMethodArray.size() - 1));
assert(validHttpMethodArray.size() > 0);
assert(validHttpMethodArray.size() < RestRequest.Method.values().length);
/*
* Generate an inverse list of one or more candidate invalid HTTP
* methods, so we have a candidate method to fire at the test endpoint.
*/
List<RestRequest.Method> invalidHttpMethodArray = new ArrayList<>(Arrays.asList(RestRequest.Method.values()));
invalidHttpMethodArray.removeAll(validHttpMethodArray);
// Remove OPTIONS, or else we'll get a 200 instead of 405
invalidHttpMethodArray.remove(RestRequest.Method.OPTIONS);
assert(invalidHttpMethodArray.size() > 0);
// Initialize test candidate RestController
CircuitBreakerService circuitBreakerService = new HierarchyCircuitBreakerService(Settings.EMPTY,
Collections.emptyList(),
new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS));
final Settings settings = Settings.EMPTY;
UsageService usageService = new UsageService();
RestController restController = new RestController(Collections.emptySet(),
null, null, circuitBreakerService, usageService);
// A basic RestHandler handles requests to the endpoint
RestHandler restHandler = (request, channel, client) -> channel.sendResponse(new TestResponse());
// Register valid test handlers with test RestController
for (RestRequest.Method method : validHttpMethodArray) {
restController.registerHandler(new Route(method, "/"), restHandler);
}
// Generate a test request with an invalid HTTP method
FakeRestRequest.Builder fakeRestRequestBuilder = new FakeRestRequest.Builder(xContentRegistry());
fakeRestRequestBuilder.withMethod(invalidHttpMethodArray.get(0));
RestRequest restRequest = fakeRestRequestBuilder.build();
// Send the request and verify the response status code
FakeRestChannel restChannel = new FakeRestChannel(restRequest, false, 1);
restController.dispatchRequest(restRequest, restChannel, new ThreadContext(Settings.EMPTY));
assertThat(restChannel.capturedResponse().status().getStatus(), is(405));
/*
* Verify the response allow header contains the valid methods for the
* test endpoint
*/
assertThat(restChannel.capturedResponse().getHeaders().get("Allow"), notNullValue());
String responseAllowHeader = restChannel.capturedResponse().getHeaders().get("Allow").get(0);
List<String> responseAllowHeaderArray = Arrays.asList(responseAllowHeader.split(","));
assertThat(responseAllowHeaderArray.size(), is(validHttpMethodArray.size()));
assertThat(responseAllowHeaderArray, containsInAnyOrder(getMethodNameStringArray(validHttpMethodArray).toArray()));
}
private static class TestResponse extends RestResponse {
@Override
public String contentType() {
return null;
}
@Override
public BytesReference content() {
return null;
}
@Override
public RestStatus status() {
return RestStatus.OK;
}
}
/**
* Convert an RestRequest.Method array to a String array, so it can be
* compared with the expected 'Allow' header String array.
*/
private List<String> getMethodNameStringArray(List<RestRequest.Method> methodArray) {
return methodArray.stream().map(method -> method.toString()).collect(Collectors.toList());
}
}
| apache-2.0 |
madawas/carbon-device-mgt | components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java | 39279 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.core.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.mock.MockConnection;
import org.wso2.carbon.device.mgt.core.mock.MockDataSource;
import org.wso2.carbon.device.mgt.core.mock.MockResultSet;
import org.wso2.carbon.device.mgt.core.mock.MockStatement;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTest {
private static final Log log = LogFactory.getLog(DeviceManagementProviderServiceTest.class);
public static final String DEVICE_ID = "9999";
private static final String ALTERNATE_DEVICE_ID = "1128";
private DeviceManagementProviderService providerService;
private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE";
private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO();
DeviceManagementProviderService deviceMgtService;
@BeforeClass
public void init() throws Exception {
DeviceConfigurationManager.getInstance().initConfig();
log.info("Initializing");
deviceMgtService = new DeviceManagementProviderServiceImpl();
DeviceManagementServiceComponent.notifyStartupListeners();
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
}
private RegistryService getRegistryService() throws RegistryException {
RealmService realmService = new InMemoryRealmService();
RegistryDataHolder.getInstance().setRealmService(realmService);
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
context.setSetup(true);
return context.getEmbeddedRegistryService();
}
@Test
public void testGetAvailableDeviceTypes() throws DeviceManagementException {
List<DeviceType> deviceTypes = deviceMgtService.getDeviceTypes();
if (!isMock()) {
Assert.assertTrue(deviceTypes.size() > 0);
}
}
@Test
public void testGetAvailableDeviceType() throws DeviceManagementException {
DeviceType deviceType = deviceMgtService.getDeviceType(DEVICE_TYPE);
if (!isMock()) {
Assert.assertTrue(deviceType.getName().equalsIgnoreCase(DEVICE_TYPE));
}
}
@Test
public void addLicense() throws DeviceManagementException {
License license = new License();
license.setLanguage("ENG");
license.setName("RANDON_DEVICE_LICENSE");
deviceMgtService.addLicense(DEVICE_TYPE, license);
}
@Test(expectedExceptions = DeviceManagementException.class)
public void testNullDeviceEnrollment() throws DeviceManagementException {
deviceMgtService.enrollDevice(null);
}
@Test
public void testSuccessfulDeviceEnrollment() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE));
MockDataSource dataSource = null;
if (isMock()) {
Field datasourceField = DeviceManagementDAOFactory.class.getDeclaredField("dataSource");
datasourceField.setAccessible(true);
dataSource = (MockDataSource) getDataSource();
dataSource.setConnection(new MockConnection(dataSource.getUrl()));
MockConnection connection = new MockConnection(dataSource.getUrl());
dataSource.setConnection(connection);
MockStatement mockStatement = new MockStatement();
MockResultSet resultSet = new MockResultSet();
resultSet.addInteger(1);
resultSet.addString(null);
mockStatement.addResultSet(resultSet);
connection.addMockStatement(mockStatement);
datasourceField.set(datasourceField, dataSource);
}
try {
boolean enrollmentStatus = deviceMgtService.enrollDevice(device);
Assert.assertTrue(enrollmentStatus);
} finally {
if (dataSource != null) {
dataSource.reset();
}
}
}
@Test(dependsOnMethods = "testSuccessfulDeviceEnrollment")
public void testIsEnrolled() throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(DEVICE_ID);
deviceIdentifier.setType(DEVICE_TYPE);
boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier);
if (!isMock()) {
Assert.assertTrue(enrollmentStatus);
}
}
@Test
public void testIsEnrolledForNonExistingDevice() throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId("34535235235235235");
deviceIdentifier.setType(DEVICE_TYPE);
boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier);
Assert.assertFalse(enrollmentStatus);
}
@Test(expectedExceptions = DeviceManagementException.class)
public void testIsEnrolledForNullDevice() throws DeviceManagementException {
deviceMgtService.isEnrolled(null);
}
@Test
public void testNonExistentDeviceType() throws DeviceManagementException {
Device device = TestDataHolder.generateDummyDeviceData("abc");
boolean enrollmentStatus = deviceMgtService.enrollDevice(device);
Assert.assertFalse(enrollmentStatus);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testReEnrollmentofSameDeviceUnderSameUser() throws DeviceManagementException {
if (!isMock()) {
Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE));
boolean enrollment = deviceMgtService.enrollDevice(device);
Assert.assertTrue(enrollment);
}
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"})
public void testReEnrollmentofSameDeviceWithOtherUser() throws DeviceManagementException {
if (!isMock()) {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setOwner("user1");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
Device alternateDevice = TestDataHolder.generateDummyDeviceData(DEVICE_ID, DEVICE_TYPE,
enrolmentInfo);
Device retrievedDevice1 = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE));
deviceMgtService.enrollDevice(alternateDevice);
Device retrievedDevice2 = deviceMgtService.getDevice(new DeviceIdentifier(alternateDevice
.getDeviceIdentifier(), alternateDevice.getType()));
Assert.assertFalse(retrievedDevice1.getEnrolmentInfo().getOwner().equalsIgnoreCase
(retrievedDevice2.getEnrolmentInfo().getOwner()));
}
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"})
public void testDisenrollment() throws DeviceManagementException {
if (!isMock()) {
Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE));
boolean disenrollmentStatus = deviceMgtService.disenrollDevice(new DeviceIdentifier
(device.getDeviceIdentifier(), device.getType()));
log.info(disenrollmentStatus);
Assert.assertTrue(disenrollmentStatus);
}
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"}, expectedExceptions =
DeviceManagementException.class)
public void testDisenrollmentWithNullDeviceID() throws DeviceManagementException {
deviceMgtService.disenrollDevice(null);
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"})
public void testDisenrollmentWithNonExistentDT() throws DeviceManagementException {
Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID,
"NON_EXISTENT_DT"));
boolean result = deviceMgtService.disenrollDevice(new DeviceIdentifier(
device.getDeviceIdentifier(), device.getType()));
Assert.assertTrue(!result);
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"})
public void testDisenrollmentWithNonExistentDevice() throws DeviceManagementException {
Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(ALTERNATE_DEVICE_ID,
DEVICE_TYPE));
boolean result = deviceMgtService.disenrollDevice(new DeviceIdentifier(
device.getDeviceIdentifier(), device.getType()));
Assert.assertTrue(!result);
}
@Test(dependsOnMethods = {"testDisenrollment"})
public void testDisenrollAlreadyDisEnrolledDevice() throws DeviceManagementException {
if (!isMock()) {
Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE));
boolean result = deviceMgtService.disenrollDevice(new DeviceIdentifier(
device.getDeviceIdentifier(), device.getType()));
Assert.assertTrue(result);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceCount() throws DeviceManagementException {
int count = deviceMgtService.getDeviceCount();
if (!isMock()) {
Assert.assertTrue(count > 0);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceCountForUser() throws DeviceManagementException {
int count = deviceMgtService.getDeviceCount(TestDataHolder.OWNER);
if (!isMock()) {
Assert.assertTrue(count > 0);
}
}
@Test
public void testGetDeviceCountForNonExistingUser() throws DeviceManagementException {
int count = deviceMgtService.getDeviceCount("ABCD");
Assert.assertEquals(count, 0);
}
@Test(expectedExceptions = DeviceManagementException.class)
public void testGetDeviceCountForNullUser() throws DeviceManagementException {
deviceMgtService.getDeviceCount(null);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testIsActive() throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier);
deviceIdentifier.setType(DEVICE_TYPE);
Assert.assertTrue(deviceMgtService.isActive(deviceIdentifier));
}
@Test
public void testIsActiveForNonExistingDevice() throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId("34535235235235235");
deviceIdentifier.setType("TEST_TYPE");
Assert.assertFalse(deviceMgtService.isActive(deviceIdentifier));
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testSetActive() throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier);
deviceIdentifier.setType(DEVICE_TYPE);
Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true));
}
@Test
public void testSetActiveForNonExistingDevice() throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId("34535235235235235");
deviceIdentifier.setType("TEST_TYPE");
Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true));
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceEnrolledTenants() throws DeviceManagementException {
List<Integer> tenants = deviceMgtService.getDeviceEnrolledTenants();
if (!isMock()) {
Assert.assertEquals(tenants.size(), 1);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDevice() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException {
MockDataSource dataSource = setDatasourceForGetDevice();
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE));
cleanupMockDatasource(dataSource);
Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase(DEVICE_ID));
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceWithInfo() throws DeviceManagementException {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)
, true);
if (!isMock()) {
Assert.assertTrue(device.getDeviceInfo() != null);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceTypeWithProps() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
MockDataSource dataSource = setDatasourceForGetDevice();
Device device = deviceMgtService.getDeviceWithTypeProperties(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE));
cleanupMockDatasource(dataSource);
Assert.assertTrue(!device.getProperties().isEmpty());
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceWithOutInfo() throws DeviceManagementException {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)
, false);
if (!isMock()) {
Assert.assertTrue(device.getDeviceInfo() == null);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesOfRole() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException {
MockDataSource dataSource = setDatasourceForGetDevice();
List<Device> devices = deviceMgtService.getAllDevicesOfRole("admin");
cleanupMockDatasource(dataSource);
Assert.assertTrue(devices.size() > 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testGetAllDevicesOfRoleFailureFlow() throws DeviceManagementException, UserStoreException, NoSuchFieldException, IllegalAccessException {
int tenantID = -1234;
RealmService mockRealmService = Mockito.mock(RealmService.class, Mockito.CALLS_REAL_METHODS);
Mockito.doThrow(new UserStoreException("Mocked Exception when obtaining Tenant Realm"))
.when(mockRealmService).getTenantUserRealm(tenantID);
RealmService currentRealm = DeviceManagementDataHolder.getInstance().getRealmService();
DeviceManagementDataHolder.getInstance().setRealmService(mockRealmService);
try {
deviceMgtService.getAllDevicesOfRole("admin");
} finally {
DeviceManagementDataHolder.getInstance().setRealmService(currentRealm);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesOfRoleWithNonExistentRole() throws DeviceManagementException {
List<Device> devices = deviceMgtService.getAllDevicesOfRole("non-existent-role");
Assert.assertTrue(devices.size() == 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testGetAllDevicesOfRoleWithNullArgs() throws DeviceManagementException {
deviceMgtService.getAllDevicesOfRole(null);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testDeviceByOwner() throws DeviceManagementException {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE), "admin", true);
if (!isMock()) {
Assert.assertTrue(device != null);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testDeviceByOwnerAndNonExistentDeviceID() throws DeviceManagementException {
String nonExistentDeviceID = "4455";
Device device = deviceMgtService.getDevice(new DeviceIdentifier(nonExistentDeviceID,
DEVICE_TYPE), "admin", true);
Assert.assertTrue(device == null);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testDeviceByOwnerWithNullDeviceID() throws DeviceManagementException {
deviceMgtService.getDevice(null, "admin", true);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testDeviceByDate() throws DeviceManagementException, TransactionManagementException,
DeviceDetailsMgtDAOException, NoSuchFieldException, IllegalAccessException {
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE));
addDeviceInformation(initialDevice);
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE), yesterday());
cleanupMockDatasource(dataSource);
if (!isMock()) {
Assert.assertTrue(device != null);
}
}
private MockResultSet getMockGetDeviceResult() {
MockResultSet resultSet = new MockResultSet();
resultSet.addInteger(1);
resultSet.addString("Test");
resultSet.addString(null);
resultSet.addString(DEVICE_TYPE);
resultSet.addString(DEVICE_ID);
resultSet.addInteger(0);
resultSet.addString("admin");
resultSet.addString("BYOD");
resultSet.addTimestamp(new Timestamp(System.currentTimeMillis()));
resultSet.addTimestamp(new Timestamp(System.currentTimeMillis()));
resultSet.addString("ACTIVE");
return resultSet;
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testUpdateDeviceInfo() throws DeviceManagementException,
TransactionManagementException, DeviceDetailsMgtDAOException {
if (!isMock()) {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE));
boolean status = deviceMgtService.updateDeviceInfo(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE), device);
Assert.assertTrue(status);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testDeviceByDateWithNonExistentDevice() throws DeviceManagementException,
TransactionManagementException, DeviceDetailsMgtDAOException {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(ALTERNATE_DEVICE_ID,
DEVICE_TYPE), yesterday());
Assert.assertTrue(device == null);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testDeviceByDateWithNullDeviceID() throws DeviceManagementException {
deviceMgtService.getDevice(null, yesterday());
}
private void addDeviceInformation(Device initialDevice) throws TransactionManagementException, DeviceDetailsMgtDAOException {
DeviceManagementDAOFactory.beginTransaction();
//Device details table will be reffered when looking for last updated time
//This dao entry is to mimic a device info operation
deviceDetailsDAO.addDeviceInformation(initialDevice.getId(), initialDevice.getEnrolmentInfo().getId(),
TestDataHolder
.generateDummyDeviceInfo());
DeviceManagementDAOFactory.closeConnection();
}
@Test(dependsOnMethods = {"testDeviceByDate"})
public void testDeviceByDateAndOwner() throws DeviceManagementException {
if (!isMock()) {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE), "admin", yesterday(), true);
Assert.assertTrue(device != null);
}
}
@Test
public void testGetAvaliableDeviceTypes() throws DeviceManagementException {
List<String> deviceTypes = deviceMgtService.getAvailableDeviceTypes();
if (!isMock()) {
Assert.assertTrue(!deviceTypes.isEmpty());
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevices() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException {
MockDataSource dataSource = setDatasourceForGetDevice();
List<Device> devices = deviceMgtService.getAllDevices();
cleanupMockDatasource(dataSource);
Assert.assertTrue(!devices.isEmpty());
}
private MockDataSource setDatasourceForGetDevice() throws IllegalAccessException, NoSuchFieldException {
MockDataSource dataSource = null;
if (isMock()) {
Field datasourceField = DeviceManagementDAOFactory.class.getDeclaredField("dataSource");
datasourceField.setAccessible(true);
dataSource = (MockDataSource) getDataSource();
//connection used for first get device operation.
MockConnection connection = new MockConnection(dataSource.getUrl());
dataSource.setConnection(connection);
MockStatement mockStatement = new MockStatement();
mockStatement.addResultSet(getMockGetDeviceResult());
connection.addMockStatement(mockStatement);
datasourceField.set(datasourceField, dataSource);
}
return dataSource;
}
private void cleanupMockDatasource(MockDataSource dataSource) {
if (isMock()) {
if (dataSource != null) {
dataSource.reset();
}
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesPaginated() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setOwnerRole("admin");
MockDataSource dataSource = setDatasourceForGetDevice();
PaginationResult result = deviceMgtService.getAllDevices(request);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testGetAllDevicesWithNullRequest() throws DeviceManagementException {
PaginationRequest request = null;
deviceMgtService.getAllDevices(request);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesByName() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setDeviceName(DEVICE_TYPE + "-" + DEVICE_ID);
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
PaginationResult result = deviceMgtService.getDevicesByName(request);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesByNameAndType() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setDeviceName(DEVICE_TYPE + "-" + DEVICE_ID);
request.setDeviceType(DEVICE_TYPE);
MockDataSource dataSource = setDatasourceForGetDevice();
List<Device> devices = deviceMgtService.getDevicesByNameAndType(request, true);
cleanupMockDatasource(dataSource);
Assert.assertTrue(!devices.isEmpty());
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesByStatus() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setStatus(EnrolmentInfo.Status.ACTIVE.toString());
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
PaginationResult result = deviceMgtService.getDevicesByStatus(request, true);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
private void setMockDeviceCount(MockConnection connection) {
MockStatement statement = new MockStatement();
connection.addMockStatement(statement);
MockResultSet resultSet = new MockResultSet();
resultSet.addInteger(1);
statement.addResultSet(resultSet);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDevicesOfTypePaginated() throws DeviceManagementException {
if (!isMock()) {
PaginationRequest request = new PaginationRequest(0, 100);
request.setDeviceType(DEVICE_TYPE);
PaginationResult result = deviceMgtService.getDevicesByType(request);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesWithInfo() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
MockDataSource dataSource = setDatasourceForGetDevice();
List<Device> devices = deviceMgtService.getAllDevices(true);
cleanupMockDatasource(dataSource);
Assert.assertTrue(!devices.isEmpty());
Assert.assertTrue(devices.get(0).getDeviceInfo() != null);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetAllDevicesWithInfoPaginated() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
PaginationResult result = deviceMgtService.getAllDevices(request, true);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetTenantedDevice() throws DeviceManagementException {
HashMap<Integer, Device> deviceMap = deviceMgtService.getTenantedDevice(new
DeviceIdentifier
(DEVICE_ID, DEVICE_TYPE));
if (!isMock()) {
Assert.assertTrue(!deviceMap.isEmpty());
}
}
@Test
public void testGetLicense() throws DeviceManagementException {
License license = deviceMgtService.getLicense(DEVICE_TYPE, "ENG");
Assert.assertTrue(license.getLanguage().equalsIgnoreCase("ENG"));
}
@Test(expectedExceptions = DeviceManagementException.class)
public void testSendRegistrationEmailNoMetaInfo() throws ConfigurationManagementException, DeviceManagementException {
deviceMgtService.sendRegistrationEmail(null);
Assert.assertTrue(false);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testGetDeviesOfUser() throws DeviceManagementException {
String username = null;
deviceMgtService.getDevicesOfUser(username);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviesOfUserWhileUserNull() throws DeviceManagementException {
if (!isMock()) {
List<Device> devices = deviceMgtService.getDevicesOfUser("admin");
Assert.assertTrue(!devices.isEmpty());
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDevieByStatus() throws DeviceManagementException {
if (!isMock()) {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE), EnrolmentInfo.Status.ACTIVE);
Assert.assertTrue(device != null);
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDevieByDate() throws DeviceManagementException {
if (!isMock()) {
List<Device> devices = deviceMgtService.getDevices(yesterday());
Assert.assertTrue(!devices.isEmpty());
}
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviesOfUserPaginated() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setOwner("admin");
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
PaginationResult result = deviceMgtService.getDevicesOfUser(request, true);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testGetDeviesOfUserWhileNullOwnerPaginated() throws DeviceManagementException {
PaginationRequest request = null;
deviceMgtService.getDevicesOfUser(request, true);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviesByOwnership() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setOwnership(EnrolmentInfo.OwnerShip.BYOD.toString());
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
PaginationResult result = deviceMgtService.getDevicesByOwnership(request);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testSetOwnership() throws DeviceManagementException {
boolean status = deviceMgtService.setOwnership(new DeviceIdentifier(DEVICE_ID,
DEVICE_TYPE), EnrolmentInfo.OwnerShip.COPE.toString());
Assert.assertTrue(status);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testSetOwnershipNonExistentDT() throws DeviceManagementException {
boolean status = deviceMgtService.setOwnership(new DeviceIdentifier(DEVICE_ID,
"non-existent-dt"), EnrolmentInfo.OwnerShip.COPE.toString());
Assert.assertFalse(status);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class)
public void testSetOwnershipOfNullDevice() throws DeviceManagementException {
deviceMgtService.setOwnership(null, EnrolmentInfo.OwnerShip.COPE.toString());
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviesByStatus() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100);
request.setStatus("ACTIVE");
MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0));
}
PaginationResult result = deviceMgtService.getDevicesByStatus(request);
cleanupMockDatasource(dataSource);
Assert.assertTrue(result.getRecordsTotal() > 0);
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"})
public void testUpdateDevicesStatus() throws DeviceManagementException {
if (!isMock()) {
boolean status = deviceMgtService.setStatus("user1", EnrolmentInfo.Status.REMOVED);
Assert.assertTrue(status);
}
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"})
public void testUpdateDevicesStatusWithDeviceID() throws DeviceManagementException {
if (!isMock()) {
boolean status = deviceMgtService.setStatus(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE), "user1",
EnrolmentInfo.Status.ACTIVE);
Assert.assertTrue(status);
}
}
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"})
public void testUpdateDevicesStatusOfNonExistingUser() throws DeviceManagementException {
boolean status = deviceMgtService.setStatus("random-user", EnrolmentInfo.Status.REMOVED);
Assert.assertFalse(status);
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviesOfUserAndDeviceType() throws DeviceManagementException {
if (!isMock()) {
List<Device> devices = deviceMgtService.getDevicesOfUser("admin", DEVICE_TYPE, true);
Assert.assertTrue(!devices.isEmpty() && devices.get(0).getType().equalsIgnoreCase
(DEVICE_TYPE) && devices.get(0).getDeviceInfo() != null);
}
}
@Test
public void testSendRegistrationEmailSuccessFlow() throws ConfigurationManagementException, DeviceManagementException {
String recipient = "test-user@wso2.com";
Properties props = new Properties();
props.setProperty("first-name", "Test");
props.setProperty("username", "User");
props.setProperty("password", "!@#$$$%");
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
deviceMgtService.sendRegistrationEmail(metaInfo);
Assert.assertTrue(true);
}
@Test
public void testSendEnrollmentInvitation() throws ConfigurationManagementException,
DeviceManagementException {
String recipient = "test-user@wso2.com";
Properties props = new Properties();
props.setProperty("first-name", "Test");
props.setProperty("username", "User");
props.setProperty("password", "!@#$$$%");
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
deviceMgtService.sendEnrolmentInvitation("template-name", metaInfo);
Assert.assertTrue(true);
}
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
} | apache-2.0 |
fceller/arangodb | 3rdParty/boost/1.69.0/libs/hana/test/map/symmetric_difference.cpp | 2454 | // Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/symmetric_difference.hpp>
#include <laws/base.hpp>
#include <support/minimal_product.hpp>
namespace hana = boost::hana;
using hana::test::ct_eq;
template <int i>
auto key() { return hana::test::ct_eq<i>{}; }
template <int i>
auto val() { return hana::test::ct_eq<-i>{}; }
template <int i, int j>
auto p() { return ::minimal_product(key<i>(), val<j>()); }
int main() {
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::symmetric_difference(
hana::make_map(),
hana::make_map()
),
hana::make_map()
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::symmetric_difference(
hana::make_map(p<1, 1>()),
hana::make_map(p<1, 1>())
),
hana::make_map()
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::symmetric_difference(
hana::make_map(p<1, 2>()),
hana::make_map(p<2, 4>())
),
hana::make_map(p<1, 2>(),
p<2, 4>())
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::symmetric_difference(
hana::make_map(p<1, 2>(),
p<2, 22>()),
hana::make_map(p<2, 4>(),
p<3, 33>())
),
hana::make_map(p<1, 2>(),
p<3, 33>())
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::symmetric_difference(
hana::make_map(p<1, 2>(),
p<2, 22>(),
p<3, 33>(),
p<5, 55>(),
p<8, 88>()),
hana::make_map(p<2, 4>(),
p<3, 33>(),
p<4, 44>(),
p<9, 99>())
),
hana::make_map(p<1, 2>(),
p<5, 55>(),
p<8, 88>(),
p<4, 44>(),
p<9, 99>())
));
}
| apache-2.0 |
fanyon/flink | flink-runtime/src/test/java/org/apache/flink/runtime/util/BlockingShutdownTest.java | 7473 | /*
* 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.flink.runtime.util;
import org.apache.flink.core.testutils.CommonTestUtils;
import org.apache.flink.runtime.testutils.TestJvmProcess;
import org.apache.flink.util.OperatingSystem;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
/**
* Test that verifies the behavior of blocking shutdown hooks and of the
* {@link JvmShutdownSafeguard} that guards against it.
*/
public class BlockingShutdownTest {
@Test
public void testProcessShutdownBlocking() throws Exception {
// this test works only on linux
assumeTrue(OperatingSystem.isLinux());
// this test leaves remaining processes if not executed with Java 8
CommonTestUtils.assumeJava8();
final File markerFile = new File(
EnvironmentInformation.getTemporaryFileDirectory(), UUID.randomUUID() + ".marker");
final BlockingShutdownProcess blockingProcess =
new BlockingShutdownProcess(markerFile.getAbsolutePath(), 0, false);
try {
blockingProcess.startProcess();
long pid = blockingProcess.getProcessId();
assertTrue("Cannot determine process ID", pid != -1);
// wait for the marker file to appear, which means the process is up properly
TestJvmProcess.waitForMarkerFile(markerFile, 30000);
// send it a regular kill command (SIG_TERM)
Process kill = Runtime.getRuntime().exec("kill " + pid);
kill.waitFor();
assertEquals("failed to send SIG_TERM to process", 0, kill.exitValue());
// minimal delay until the Java process object notices that the process is gone
// this will not let the test fail predictably if the process is actually in fact going away,
// but it would create frequent failures. Not ideal, but the best we can do without
// severely prolonging the test
Thread.sleep(50);
// the process should not go away by itself
assertTrue("Test broken, process shutdown blocking does not work", blockingProcess.isAlive());
}
finally {
blockingProcess.destroy();
//noinspection ResultOfMethodCallIgnored
markerFile.delete();
}
}
@Test
public void testProcessExitsDespiteBlockingShutdownHook() throws Exception {
// this test works only on linux
assumeTrue(OperatingSystem.isLinux());
final File markerFile = new File(
EnvironmentInformation.getTemporaryFileDirectory(), UUID.randomUUID() + ".marker");
final BlockingShutdownProcess blockingProcess =
new BlockingShutdownProcess(markerFile.getAbsolutePath(), 100, true);
try {
blockingProcess.startProcess();
long pid = blockingProcess.getProcessId();
assertTrue("Cannot determine process ID", pid != -1);
// wait for the marker file to appear, which means the process is up properly
TestJvmProcess.waitForMarkerFile(markerFile, 30000);
// send it a regular kill command (SIG_TERM)
Process kill = Runtime.getRuntime().exec("kill " + pid);
kill.waitFor();
assertEquals("failed to send SIG_TERM to process", 0, kill.exitValue());
// the process should eventually go away
final long deadline = System.nanoTime() + 30_000_000_000L; // 30 secs in nanos
while (blockingProcess.isAlive() && System.nanoTime() < deadline) {
Thread.sleep(50);
}
assertFalse("shutdown blocking process does not properly terminate itself", blockingProcess.isAlive());
}
finally {
blockingProcess.destroy();
//noinspection ResultOfMethodCallIgnored
markerFile.delete();
}
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
// a method that blocks indefinitely
static void parkForever() {
// park this forever
final Object lock = new Object();
//noinspection InfiniteLoopStatement
while (true) {
try {
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException ignored) {}
}
}
// ------------------------------------------------------------------------
// Blocking Process Implementation
// ------------------------------------------------------------------------
private static final class BlockingShutdownProcess extends TestJvmProcess {
private final String tempFilePath;
private final long selfKillDelay;
private final boolean installSignalHandler;
public BlockingShutdownProcess(String tempFilePath, long selfKillDelay, boolean installSignalHandler)
throws Exception {
this.tempFilePath = tempFilePath;
this.selfKillDelay = selfKillDelay;
this.installSignalHandler = installSignalHandler;
}
@Override
public String getName() {
return "BlockingShutdownProcess";
}
@Override
public String[] getJvmArgs() {
return new String[] { tempFilePath, String.valueOf(installSignalHandler), String.valueOf(selfKillDelay) };
}
@Override
public String getEntryPointClassName() {
return BlockingShutdownProcessEntryPoint.class.getName();
}
}
// ------------------------------------------------------------------------
public static final class BlockingShutdownProcessEntryPoint {
private static final Logger LOG = LoggerFactory.getLogger(BlockingShutdownProcessEntryPoint.class);
public static void main(String[] args) throws Exception {
File touchFile = new File(args[0]);
boolean installHandler = Boolean.parseBoolean(args[1]);
long killDelay = Long.parseLong(args[2]);
// install the blocking shutdown hook
Thread shutdownHook = new Thread(new BlockingRunnable(), "Blocking ShutdownHook");
try {
// Add JVM shutdown hook to call shutdown of service
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
catch (IllegalStateException ignored) {
// JVM is already shutting down. No need to do this.
}
catch (Throwable t) {
System.err.println("Cannot register process cleanup shutdown hook.");
t.printStackTrace();
}
// install the jvm terminator, if we want it
if (installHandler) {
JvmShutdownSafeguard.installAsShutdownHook(LOG, killDelay);
}
System.err.println("signaling process started");
TestJvmProcess.touchFile(touchFile);
System.err.println("parking the main thread");
parkForever();
}
}
// ------------------------------------------------------------------------
static final class BlockingRunnable implements Runnable {
@Override
public void run() {
System.err.println("starting shutdown hook");
parkForever();
}
}
}
| apache-2.0 |
StCostea/k3po | lang/src/main/java/org/kaazing/k3po/lang/internal/el/VariableMapper.java | 1349 | /**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.k3po.lang.internal.el;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.el.ValueExpression;
public class VariableMapper extends javax.el.VariableMapper {
protected final ConcurrentMap<String, ValueExpression> variables;
public VariableMapper() {
variables = new ConcurrentHashMap<>();
}
@Override
public ValueExpression resolveVariable(String name) {
return variables.get(name);
}
@Override
public ValueExpression setVariable(String name,
ValueExpression expr) {
return expr == null ? variables.remove(name) : variables.put(name, expr);
}
}
| apache-2.0 |
flingone/frameworks_base_cmds_remoted | libs/boost/libs/iostreams/test/detail/null_padded_codecvt.hpp | 9908 | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2004-2007 Jonathan Turkanis
// 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.)
// See http://www.boost.org/libs/iostreams for documentation.
// Contains the definitions of two codecvt facets useful for testing code
// conversion. Both represent the "null padded" character encoding described as
// follows. A wide character can be represented by the encoding if its value V
// is within the range of an unsigned char. The first char of the sequence
// representing V is V % 3 + 1. This is followed by V % 3 null characters, and
// finally by V itself.
// The first codecvt facet, null_padded_codecvt, is statefull, with state_type
// equal to int.
// The second codecvt facet, stateless_null_padded_codecvt, is stateless. At
// each point in a conversion, no characters are consumed unless there is room
// in the output sequence to write an entire multibyte sequence.
#ifndef BOOST_IOSTREAMS_TEST_NULL_PADDED_CODECVT_HPP_INCLUDED
#define BOOST_IOSTREAMS_TEST_NULL_PADDED_CODECVT_HPP_INCLUDED
#include <boost/config.hpp> // NO_STDC_NAMESPACE
#include <boost/iostreams/detail/codecvt_helper.hpp>
#include <boost/iostreams/detail/config/wide_streams.hpp>
#include <cstddef> // mbstate_t.
#include <locale> // codecvt.
#include <boost/integer_traits.hpp> // const_max.
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::mbstate_t; }
#endif
namespace boost { namespace iostreams { namespace test {
//------------------Definition of null_padded_codecvt_state-------------------//
class null_padded_codecvt_state {
public:
null_padded_codecvt_state(int val = 0) : val_(val) { }
operator int() const { return val_; }
int& val() { return val_; }
const int& val() const { return val_; }
private:
int val_;
};
} } }
BOOST_IOSTREAMS_CODECVT_SPEC(boost::iostreams::test::null_padded_codecvt_state)
namespace boost { namespace iostreams { namespace test {
//------------------Definition of null_padded_codevt--------------------------//
//
// state is initially 0. After a single character is consumed, state is set to
// the number of characters in the current multibyte sequence and decremented
// as each character is consumed until its value reaches 0 again.
//
class null_padded_codecvt
: public iostreams::detail::codecvt_helper<
wchar_t, char, null_padded_codecvt_state
>
{
public:
typedef null_padded_codecvt_state state_type;
private:
std::codecvt_base::result
do_in( state_type& state, const char* first1, const char* last1,
const char*& next1, wchar_t* first2, wchar_t* last2,
wchar_t*& next2 ) const
{
using namespace std;
if (state < 0 || state > 3)
return codecvt_base::error;
next1 = first1;
next2 = first2;
while (next2 != last2 && next1 != last1) {
while (next1 != last1) {
if (state == 0) {
if (*next1 < 1 || *next1 > 3)
return codecvt_base::error;
state = *next1++;
} else if (state == 1) {
*next2++ = (unsigned char) *next1++;
state = 0;
break;
} else {
if (*next1++ != 0)
return codecvt_base::error;
--state.val();
}
}
}
return next2 == last2 ?
codecvt_base::ok :
codecvt_base::partial;
}
std::codecvt_base::result
do_out( state_type& state, const wchar_t* first1, const wchar_t* last1,
const wchar_t*& next1, char* first2, char* last2,
char*& next2 ) const
{
using namespace std;
if (state < 0 || state > 3)
return codecvt_base::error;
next1 = first1;
next2 = first2;
while (next1 != last1 && next2 != last2) {
while (next2 != last2) {
if (state == 0) {
if (*next1 > integer_traits<unsigned char>::const_max)
return codecvt_base::noconv;
state = *next1 % 3 + 1;
*next2++ = static_cast<char>(state);
} else if (state == 1) {
state = 0;
*next2++ = static_cast<unsigned char>(*next1++);
break;
} else {
--state.val();
*next2++ = 0;
}
}
}
return next1 == last1 ?
codecvt_base::ok :
codecvt_base::partial;
}
std::codecvt_base::result
do_unshift( state_type& state,
char* /* first2 */,
char* last2,
char*& next2 ) const
{
using namespace std;
next2 = last2;
while (state.val()-- > 0)
if (next2 != last2)
*next2++ = 0;
else
return codecvt_base::partial;
return codecvt_base::ok;
}
bool do_always_noconv() const throw() { return false; }
int do_max_length() const throw() { return 4; }
int do_encoding() const throw() { return -1; }
int do_length( BOOST_IOSTREAMS_CODECVT_CV_QUALIFIER state_type& state,
const char* first1, const char* last1,
std::size_t len2 ) const throw()
{ // Implementation should follow that of do_in().
int st = state;
std::size_t result = 0;
const char* next1 = first1;
while (result < len2 && next1 != last1) {
while (next1 != last1) {
if (st == 0) {
if (*next1 < 1 || *next1 > 3)
return static_cast<int>(result); // error.
st = *next1++;
} else if (st == 1) {
++result;
st = 0;
break;
} else {
if (*next1++ != 0)
return static_cast<int>(result); // error.
--st;
}
}
}
return static_cast<int>(result);
}
};
//------------------Definition of stateless_null_padded_codevt----------------//
class stateless_null_padded_codecvt
: public std::codecvt<wchar_t, char, std::mbstate_t>
{
std::codecvt_base::result
do_in( state_type&, const char* first1, const char* last1,
const char*& next1, wchar_t* first2, wchar_t* last2,
wchar_t*& next2 ) const
{
using namespace std;
for ( next1 = first1, next2 = first2;
next1 != last1 && next2 != last2; )
{
int len = (unsigned char) *next1;
if (len < 1 || len > 3)
return codecvt_base::error;
if (last1 - next1 < len + 1)
return codecvt_base::partial;
++next1;
while (len-- > 1)
if (*next1++ != 0)
return codecvt_base::error;
*next2++ = (unsigned char) *next1++;
}
return next1 == last1 && next2 == last2 ?
codecvt_base::ok :
codecvt_base::partial;
}
std::codecvt_base::result
do_out( state_type&, const wchar_t* first1, const wchar_t* last1,
const wchar_t*& next1, char* first2, char* last2,
char*& next2 ) const
{
using namespace std;
for ( next1 = first1, next2 = first2;
next1 != last1 && next2 != last2; )
{
if (*next1 > integer_traits<unsigned char>::const_max)
return codecvt_base::noconv;
int skip = *next1 % 3 + 2;
if (last2 - next2 < skip)
return codecvt_base::partial;
*next2++ = static_cast<char>(--skip);
while (skip-- > 1)
*next2++ = 0;
*next2++ = (unsigned char) *next1++;
}
return codecvt_base::ok;
}
std::codecvt_base::result
do_unshift( state_type&,
char* /* first2 */,
char* /* last2 */,
char*& /* next2 */ ) const
{
return std::codecvt_base::ok;
}
bool do_always_noconv() const throw() { return false; }
int do_max_length() const throw() { return 4; }
int do_encoding() const throw() { return -1; }
int do_length( BOOST_IOSTREAMS_CODECVT_CV_QUALIFIER state_type&,
const char* first1, const char* last1,
std::size_t len2 ) const throw()
{ // Implementation should follow that of do_in().
std::size_t result = 0;
for ( const char* next1 = first1;
next1 != last1 && result < len2; ++result)
{
int len = (unsigned char) *next1;
if (len < 1 || len > 3 || last1 - next1 < len + 1)
return static_cast<int>(result); // error.
++next1;
while (len-- > 1)
if (*next1++ != 0)
return static_cast<int>(result); // error.
++next1;
}
return static_cast<int>(result);
}
};
} } } // End namespaces detail, iostreams, boost.
#endif // #ifndef BOOST_IOSTREAMS_TEST_NULL_PADDED_CODECVT_HPP_INCLUDED
| apache-2.0 |
zhangsu/amphtml | test/unit/test-video-rotate-to-fullscreen.js | 9249 | /**
* Copyright 2018 The AMP HTML 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.
*/
import {AutoFullscreenManager} from '../../src/service/video-manager-impl';
import {PlayingStates} from '../../src/video-interface';
import {Services} from '../../src/services';
describes.fakeWin('Rotate-to-fullscreen', {amp: true}, env => {
let ampdoc;
let autoFullscreenManager;
function createVideo() {
const element = env.win.document.createElement('div');
const noop = () => {};
Object.assign(element, {
getIntersectionChangeEntry: noop,
});
return {
element,
signals: () => ({whenSignal: () => ({then: noop})}),
};
}
function mockCenteredVideo(element) {
autoFullscreenManager.currentlyCentered_ = element;
}
function mockOrientation(orientation) {
env.win.screen = env.win.screen || {orientation: {type: ''}};
env.win.screen.orientation.type = orientation;
}
beforeEach(() => {
ampdoc = env.ampdoc;
autoFullscreenManager = new AutoFullscreenManager(ampdoc);
sandbox.stub(autoFullscreenManager, 'canFullscreen_').returns(true);
});
it('should enter fullscreen if a video is centered in portrait', () => {
const video = createVideo();
const entry = {video};
const enter = sandbox.stub(autoFullscreenManager, 'enter_');
mockCenteredVideo(video.element);
sandbox.stub(autoFullscreenManager, 'selectBestCenteredInPortrait_');
autoFullscreenManager.register(entry);
mockOrientation('landscape');
autoFullscreenManager.onRotation_();
expect(enter).to.have.been.calledOnce;
});
it('should not enter fullscreen if no video is centered in portrait', () => {
const video = createVideo();
const entry = {video};
const enter = sandbox.stub(autoFullscreenManager, 'enter_');
mockCenteredVideo(null);
sandbox.stub(autoFullscreenManager, 'selectBestCenteredInPortrait_');
autoFullscreenManager.register(entry);
mockOrientation('landscape');
autoFullscreenManager.onRotation_();
expect(enter).to.not.have.been.called;
});
it('should exit fullscreen on rotation', () => {
const video = createVideo();
const entry = {video};
const exit = sandbox.stub(autoFullscreenManager, 'exit_');
sandbox.stub(autoFullscreenManager, 'selectBestCenteredInPortrait_');
autoFullscreenManager.register(entry);
autoFullscreenManager.currentlyInFullscreen_ = entry;
mockOrientation('portrait');
autoFullscreenManager.onRotation_();
expect(exit).to.have.been.calledOnce;
});
it('should not exit on rotation if no video was in fullscreen', () => {
const video = createVideo();
const entry = {video};
const exit = sandbox.stub(autoFullscreenManager, 'exit_');
sandbox.stub(autoFullscreenManager, 'selectBestCenteredInPortrait_');
autoFullscreenManager.register(entry);
autoFullscreenManager.currentlyInFullscreen_ = null;
mockOrientation('portrait');
autoFullscreenManager.onRotation_();
expect(exit).to.not.have.been.called;
});
it('selects the only video playing manually amongst visible', () => {
const video1 = createVideo();
const video2 = createVideo();
const video3 = createVideo();
sandbox.stub(Services.viewportForDoc(ampdoc), 'getSize').returns({
width: 1000,
height: 1000,
});
sandbox.stub(video1.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 0,
bottom: 200,
width: 300,
height: 200,
},
});
sandbox.stub(video2.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 200,
bottom: 400,
width: 300,
height: 200,
},
});
sandbox.stub(video3.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 400,
bottom: 600,
width: 300,
height: 200,
},
});
const getPlayingState = sandbox.stub(
autoFullscreenManager,
'getPlayingState_'
);
getPlayingState.withArgs(video1).returns(PlayingStates.PAUSED);
getPlayingState.withArgs(video2).returns(PlayingStates.PLAYING_AUTO);
getPlayingState.withArgs(video3).returns(PlayingStates.PLAYING_MANUAL);
autoFullscreenManager.register({video: video1});
autoFullscreenManager.register({video: video2});
autoFullscreenManager.register({video: video3});
expect(autoFullscreenManager.selectBestCenteredInPortrait_()).to.equal(
video3
);
});
it('selects center-most video among those visible and playing', () => {
const video1 = createVideo();
const video2 = createVideo();
const video3 = createVideo();
sandbox.stub(Services.viewportForDoc(ampdoc), 'getSize').returns({
width: 1000,
height: 600,
});
sandbox.stub(video1.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 0,
bottom: 200,
width: 300,
height: 200,
},
});
sandbox.stub(video2.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 200,
bottom: 400,
width: 300,
height: 200,
},
});
sandbox.stub(video3.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 400,
bottom: 600,
width: 300,
height: 200,
},
});
const getPlayingState = sandbox.stub(
autoFullscreenManager,
'getPlayingState_'
);
getPlayingState.withArgs(video1).returns(PlayingStates.PLAYING_MANUAL);
getPlayingState.withArgs(video2).returns(PlayingStates.PLAYING_MANUAL);
getPlayingState.withArgs(video3).returns(PlayingStates.PLAYING_MANUAL);
autoFullscreenManager.register({video: video1});
autoFullscreenManager.register({video: video2});
autoFullscreenManager.register({video: video3});
expect(autoFullscreenManager.selectBestCenteredInPortrait_()).to.equal(
video2
);
});
it('selects top-most video if two videos are equally centered', () => {
const video1 = createVideo();
const video2 = createVideo();
sandbox.stub(Services.viewportForDoc(ampdoc), 'getSize').returns({
width: 1000,
height: 400,
});
sandbox.stub(video1.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 0,
bottom: 200,
width: 300,
height: 200,
},
});
sandbox.stub(video2.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 200,
bottom: 400,
width: 300,
height: 200,
},
});
const getPlayingState = sandbox.stub(
autoFullscreenManager,
'getPlayingState_'
);
getPlayingState.withArgs(video1).returns(PlayingStates.PLAYING_MANUAL);
getPlayingState.withArgs(video2).returns(PlayingStates.PLAYING_MANUAL);
autoFullscreenManager.register({video: video1});
autoFullscreenManager.register({video: video2});
expect(autoFullscreenManager.selectBestCenteredInPortrait_()).to.equal(
video1
);
});
it('selects the highest intersection ratio if two videos are visible', () => {
const video1 = createVideo();
const video2 = createVideo();
sandbox.stub(Services.viewportForDoc(ampdoc), 'getSize').returns({
width: 1000,
height: 400,
});
sandbox.stub(video1.element, 'getIntersectionChangeEntry').returns({
intersectionRatio: 0.9,
boundingClientRect: {
top: -30,
bottom: 170,
width: 300,
height: 200,
},
});
sandbox.stub(video2.element, 'getIntersectionChangeEntry').returns({
// Visible:
intersectionRatio: 1,
boundingClientRect: {
top: 200,
bottom: 400,
width: 300,
height: 200,
},
});
const getPlayingState = sandbox.stub(
autoFullscreenManager,
'getPlayingState_'
);
getPlayingState.withArgs(video1).returns(PlayingStates.PLAYING_MANUAL);
getPlayingState.withArgs(video2).returns(PlayingStates.PLAYING_MANUAL);
autoFullscreenManager.register({video: video1});
autoFullscreenManager.register({video: video2});
expect(autoFullscreenManager.selectBestCenteredInPortrait_()).to.equal(
video2
);
});
});
| apache-2.0 |
codenpk/yelo-android | app/src/main/java/red/yelo/widgets/FlipImageView.java | 10453 | /*
*
* * Copyright (C) 2015 yelo.red
* *
* * 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 red.yelo.widgets;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.Transformation;
import android.widget.ImageView;
import red.yelo.R;
/**
* Created with IntelliJ IDEA. User: castorflex Date: 30/12/12 Time: 16:25
*/
public class FlipImageView extends ImageView implements View.OnClickListener,
Animation.AnimationListener {
private static final int FLAG_ROTATION_X = 1 << 0;
private static final int FLAG_ROTATION_Y = 1 << 1;
private static final int FLAG_ROTATION_Z = 1 << 2;
private static final Interpolator fDefaultInterpolator = new DecelerateInterpolator();
private static int sDefaultDuration;
private static int sDefaultRotations;
private static boolean sDefaultAnimated;
private static boolean sDefaultFlipped;
private static boolean sDefaultIsRotationReversed;
public interface OnFlipListener {
public void onClick(FlipImageView view);
public void onFlipStart(FlipImageView view);
public void onFlipEnd(FlipImageView view);
}
private OnFlipListener mListener;
private boolean mIsFlipped;
private boolean mIsDefaultAnimated;
private Drawable mDrawable;
private Drawable mFlippedDrawable;
private FlipAnimator mAnimation;
private boolean mIsRotationXEnabled;
private boolean mIsRotationYEnabled;
private boolean mIsRotationZEnabled;
private boolean mIsFlipping;
private boolean mIsRotationReversed;
public FlipImageView(Context context) {
super(context);
init(context, null, 0);
}
public FlipImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public FlipImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
sDefaultDuration = context.getResources().getInteger(R.integer.default_fiv_duration);
sDefaultRotations = context.getResources().getInteger(R.integer.default_fiv_rotations);
sDefaultAnimated = context.getResources().getBoolean(R.bool.default_fiv_isAnimated);
sDefaultFlipped = context.getResources().getBoolean(R.bool.default_fiv_isFlipped);
sDefaultIsRotationReversed = context.getResources().getBoolean(R.bool.default_fiv_isRotationReversed);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FlipImageView, defStyle, 0);
mIsDefaultAnimated = a.getBoolean(R.styleable.FlipImageView_isAnimated, sDefaultAnimated);
mIsFlipped = a.getBoolean(R.styleable.FlipImageView_isFlipped, sDefaultFlipped);
mFlippedDrawable = a.getDrawable(R.styleable.FlipImageView_flipDrawable);
int duration = a.getInt(R.styleable.FlipImageView_flipDuration, sDefaultDuration);
int interpolatorResId = a.getResourceId(R.styleable.FlipImageView_flipInterpolator, 0);
Interpolator interpolator = interpolatorResId > 0 ? AnimationUtils
.loadInterpolator(context, interpolatorResId) : fDefaultInterpolator;
int rotations = a.getInteger(R.styleable.FlipImageView_flipRotations, sDefaultRotations);
mIsRotationXEnabled = (rotations & FLAG_ROTATION_X) != 0;
mIsRotationYEnabled = (rotations & FLAG_ROTATION_Y) != 0;
mIsRotationZEnabled = (rotations & FLAG_ROTATION_Z) != 0;
mDrawable = getDrawable();
mIsRotationReversed = a.getBoolean(R.styleable.FlipImageView_reverseRotation, sDefaultIsRotationReversed);
mAnimation = new FlipAnimator();
mAnimation.setAnimationListener(this);
mAnimation.setInterpolator(interpolator);
mAnimation.setDuration(duration);
setOnClickListener(this);
setImageDrawable(mIsFlipped ? mFlippedDrawable : mDrawable);
mIsFlipping = false;
a.recycle();
}
public void setFlippedDrawable(Drawable flippedDrawable){
mFlippedDrawable = flippedDrawable;
if(mIsFlipped) setImageDrawable(mFlippedDrawable);
}
public void setDrawable(Drawable drawable){
mDrawable = drawable;
if(!mIsFlipped) setImageDrawable(mDrawable);
}
public boolean isRotationXEnabled() {
return mIsRotationXEnabled;
}
public void setRotationXEnabled(boolean enabled) {
mIsRotationXEnabled = enabled;
}
public boolean isRotationYEnabled() {
return mIsRotationYEnabled;
}
public void setRotationYEnabled(boolean enabled) {
mIsRotationYEnabled = enabled;
}
public boolean isRotationZEnabled() {
return mIsRotationZEnabled;
}
public void setRotationZEnabled(boolean enabled) {
mIsRotationZEnabled = enabled;
}
public FlipAnimator getFlipAnimation() {
return mAnimation;
}
public void setInterpolator(Interpolator interpolator) {
mAnimation.setInterpolator(interpolator);
}
public void setDuration(int duration) {
mAnimation.setDuration(duration);
}
public boolean isFlipped() {
return mIsFlipped;
}
public boolean isFlipping() {
return mIsFlipping;
}
public boolean isRotationReversed(){
return mIsRotationReversed;
}
public void setRotationReversed(boolean rotationReversed){
mIsRotationReversed = rotationReversed;
}
public boolean isAnimated() {
return mIsDefaultAnimated;
}
public void setAnimated(boolean animated) {
mIsDefaultAnimated = animated;
}
public void setFlipped(boolean flipped) {
setFlipped(flipped, mIsDefaultAnimated);
}
public void setFlipped(boolean flipped, boolean animated) {
if (flipped != mIsFlipped) {
toggleFlip(animated);
}
}
public void toggleFlip() {
toggleFlip(mIsDefaultAnimated);
}
public void toggleFlip(boolean animated) {
if (animated) {
mAnimation.setToDrawable(mIsFlipped ? mDrawable : mFlippedDrawable);
startAnimation(mAnimation);
} else {
setImageDrawable(mIsFlipped ? mDrawable : mFlippedDrawable);
}
mIsFlipped = !mIsFlipped;
}
public void setOnFlipListener(OnFlipListener listener) {
mListener = listener;
}
@Override
public void onClick(View v) {
toggleFlip();
if (mListener != null) {
mListener.onClick(this);
}
}
@Override
public void onAnimationStart(Animation animation) {
if (mListener != null) {
mListener.onFlipStart(this);
}
mIsFlipping = true;
}
@Override
public void onAnimationEnd(Animation animation) {
if (mListener != null) {
mListener.onFlipEnd(this);
}
mIsFlipping = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
/**
* Animation part All credits goes to coomar
*/
public class FlipAnimator extends Animation {
private Camera camera;
private Drawable toDrawable;
private float centerX;
private float centerY;
private boolean visibilitySwapped;
public void setToDrawable(Drawable to) {
toDrawable = to;
visibilitySwapped = false;
}
public FlipAnimator() {
setFillAfter(true);
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
camera = new Camera();
this.centerX = width / 2;
this.centerY = height / 2;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
// Angle around the y-axis of the rotation at the given time. It is
// calculated both in radians and in the equivalent degrees.
final double radians = Math.PI * interpolatedTime;
float degrees = (float) (180.0 * radians / Math.PI);
if(mIsRotationReversed){
degrees = -degrees;
}
// Once we reach the midpoint in the animation, we need to hide the
// source view and show the destination view. We also need to change
// the angle by 180 degrees so that the destination does not come in
// flipped around. This is the main problem with SDK sample, it does not
// do this.
if (interpolatedTime >= 0.5f) {
if(mIsRotationReversed){ degrees += 180.f; } else{ degrees -= 180.f; }
if (!visibilitySwapped) {
setImageDrawable(toDrawable);
visibilitySwapped = true;
}
}
final Matrix matrix = t.getMatrix();
camera.save();
camera.translate(0.0f, 0.0f, (float) (150.0 * Math.sin(radians)));
camera.rotateX(mIsRotationXEnabled ? degrees : 0);
camera.rotateY(mIsRotationYEnabled ? degrees : 0);
camera.rotateZ(mIsRotationZEnabled ? degrees : 0);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}
}
| apache-2.0 |
Yetangitu/frontend | src/libraries/controllers/GroupController.php | 294 | <?php
/**
* Group controller for HTML endpoints.
*
* @author Jaisen Mathai <jaisen@jmathai.com>
*/
class GroupController extends BaseController
{
/**
* Call the parent constructor
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
}
| apache-2.0 |
smithab/azure-sdk-for-net | src/Batch/Client/Src/BatchRequestTimeout.cs | 2657 | // Copyright (c) Microsoft and contributors. 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.
namespace Microsoft.Azure.Batch
{
using System;
using Microsoft.Azure.Batch.Protocol;
using Protocol.Models;
/// <summary>
/// Class which provides easy access to the <see cref="IBatchRequest.Timeout"/> property and the <see cref="Protocol.Models.ITimeoutOptions.Timeout"/> property.
/// </summary>
public class BatchRequestTimeout : Protocol.RequestInterceptor
{
/// <summary>
/// Gets or sets the server timeout to be applied to each request issued to the Batch service.
/// </summary>
public TimeSpan? ServerTimeout { get; set; }
/// <summary>
/// Gets or sets the client timeout to be applied to each request issued to the Batch service.
/// </summary>
public TimeSpan? ClientTimeout { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BatchRequestTimeout"/> class.
/// </summary>
/// <param name="serverTimeout">The server timeout to be applied to each request.</param>
/// <param name="clientTimeout">The client timeout to be applied to each request.</param>
public BatchRequestTimeout(TimeSpan? serverTimeout = null, TimeSpan? clientTimeout = null)
{
this.ServerTimeout = serverTimeout;
this.ClientTimeout = clientTimeout;
base.ModificationInterceptHandler = this.SetTimeoutInterceptor;
}
private void SetTimeoutInterceptor(Protocol.IBatchRequest request)
{
if (this.ClientTimeout.HasValue)
{
request.Timeout = this.ClientTimeout.Value;
}
ITimeoutOptions timeoutOptions = request.Options as ITimeoutOptions;
if (this.ServerTimeout.HasValue && timeoutOptions != null)
{
//TODO: It would be nice if the Parameters.ServerTimeout property were a TimeSpan not an int
timeoutOptions.Timeout = (int)this.ServerTimeout.Value.TotalSeconds;
}
}
}
}
| apache-2.0 |
superbstreak/drill | exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/auth/FormSecurityHanlder.java | 2195 | /*
* 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.drill.exec.server.rest.auth;
import org.apache.drill.common.exceptions.DrillException;
import org.apache.drill.exec.rpc.security.plain.PlainFactory;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.server.rest.WebServerConstants;
import org.eclipse.jetty.security.authentication.FormAuthenticator;
import org.eclipse.jetty.util.security.Constraint;
public class FormSecurityHanlder extends DrillHttpConstraintSecurityHandler {
//private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FormSecurityHanlder.class);
@Override
public String getImplName() {
return Constraint.__FORM_AUTH;
}
@Override
public void doSetup(DrillbitContext dbContext) throws DrillException {
// Check if PAMAuthenticator is available or not which is required for FORM authentication
if (!dbContext.getAuthProvider().containsFactory(PlainFactory.SIMPLE_NAME)) {
throw new DrillException("FORM mechanism was configured but PLAIN mechanism is not enabled to provide an " +
"authenticator. Please configure user authentication with PLAIN mechanism and authenticator to use " +
"FORM authentication");
}
setup(new FormAuthenticator(WebServerConstants.FORM_LOGIN_RESOURCE_PATH,
WebServerConstants.FORM_LOGIN_RESOURCE_PATH, true), new DrillRestLoginService(dbContext));
}
} | apache-2.0 |
gerashegalov/Impala | fe/src/main/java/com/cloudera/impala/authorization/Privilege.java | 2229 | // Copyright 2013 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.impala.authorization;
import java.util.EnumSet;
import org.apache.sentry.core.model.db.DBModelAction;
/*
* Maps an Impala Privilege to one or more Hive Access "Actions".
*/
public enum Privilege {
ALL(DBModelAction.ALL, false),
ALTER(DBModelAction.ALL, false),
DROP(DBModelAction.ALL, false),
CREATE(DBModelAction.ALL, false),
INSERT(DBModelAction.INSERT, false),
SELECT(DBModelAction.SELECT, false),
// Privileges required to view metadata on a server object.
VIEW_METADATA(EnumSet.of(DBModelAction.INSERT, DBModelAction.SELECT), true),
// Special privilege that is used to determine if the user has any valid privileges
// on a target object.
ANY(EnumSet.allOf(DBModelAction.class), true),
;
private final EnumSet<DBModelAction> actions;
// Determines whether to check if the user has ANY the privileges defined in the
// actions list or whether to check if the user has ALL of the privileges in the
// actions list.
private final boolean anyOf_;
private Privilege(EnumSet<DBModelAction> actions, boolean anyOf) {
this.actions = actions;
this.anyOf_ = anyOf;
}
private Privilege(DBModelAction action, boolean anyOf) {
this(EnumSet.of(action), anyOf);
}
/*
* Returns the set of Hive Access Actions mapping to this Privilege.
*/
public EnumSet<DBModelAction> getHiveActions() {
return actions;
}
/*
* Determines whether to check if the user has ANY the privileges defined in the
* actions list or whether to check if the user has ALL of the privileges in the
* actions list.
*/
public boolean getAnyOf() { return anyOf_; }
} | apache-2.0 |
elkingtonmcb/Glimpse | source/Glimpse.AspNet/Model/ServerModel.cs | 1439 | using System.Collections.Generic;
using System.Web;
using Glimpse.Core.Extensions;
namespace Glimpse.AspNet.Model
{
public class ServerModel
{
public ServerModel(HttpContextBase httpContext)
{
HttpVariables = new Dictionary<string, string>();
GeneralVariables = new Dictionary<string, string>();
SecurityRelatedVariables = new Dictionary<string, string>();
foreach (var serverVariable in httpContext.Request.ServerVariables.ToDictionary())
{
string lowerCasedKey = serverVariable.Key.ToLower();
if (lowerCasedKey.StartsWith("http_"))
{
HttpVariables.Add(serverVariable.Key, serverVariable.Value);
}
else if (lowerCasedKey.StartsWith("cert_") || lowerCasedKey.StartsWith("https_"))
{
SecurityRelatedVariables.Add(serverVariable.Key, serverVariable.Value);
}
else
{
GeneralVariables.Add(serverVariable.Key, serverVariable.Value);
}
}
}
public IDictionary<string, string> HttpVariables { get; private set; }
public IDictionary<string, string> GeneralVariables { get; private set; }
public IDictionary<string, string> SecurityRelatedVariables { get; private set; }
}
}
| apache-2.0 |
baldimir/drools | kie-pmml/src/test/java/org/kie/pmml/pmml_4_2/predictive/models/ClusteringTest.java | 2703 | /*
* Copyright 2011 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.pmml.pmml_4_2.predictive.models;
import java.util.Collection;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import org.kie.api.definition.type.FactType;
import org.kie.api.runtime.ClassObjectFilter;
import org.kie.api.runtime.KieSession;
import org.kie.pmml.pmml_4_2.DroolsAbstractPMMLTest;
import static org.drools.core.command.runtime.pmml.PmmlConstants.DEFAULT_ROOT_PACKAGE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Ignore
public class ClusteringTest extends DroolsAbstractPMMLTest {
private static final boolean VERBOSE = true;
private static final String source1 = "org/kie/pmml/pmml_4_2/test_clustering.xml";
@After
public void tearDown() {
getKSession().dispose();
}
@Test
public void testCenterBasedClustering() throws Exception {
setKSession( getModelSession( source1, VERBOSE ) );
setKbase( getKSession().getKieBase() );
KieSession kSession = getKSession();
kSession.fireAllRules(); //init model
kSession.getEntryPoint( "in_Fld0" ).insert( "y" );
kSession.getEntryPoint( "in_Fld1" ).insert( 2.0 );
kSession.getEntryPoint( "in_Fld2" ).insert( -1.0 );
kSession.fireAllRules();
FactType mu = kSession.getKieBase().getFactType( DEFAULT_ROOT_PACKAGE, "DistanceMembership" );
Collection mus = kSession.getObjects( new ClassObjectFilter( mu.getFactClass()) );
assertTrue( mus.size() > 0 );
for ( Object x : mus ) {
Integer ix = (Integer) mu.get( x, "index" );
String lab = (String) mu.get( x, "label" );
Double m = (Double) mu.get( x, "mu" );
if ( ix == 0 ) {
assertEquals( "Klust1", lab );
assertEquals( 41.1, m, 0.001 );
} else if ( ix == 1 ) {
assertEquals( "Klust2", lab );
assertEquals( 14704.428, m, 0.001 );
}
}
checkGeneratedRules();
}
}
| apache-2.0 |
filius/asterisk-java | src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java | 12321 | /*
* Copyright 2004-2006 Stefan Reuter
*
* 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.asteriskjava.manager.internal;
import org.asteriskjava.manager.event.DisconnectEvent;
import org.asteriskjava.manager.event.ManagerEvent;
import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent;
import org.asteriskjava.manager.response.ManagerResponse;
import org.asteriskjava.util.DateUtil;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;
import org.asteriskjava.util.SocketConnectionFacade;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Default implementation of the ManagerReader interface.
*
* @author srt
* @version $Id$
*/
public class ManagerReaderImpl implements ManagerReader
{
/**
* Instance logger.
*/
private final Log logger = LogFactory.getLog(getClass());
/**
* The event builder utility to convert a map of attributes reveived from asterisk to instances
* of registered event classes.
*/
private final EventBuilder eventBuilder;
/**
* The response builder utility to convert a map of attributes reveived from asterisk to
* instances of well known response classes.
*/
private final ResponseBuilder responseBuilder;
/**
* The dispatcher to use for dispatching events and responses.
*/
private final Dispatcher dispatcher;
private final Map<String, Class<? extends ManagerResponse>> expectedResponseClasses;
/**
* The source to use when creating {@link ManagerEvent}s.
*/
private final Object source;
/**
* The socket to use for reading from the asterisk server.
*/
private SocketConnectionFacade socket;
/**
* If set to <code>true</code>, terminates and closes the reader.
*/
private volatile boolean die = false;
/**
* <code>true</code> if the main loop has finished.
*/
private boolean dead = false;
/**
* Exception that caused this reader to terminate if any.
*/
private IOException terminationException;
/**
* Creates a new ManagerReaderImpl.
*
* @param dispatcher the dispatcher to use for dispatching events and responses.
* @param source the source to use when creating {@link ManagerEvent}s
*/
public ManagerReaderImpl(final Dispatcher dispatcher, Object source)
{
this.dispatcher = dispatcher;
this.source = source;
this.eventBuilder = new EventBuilderImpl();
this.responseBuilder = new ResponseBuilderImpl();
this.expectedResponseClasses = new ConcurrentHashMap<String, Class<? extends ManagerResponse>>();
}
/**
* Sets the socket to use for reading from the asterisk server.
*
* @param socket the socket to use for reading from the asterisk server.
*/
public void setSocket(final SocketConnectionFacade socket)
{
this.socket = socket;
}
public void registerEventClass(Class<? extends ManagerEvent> eventClass)
{
eventBuilder.registerEventClass(eventClass);
}
public void expectResponseClass(String internalActionId, Class<? extends ManagerResponse> responseClass)
{
expectedResponseClasses.put(internalActionId, responseClass);
}
/**
* Reads line by line from the asterisk server, sets the protocol identifier (using a
* generated {@link org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent}) as soon as it is
* received and dispatches the received events and responses via the associated dispatcher.
*
* @see org.asteriskjava.manager.internal.Dispatcher#dispatchEvent(ManagerEvent)
* @see org.asteriskjava.manager.internal.Dispatcher#dispatchResponse(ManagerResponse)
*/
public void run()
{
final Map<String, Object> buffer = new HashMap<String, Object>();
String line;
if (socket == null)
{
throw new IllegalStateException("Unable to run: socket is null.");
}
this.die = false;
this.dead = false;
try
{
// main loop
while (!this.die && (line = socket.readLine()) != null)
{
// maybe we will find a better way to identify the protocol identifier but for now
// this works quite well.
if (line.startsWith("Asterisk Call Manager/") ||
line.startsWith("Asterisk Call Manager Proxy/") ||
line.startsWith("Asterisk Manager Proxy/") ||
line.startsWith("OpenPBX Call Manager/") ||
line.startsWith("CallWeaver Call Manager/"))
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
protocolIdentifierReceivedEvent = new ProtocolIdentifierReceivedEvent(source);
protocolIdentifierReceivedEvent.setProtocolIdentifier(line);
protocolIdentifierReceivedEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(protocolIdentifierReceivedEvent);
continue;
}
/* Special handling for "Response: Follows" (CommandResponse)
* As we are using "\r\n" as the delimiter for line this also handles multiline
* results as long as they only contain "\n".
*/
if ("Follows".equals(buffer.get("response")) && line.endsWith("--END COMMAND--"))
{
buffer.put(COMMAND_RESULT_RESPONSE_KEY, line);
continue;
}
if (line.length() > 0)
{
int delimiterIndex;
int delimiterLength;
// begin of workaround for Astersik bug 13319
// see AJ-77
// Use this workaround only when line starts from "From " and "To "
int isFromAtStart, isToAtStart;
isFromAtStart = line.indexOf("From ");
isToAtStart = line.indexOf("To ");
if (isFromAtStart == 0 || isToAtStart == 0)
{
delimiterIndex = line.indexOf(" ");
delimiterLength = 1;
}
else
{
delimiterIndex = line.indexOf(": ");
delimiterLength = 2;
}
// end of workaround for Astersik bug 13319
if (delimiterIndex > 0 && line.length() > delimiterIndex + delimiterLength)
{
String name;
String value;
name = line.substring(0, delimiterIndex).toLowerCase(Locale.ENGLISH);
value = line.substring(delimiterIndex + delimiterLength);
addToBuffer(buffer, name, value);
// TODO tracing
//logger.debug("Got name [" + name + "], value: [" + value + "]");
}
}
// an empty line indicates a normal response's or event's end so we build
// the corresponding value object and dispatch it through the ManagerConnection.
if (line.length() == 0)
{
if (buffer.containsKey("event"))
{
// TODO tracing
//logger.debug("attempting to build event: " + buffer.get("event"));
ManagerEvent event = buildEvent(source, buffer);
if (event != null)
{
dispatcher.dispatchEvent(event);
}
else
{
logger.debug("buildEvent returned null");
}
}
else if (buffer.containsKey("response"))
{
ManagerResponse response = buildResponse(buffer);
// TODO tracing
//logger.debug("attempting to build response");
if (response != null)
{
dispatcher.dispatchResponse(response);
}
}
else
{
if (buffer.size() > 0)
{
logger.debug("Buffer contains neither response nor event");
}
}
buffer.clear();
}
}
this.dead = true;
logger.debug("Reached end of stream, terminating reader.");
}
catch (IOException e)
{
this.terminationException = e;
this.dead = true;
logger.info("Terminating reader thread: " + e.getMessage());
}
finally
{
this.dead = true;
// cleans resources and reconnects if needed
DisconnectEvent disconnectEvent = new DisconnectEvent(source);
disconnectEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(disconnectEvent);
}
}
@SuppressWarnings("unchecked")
private void addToBuffer(Map<String, Object> buffer, String name, String value)
{
// if we already have a value for that key, convert the value to a list and add
// the new value to that list.
if (buffer.containsKey(name))
{
Object currentValue = buffer.get(name);
if (currentValue instanceof List)
{
((List<String>) currentValue).add(value);
return;
}
List<String> list = new ArrayList<String>();
if (currentValue instanceof String)
{
list.add((String) currentValue);
}
else
{
list.add(currentValue.toString());
}
list.add(value);
buffer.put(name, list);
}
else
{
buffer.put(name, value);
}
}
public void die()
{
this.die = true;
}
public boolean isDead()
{
return dead;
}
public IOException getTerminationException()
{
return terminationException;
}
private ManagerResponse buildResponse(Map<String, Object> buffer)
{
Class<? extends ManagerResponse> responseClass = null;
final String actionId = (String) buffer.get("actionid");
final String internalActionId = ManagerUtil.getInternalActionId(actionId);
if (internalActionId != null)
{
responseClass = expectedResponseClasses.get(internalActionId);
if (responseClass != null)
{
expectedResponseClasses.remove(internalActionId);
}
}
final ManagerResponse response = responseBuilder.buildResponse(responseClass, buffer);
if (response != null)
{
response.setDateReceived(DateUtil.getDate());
}
return response;
}
private ManagerEvent buildEvent(Object source, Map<String, Object> buffer)
{
ManagerEvent event;
event = eventBuilder.buildEvent(source, buffer);
if (event != null)
{
event.setDateReceived(DateUtil.getDate());
}
return event;
}
}
| apache-2.0 |
wildfly-security-incubator/keycloak | adapters/oidc/spring-security/src/main/java/org/keycloak/adapters/springsecurity/filter/KeycloakPreAuthActionsFilter.java | 3742 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.adapters.springsecurity.filter;
import org.keycloak.adapters.AdapterDeploymentContext;
import org.keycloak.adapters.spi.HttpFacade;
import org.keycloak.adapters.NodesRegistrationManagement;
import org.keycloak.adapters.PreAuthActionsHandler;
import org.keycloak.adapters.spi.UserSessionManagement;
import org.keycloak.adapters.springsecurity.facade.SimpleHttpFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Exposes a Keycloak adapter {@link PreAuthActionsHandler} as a Spring Security filter.
*
* @author <a href="mailto:srossillo@smartling.com">Scott Rossillo</a>
* @version $Revision: 1 $
*/
public class KeycloakPreAuthActionsFilter extends GenericFilterBean implements ApplicationContextAware {
private static final Logger log = LoggerFactory.getLogger(KeycloakPreAuthActionsFilter.class);
private final NodesRegistrationManagement management = new NodesRegistrationManagement();
private ApplicationContext applicationContext;
private AdapterDeploymentContext deploymentContext;
private UserSessionManagement userSessionManagement;
public KeycloakPreAuthActionsFilter() {
super();
}
public KeycloakPreAuthActionsFilter(UserSessionManagement userSessionManagement) {
this.userSessionManagement = userSessionManagement;
}
@Override
protected void initFilterBean() throws ServletException {
deploymentContext = applicationContext.getBean(AdapterDeploymentContext.class);
}
@Override
public void destroy() {
log.debug("Unregistering deployment");
management.stop();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpFacade facade = new SimpleHttpFacade((HttpServletRequest)request, (HttpServletResponse)response);
PreAuthActionsHandler handler = new PreAuthActionsHandler(userSessionManagement, deploymentContext, facade);
if (handler.handleRequest()) {
log.debug("Pre-auth filter handled request: {}", ((HttpServletRequest) request).getRequestURI());
} else {
chain.doFilter(request, response);
}
}
public void setUserSessionManagement(UserSessionManagement userSessionManagement) {
this.userSessionManagement = userSessionManagement;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| apache-2.0 |
dushmis/buck | test/com/facebook/buck/cli/TestCommandTest.java | 11331 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.FakeTestRule;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TestRule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.kohsuke.args4j.CmdLineException;
import java.util.List;
public class TestCommandTest {
private TestCommand getCommand(String... args) throws CmdLineException {
TestCommand command = new TestCommand();
new AdditionalOptionsCmdLineParser(command).parseArgument(args);
return command;
}
@Test
public void testFilterBuilds() throws CmdLineException {
SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
TestCommand command = getCommand("--exclude", "linux", "windows");
TestRule rule1 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows"), Label.of("linux")),
BuildTargetFactory.newInstance("//:for"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
TestRule rule2 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("android")),
BuildTargetFactory.newInstance("//:teh"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
TestRule rule3 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows")),
BuildTargetFactory.newInstance("//:lulz"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
List<TestRule> testRules = ImmutableList.of(rule1, rule2, rule3);
Iterable<TestRule> result = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.<BuildTarget>of(),
testRules);
assertThat(result, contains(rule2));
}
@Test
public void testLabelConjunctionsWithInclude() throws CmdLineException {
SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
TestCommand command = getCommand("--include", "windows+linux");
TestRule rule1 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows"), Label.of("linux")),
BuildTargetFactory.newInstance("//:for"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
TestRule rule2 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows")),
BuildTargetFactory.newInstance("//:lulz"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
List<TestRule> testRules = ImmutableList.of(rule1, rule2);
Iterable<TestRule> result = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.<BuildTarget>of(),
testRules);
assertEquals(ImmutableSet.of(rule1), result);
}
@Test
public void testLabelConjunctionsWithExclude() throws CmdLineException {
SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
TestCommand command = getCommand("--exclude", "windows+linux");
TestRule rule1 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows"), Label.of("linux")),
BuildTargetFactory.newInstance("//:for"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
TestRule rule2 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows")),
BuildTargetFactory.newInstance("//:lulz"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
List<TestRule> testRules = ImmutableList.of(rule1, rule2);
Iterable<TestRule> result = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.<BuildTarget>of(),
testRules);
assertEquals(ImmutableSet.of(rule2), result);
}
@Test
public void testLabelPriority() throws CmdLineException {
TestCommand command = getCommand("--exclude", "c", "--include", "a+b");
TestRule rule = new FakeTestRule(
ImmutableSet.<Label>of(
Label.of("a"),
Label.of("b"),
Label.of("c")),
BuildTargetFactory.newInstance("//:for"),
new SourcePathResolver(new BuildRuleResolver()),
ImmutableSortedSet.<BuildRule>of());
List<TestRule> testRules = ImmutableList.of(rule);
Iterable<TestRule> result = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.<BuildTarget>of(),
testRules);
assertEquals(ImmutableSet.of(), result);
}
@Test
public void testLabelPlingSyntax() throws CmdLineException {
TestCommand command = getCommand("--labels", "!c", "a+b");
TestRule rule = new FakeTestRule(
ImmutableSet.<Label>of(
Label.of("a"),
Label.of("b"),
Label.of("c")),
BuildTargetFactory.newInstance("//:for"),
new SourcePathResolver(new BuildRuleResolver()),
ImmutableSortedSet.<BuildRule>of());
List<TestRule> testRules = ImmutableList.of(rule);
Iterable<TestRule> result = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.<BuildTarget>of(),
testRules);
assertEquals(ImmutableSet.of(), result);
}
@Test
public void testNoTransitiveTests() throws CmdLineException {
SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
TestCommand command = getCommand("--exclude-transitive-tests", "//:wow");
FakeTestRule rule1 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows"), Label.of("linux")),
BuildTargetFactory.newInstance("//:for"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
FakeTestRule rule2 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows")),
BuildTargetFactory.newInstance("//:lulz"),
pathResolver,
ImmutableSortedSet.<BuildRule>of(rule1));
FakeTestRule rule3 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("linux")),
BuildTargetFactory.newInstance("//:wow"),
pathResolver,
ImmutableSortedSet.<BuildRule>of(rule2));
List<TestRule> testRules = ImmutableList.<TestRule>of(rule1, rule2, rule3);
Iterable<TestRule> filtered = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.of(BuildTargetFactory.newInstance("//:wow")),
testRules);
assertEquals(rule3, Iterables.getOnlyElement(filtered));
}
@Test
public void testNoTransitiveTestsWhenLabelExcludeWins() throws CmdLineException {
SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
TestCommand command = getCommand(
"--labels", "!linux", "--always-exclude",
"--exclude-transitive-tests", "//:for", "//:lulz");
FakeTestRule rule1 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows"), Label.of("linux")),
BuildTargetFactory.newInstance("//:for"),
pathResolver,
ImmutableSortedSet.<BuildRule>of());
FakeTestRule rule2 = new FakeTestRule(
ImmutableSet.<Label>of(Label.of("windows")),
BuildTargetFactory.newInstance("//:lulz"),
pathResolver,
ImmutableSortedSet.<BuildRule>of(rule1));
List<TestRule> testRules = ImmutableList.<TestRule>of(rule1, rule2);
Iterable<TestRule> filtered = command.filterTestRules(
new FakeBuckConfig(),
ImmutableSet.of(
BuildTargetFactory.newInstance("//:for"),
BuildTargetFactory.newInstance("//:lulz")),
testRules);
assertEquals(rule2, Iterables.getOnlyElement(filtered));
}
@Test
public void testIfAGlobalExcludeExcludesALabel() throws CmdLineException {
BuckConfig config = new FakeBuckConfig(
ImmutableMap.of(
"test",
ImmutableMap.of("excluded_labels", "e2e")));
assertThat(config.getDefaultRawExcludedLabelSelectors(), contains("e2e"));
TestCommand command = new TestCommand();
new AdditionalOptionsCmdLineParser(command).parseArgument();
assertFalse(command.isMatchedByLabelOptions(config, ImmutableSet.<Label>of(Label.of("e2e"))));
}
@Test
public void testIfALabelIsIncludedItShouldNotBeExcludedEvenIfTheExcludeIsGlobal()
throws CmdLineException {
BuckConfig config = new FakeBuckConfig(
ImmutableMap.of(
"test",
ImmutableMap.of("excluded_labels", "e2e")));
assertThat(config.getDefaultRawExcludedLabelSelectors(), contains("e2e"));
TestCommand command = new TestCommand();
new AdditionalOptionsCmdLineParser(command).parseArgument("--include", "e2e");
assertTrue(command.isMatchedByLabelOptions(config, ImmutableSet.<Label>of(Label.of("e2e"))));
}
@Test
public void testIncludingATestOnTheCommandLineMeansYouWouldLikeItRun() throws CmdLineException {
String excludedLabel = "exclude_me";
BuckConfig config = new FakeBuckConfig(
ImmutableMap.of(
"test",
ImmutableMap.of("excluded_labels", excludedLabel)));
assertThat(config.getDefaultRawExcludedLabelSelectors(), contains(excludedLabel));
TestCommand command = new TestCommand();
new AdditionalOptionsCmdLineParser(command).parseArgument("//example:test");
FakeTestRule rule = new FakeTestRule(
/* labels */ ImmutableSet.<Label>of(Label.of(excludedLabel)),
BuildTargetFactory.newInstance("//example:test"),
new SourcePathResolver(new BuildRuleResolver()),
/* deps */ ImmutableSortedSet.<BuildRule>of()
/* visibility */);
Iterable<TestRule> filtered = command.filterTestRules(
config,
ImmutableSet.of(BuildTargetFactory.newInstance("//example:test")),
ImmutableSet.<TestRule>of(rule));
assertEquals(rule, Iterables.getOnlyElement(filtered));
}
@Test
public void shouldAlwaysDefaultToOneThreadWhenRunningTestsWithDebugFlag()
throws CmdLineException {
TestCommand command = getCommand("-j", "15");
assertThat(
command.getNumTestThreads(new FakeBuckConfig(command.getConfigOverrides())),
Matchers.equalTo(15));
command = getCommand("-j", "15", "--debug");
assertThat(
command.getNumTestThreads(new FakeBuckConfig(command.getConfigOverrides())),
Matchers.equalTo(1));
}
}
| apache-2.0 |
TheTypoMaster/SPHERE-Framework | UnitTest/Console/phpMyAdmin-4.3.12/libraries/navigation/Nodes/Node_Database.class.php | 23746 | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Functionality for the navigation tree
*
* @package PhpMyAdmin-Navigation
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Represents a database node in the navigation tree
*
* @package PhpMyAdmin-Navigation
*/
class Node_Database extends Node
{
/**
* The number of hidden items in this database
*
* @var int
*/
private $_hiddenCount = 0;
/**
* Initialises the class
*
* @param string $name An identifier for the new node
* @param int $type Type of node, may be one of CONTAINER or OBJECT
* @param bool $is_group Whether this object has been created
* while grouping nodes
*
* @return Node_Database
*/
public function __construct($name, $type = Node::OBJECT, $is_group = false)
{
parent::__construct($name, $type, $is_group);
$this->icon = PMA_Util::getImage(
's_db.png',
__('Database operations')
);
$this->links = array(
'text' => $GLOBALS['cfg']['DefaultTabDatabase']
. '?server=' . $GLOBALS['server']
. '&db=%1$s&token=' . $_SESSION[' PMA_token '],
'icon' => 'db_operations.php?server=' . $GLOBALS['server']
. '&db=%1$s&token=' . $_SESSION[' PMA_token '],
'title' => __('Structure')
);
$this->classes = 'database';
}
/**
* Returns the number of children of type $type present inside this container
* This method is overridden by the Node_Database and Node_Table classes
*
* @param string $type The type of item we are looking for
* ('tables', 'views', etc)
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
public function getPresence($type = '', $searchClause = '', $singleItem = false)
{
$retval = 0;
switch ($type) {
case 'tables':
$retval = $this->_getTableCount($searchClause, $singleItem);
break;
case 'views':
$retval = $this->_getViewCount($searchClause, $singleItem);
break;
case 'procedures':
$retval = $this->_getProcedureCount($searchClause, $singleItem);
break;
case 'functions':
$retval = $this->_getFunctionCount($searchClause, $singleItem);
break;
case 'events':
$retval = $this->_getEventCount($searchClause, $singleItem);
break;
default:
break;
}
return $retval;
}
/**
* Returns the number of tables or views present inside this database
*
* @param string $which tables|views
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
private function _getTableOrViewCount($which, $searchClause, $singleItem)
{
$retval = 0;
$db = $this->real_name;
if ($which == 'tables') {
$condition = '=';
} else {
$condition = '!=';
}
if (! $GLOBALS['cfg']['Server']['DisableIS'] || PMA_DRIZZLE) {
$db = PMA_Util::sqlAddSlashes($db);
$query = "SELECT COUNT(*) ";
$query .= "FROM `INFORMATION_SCHEMA`.`TABLES` ";
$query .= "WHERE `TABLE_SCHEMA`='$db' ";
if (PMA_DRIZZLE) {
$query .= "AND `TABLE_TYPE`" . $condition . "'BASE' ";
} else {
$query .= "AND `TABLE_TYPE`" . $condition . "'BASE TABLE' ";
}
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'TABLE_NAME'
);
}
$retval = (int)$GLOBALS['dbi']->fetchValue($query);
} else {
$query = "SHOW FULL TABLES FROM ";
$query .= PMA_Util::backquote($db);
$query .= " WHERE `Table_type`" . $condition . "'BASE TABLE' ";
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'Tables_in_' . $db
);
}
$retval = $GLOBALS['dbi']->numRows(
$GLOBALS['dbi']->tryQuery($query)
);
}
return $retval;
}
/**
* Returns the number of tables present inside this database
*
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
private function _getTableCount($searchClause, $singleItem)
{
return $this->_getTableOrViewCount(
'tables', $searchClause, $singleItem
);
}
/**
* Returns the number of views present inside this database
*
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
private function _getViewCount($searchClause, $singleItem)
{
return $this->_getTableOrViewCount(
'views', $searchClause, $singleItem
);
}
/**
* Returns the number of procedures present inside this database
*
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
private function _getProcedureCount($searchClause, $singleItem)
{
$retval = 0;
$db = $this->real_name;
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
$db = PMA_Util::sqlAddSlashes($db);
$query = "SELECT COUNT(*) ";
$query .= "FROM `INFORMATION_SCHEMA`.`ROUTINES` ";
$query .= "WHERE `ROUTINE_SCHEMA` "
. PMA_Util::getCollateForIS() . "='$db'";
$query .= "AND `ROUTINE_TYPE`='PROCEDURE' ";
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'ROUTINE_NAME'
);
}
$retval = (int)$GLOBALS['dbi']->fetchValue($query);
} else {
$db = PMA_Util::sqlAddSlashes($db);
$query = "SHOW PROCEDURE STATUS WHERE `Db`='$db' ";
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'Name'
);
}
$retval = $GLOBALS['dbi']->numRows(
$GLOBALS['dbi']->tryQuery($query)
);
}
return $retval;
}
/**
* Returns the number of functions present inside this database
*
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
private function _getFunctionCount($searchClause, $singleItem)
{
$retval = 0;
$db = $this->real_name;
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
$db = PMA_Util::sqlAddSlashes($db);
$query = "SELECT COUNT(*) ";
$query .= "FROM `INFORMATION_SCHEMA`.`ROUTINES` ";
$query .= "WHERE `ROUTINE_SCHEMA` "
. PMA_Util::getCollateForIS() . "='$db' ";
$query .= "AND `ROUTINE_TYPE`='FUNCTION' ";
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'ROUTINE_NAME'
);
}
$retval = (int)$GLOBALS['dbi']->fetchValue($query);
} else {
$db = PMA_Util::sqlAddSlashes($db);
$query = "SHOW FUNCTION STATUS WHERE `Db`='$db' ";
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'Name'
);
}
$retval = $GLOBALS['dbi']->numRows(
$GLOBALS['dbi']->tryQuery($query)
);
}
return $retval;
}
/**
* Returns the number of events present inside this database
*
* @param string $searchClause A string used to filter the results of
* the query
* @param boolean $singleItem Whether to get presence of a single known
* item or false in none
*
* @return int
*/
private function _getEventCount($searchClause, $singleItem)
{
$retval = 0;
$db = $this->real_name;
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
$db = PMA_Util::sqlAddSlashes($db);
$query = "SELECT COUNT(*) ";
$query .= "FROM `INFORMATION_SCHEMA`.`EVENTS` ";
$query .= "WHERE `EVENT_SCHEMA` "
. PMA_Util::getCollateForIS() . "='$db' ";
if (! empty($searchClause)) {
$query .= "AND " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'EVENT_NAME'
);
}
$retval = (int)$GLOBALS['dbi']->fetchValue($query);
} else {
$db = PMA_Util::backquote($db);
$query = "SHOW EVENTS FROM $db ";
if (! empty($searchClause)) {
$query .= "WHERE " . $this->_getWhereClauseForSearch(
$searchClause, $singleItem, 'Name'
);
}
$retval = $GLOBALS['dbi']->numRows(
$GLOBALS['dbi']->tryQuery($query)
);
}
return $retval;
}
/**
* Returns the WHERE clause for searching inside a database
*
* @param string $searchClause A string used to filter the results of the query
* @param boolean $singleItem Whether to get presence of a single known item
* @param string $columnName Name of the column in the result set to match
*
* @return string WHERE clause for searching
*/
private function _getWhereClauseForSearch(
$searchClause, $singleItem, $columnName
) {
$query = '';
if ($singleItem) {
$query .= PMA_Util::backquote($columnName) . " = ";
$query .= "'" . PMA_Util::sqlAddSlashes($searchClause) . "'";
} else {
$query .= PMA_Util::backquote($columnName) . " LIKE ";
$query .= "'%" . PMA_Util::sqlAddSlashes($searchClause, true) . "%'";
}
return $query;
}
/**
* Returns the names of children of type $type present inside this container
* This method is overridden by the Node_Database and Node_Table classes
*
* @param string $type The type of item we are looking for
* ('tables', 'views', etc)
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
public function getData($type, $pos, $searchClause = '')
{
$retval = array();
$db = $this->real_name;
switch ($type) {
case 'tables':
$retval = $this->_getTables($pos, $searchClause);
break;
case 'views':
$retval = $this->_getViews($pos, $searchClause);
break;
case 'procedures':
$retval = $this->_getProcedures($pos, $searchClause);
break;
case 'functions':
$retval = $this->_getFunctions($pos, $searchClause);
break;
case 'events':
$retval = $this->_getEvents($pos, $searchClause);
break;
default:
break;
}
// Remove hidden items so that they are not displayed in navigation tree
$cfgRelation = PMA_getRelationsParam();
if (isset($cfgRelation['navwork']) && $cfgRelation['navwork']) {
$navTable = PMA_Util::backquote($cfgRelation['db'])
. "." . PMA_Util::backquote($cfgRelation['navigationhiding']);
$sqlQuery = "SELECT `item_name` FROM " . $navTable
. " WHERE `username`='" . $cfgRelation['user'] . "'"
. " AND `item_type`='" . substr($type, 0, -1)
. "'" . " AND `db_name`='" . PMA_Util::sqlAddSlashes($db) . "'";
$result = PMA_queryAsControlUser($sqlQuery, false);
if ($result) {
$hiddenItems = array();
while ($row = $GLOBALS['dbi']->fetchArray($result)) {
$hiddenItems[] = $row[0];
}
foreach ($retval as $key => $item) {
if (in_array($item, $hiddenItems)) {
unset($retval[$key]);
}
}
}
$GLOBALS['dbi']->freeResult($result);
}
return $retval;
}
/**
* Returns the list of tables or views inside this database
*
* @param string $which tables|views
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getTablesOrViews($which, $pos, $searchClause)
{
if ($which == 'tables') {
$condition = '=';
} else {
$condition = '!=';
}
$maxItems = $GLOBALS['cfg']['MaxNavigationItems'];
$retval = array();
$db = $this->real_name;
if (! $GLOBALS['cfg']['Server']['DisableIS'] || PMA_DRIZZLE) {
$escdDb = PMA_Util::sqlAddSlashes($db);
$query = "SELECT `TABLE_NAME` AS `name` ";
$query .= "FROM `INFORMATION_SCHEMA`.`TABLES` ";
$query .= "WHERE `TABLE_SCHEMA`='$escdDb' ";
if (PMA_DRIZZLE) {
$query .= "AND `TABLE_TYPE`" . $condition . "'BASE' ";
} else {
$query .= "AND `TABLE_TYPE`" . $condition . "'BASE TABLE' ";
}
if (! empty($searchClause)) {
$query .= "AND `TABLE_NAME` LIKE '%";
$query .= PMA_Util::sqlAddSlashes(
$searchClause, true
);
$query .= "%'";
}
$query .= "ORDER BY `TABLE_NAME` ASC ";
$query .= "LIMIT " . intval($pos) . ", $maxItems";
$retval = $GLOBALS['dbi']->fetchResult($query);
} else {
$query = " SHOW FULL TABLES FROM ";
$query .= PMA_Util::backquote($db);
$query .= " WHERE `Table_type`" . $condition . "'BASE TABLE' ";
if (! empty($searchClause)) {
$query .= "AND " . PMA_Util::backquote(
"Tables_in_" . $db
);
$query .= " LIKE '%" . PMA_Util::sqlAddSlashes(
$searchClause, true
);
$query .= "%'";
}
$handle = $GLOBALS['dbi']->tryQuery($query);
if ($handle !== false) {
$count = 0;
while ($arr = $GLOBALS['dbi']->fetchArray($handle)) {
if ($pos <= 0 && $count < $maxItems) {
$retval[] = $arr[0];
$count++;
}
$pos--;
}
}
}
return $retval;
}
/**
* Returns the list of tables inside this database
*
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getTables($pos, $searchClause)
{
return $this->_getTablesOrViews('tables', $pos, $searchClause);
}
/**
* Returns the list of views inside this database
*
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getViews($pos, $searchClause)
{
return $this->_getTablesOrViews('views', $pos, $searchClause);
}
/**
* Returns the list of procedures or functions inside this database
*
* @param string $routineType PROCEDURE|FUNCTION
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getRoutines($routineType, $pos, $searchClause)
{
$maxItems = $GLOBALS['cfg']['MaxNavigationItems'];
$retval = array();
$db = $this->real_name;
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
$escdDb = PMA_Util::sqlAddSlashes($db);
$query = "SELECT `ROUTINE_NAME` AS `name` ";
$query .= "FROM `INFORMATION_SCHEMA`.`ROUTINES` ";
$query .= "WHERE `ROUTINE_SCHEMA` "
. PMA_Util::getCollateForIS() . "='$escdDb'";
$query .= "AND `ROUTINE_TYPE`='" . $routineType . "' ";
if (! empty($searchClause)) {
$query .= "AND `ROUTINE_NAME` LIKE '%";
$query .= PMA_Util::sqlAddSlashes(
$searchClause, true
);
$query .= "%'";
}
$query .= "ORDER BY `ROUTINE_NAME` ASC ";
$query .= "LIMIT " . intval($pos) . ", $maxItems";
$retval = $GLOBALS['dbi']->fetchResult($query);
} else {
$escdDb = PMA_Util::sqlAddSlashes($db);
$query = "SHOW " . $routineType . " STATUS WHERE `Db`='$escdDb' ";
if (! empty($searchClause)) {
$query .= "AND `Name` LIKE '%";
$query .= PMA_Util::sqlAddSlashes(
$searchClause, true
);
$query .= "%'";
}
$handle = $GLOBALS['dbi']->tryQuery($query);
if ($handle !== false) {
$count = 0;
while ($arr = $GLOBALS['dbi']->fetchArray($handle)) {
if ($pos <= 0 && $count < $maxItems) {
$retval[] = $arr['Name'];
$count++;
}
$pos--;
}
}
}
return $retval;
}
/**
* Returns the list of procedures inside this database
*
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getProcedures($pos, $searchClause)
{
return $this->_getRoutines('PROCEDURE', $pos, $searchClause);
}
/**
* Returns the list of functions inside this database
*
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getFunctions($pos, $searchClause)
{
return $this->_getRoutines('FUNCTION', $pos, $searchClause);
}
/**
* Returns the list of events inside this database
*
* @param int $pos The offset of the list within the results
* @param string $searchClause A string used to filter the results of the query
*
* @return array
*/
private function _getEvents($pos, $searchClause)
{
$maxItems = $GLOBALS['cfg']['MaxNavigationItems'];
$retval = array();
$db = $this->real_name;
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
$escdDb = PMA_Util::sqlAddSlashes($db);
$query = "SELECT `EVENT_NAME` AS `name` ";
$query .= "FROM `INFORMATION_SCHEMA`.`EVENTS` ";
$query .= "WHERE `EVENT_SCHEMA` "
. PMA_Util::getCollateForIS() . "='$escdDb' ";
if (! empty($searchClause)) {
$query .= "AND `EVENT_NAME` LIKE '%";
$query .= PMA_Util::sqlAddSlashes(
$searchClause, true
);
$query .= "%'";
}
$query .= "ORDER BY `EVENT_NAME` ASC ";
$query .= "LIMIT " . intval($pos) . ", $maxItems";
$retval = $GLOBALS['dbi']->fetchResult($query);
} else {
$escdDb = PMA_Util::backquote($db);
$query = "SHOW EVENTS FROM $escdDb ";
if (! empty($searchClause)) {
$query .= "WHERE `Name` LIKE '%";
$query .= PMA_Util::sqlAddSlashes(
$searchClause, true
);
$query .= "%'";
}
$handle = $GLOBALS['dbi']->tryQuery($query);
if ($handle !== false) {
$count = 0;
while ($arr = $GLOBALS['dbi']->fetchArray($handle)) {
if ($pos <= 0 && $count < $maxItems) {
$retval[] = $arr['Name'];
$count++;
}
$pos--;
}
}
}
return $retval;
}
/**
* Returns HTML for show hidden button displayed infront of database node
*
* @return String HTML for show hidden button
*/
public function getHtmlForControlButtons()
{
$ret = '';
$cfgRelation = PMA_getRelationsParam();
if (isset($cfgRelation['navwork']) && $cfgRelation['navwork']) {
if ( $this->_hiddenCount > 0) {
$ret = '<span class="dbItemControls">'
. '<a href="navigation.php'
. PMA_URL_getCommon()
. '&showUnhideDialog=true'
. '&dbName=' . urldecode($this->real_name) . '"'
. ' class="showUnhide ajax">'
. PMA_Util::getImage(
'lightbulb.png', __('Show hidden items')
)
. '</a></span>';
}
}
return $ret;
}
/**
* Sets the number of hidden items in this database
*
* @param int $count hidden item count
*
* @return void
*/
public function setHiddenCount($count)
{
$this->_hiddenCount = $count;
}
}
?>
| bsd-2-clause |
reitermarkus/homebrew-cask | Casks/colorpicker-materialdesign.rb | 547 | cask "colorpicker-materialdesign" do
version "2.0.0"
sha256 "244efc1d45c11dbffc478fc92b25ae777b4cfde463b06663290cc8352d6a2464"
url "https://github.com/CodeCatalyst/MaterialDesignColorPicker/releases/download/v#{version}/MaterialDesignColorPicker.colorPicker.zip"
appcast "https://github.com/CodeCatalyst/MaterialDesignColorPicker/releases.atom"
name "Material Design"
homepage "https://github.com/CodeCatalyst/MaterialDesignColorPicker"
depends_on macos: ">= :el_capitan"
colorpicker "MaterialDesignColorPicker.colorPicker"
end
| bsd-2-clause |
Jonekee/chromium.src | chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_crypto_delegate_chromeos.cc | 4091 | // 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/extensions/api/easy_unlock_private/easy_unlock_private_crypto_delegate.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/easy_unlock_client.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace extensions {
namespace api {
namespace {
// Converts encryption type to a string representation used by EasyUnlock dbus
// client.
std::string EncryptionTypeToString(easy_unlock_private::EncryptionType type) {
switch (type) {
case easy_unlock_private::ENCRYPTION_TYPE_AES_256_CBC:
return easy_unlock::kEncryptionTypeAES256CBC;
default:
return easy_unlock::kEncryptionTypeNone;
}
}
// Converts signature type to a string representation used by EasyUnlock dbus
// client.
std::string SignatureTypeToString(easy_unlock_private::SignatureType type) {
switch (type) {
case easy_unlock_private::SIGNATURE_TYPE_ECDSA_P256_SHA256:
return easy_unlock::kSignatureTypeECDSAP256SHA256;
case easy_unlock_private::SIGNATURE_TYPE_HMAC_SHA256:
// Fall through to default.
default:
return easy_unlock::kSignatureTypeHMACSHA256;
}
}
// ChromeOS specific EasyUnlockPrivateCryptoDelegate implementation.
class EasyUnlockPrivateCryptoDelegateChromeOS
: public extensions::api::EasyUnlockPrivateCryptoDelegate {
public:
EasyUnlockPrivateCryptoDelegateChromeOS()
: dbus_client_(
chromeos::DBusThreadManager::Get()->GetEasyUnlockClient()) {
}
virtual ~EasyUnlockPrivateCryptoDelegateChromeOS() {}
virtual void GenerateEcP256KeyPair(const KeyPairCallback& callback) override {
dbus_client_->GenerateEcP256KeyPair(callback);
}
virtual void PerformECDHKeyAgreement(
const easy_unlock_private::PerformECDHKeyAgreement::Params& params,
const DataCallback& callback) override {
dbus_client_->PerformECDHKeyAgreement(
params.private_key,
params.public_key,
callback);
}
virtual void CreateSecureMessage(
const easy_unlock_private::CreateSecureMessage::Params& params,
const DataCallback& callback) override {
chromeos::EasyUnlockClient::CreateSecureMessageOptions options;
options.key = params.key;
if (params.options.associated_data)
options.associated_data = *params.options.associated_data;
if (params.options.public_metadata)
options.public_metadata = *params.options.public_metadata;
if (params.options.verification_key_id)
options.verification_key_id = *params.options.verification_key_id;
if (params.options.decryption_key_id)
options.decryption_key_id = *params.options.decryption_key_id;
options.encryption_type =
EncryptionTypeToString(params.options.encrypt_type);
options.signature_type =
SignatureTypeToString(params.options.sign_type);
dbus_client_->CreateSecureMessage(params.payload, options, callback);
}
virtual void UnwrapSecureMessage(
const easy_unlock_private::UnwrapSecureMessage::Params& params,
const DataCallback& callback) override {
chromeos::EasyUnlockClient::UnwrapSecureMessageOptions options;
options.key = params.key;
if (params.options.associated_data)
options.associated_data = *params.options.associated_data;
options.encryption_type =
EncryptionTypeToString(params.options.encrypt_type);
options.signature_type =
SignatureTypeToString(params.options.sign_type);
dbus_client_->UnwrapSecureMessage(params.secure_message, options, callback);
}
private:
chromeos::EasyUnlockClient* dbus_client_;
DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateCryptoDelegateChromeOS);
};
} // namespace
// static
scoped_ptr<EasyUnlockPrivateCryptoDelegate>
EasyUnlockPrivateCryptoDelegate::Create() {
return scoped_ptr<EasyUnlockPrivateCryptoDelegate>(
new EasyUnlockPrivateCryptoDelegateChromeOS());
}
} // namespace api
} // namespace extensions
| bsd-3-clause |
chromium/chromium | third_party/crashpad/crashpad/util/linux/ptracer_test.cc | 2342 | // Copyright 2017 The Crashpad 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 "util/linux/ptracer.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/linux/get_tls.h"
#include "test/multiprocess.h"
#include "util/file/file_io.h"
#include "util/linux/scoped_ptrace_attach.h"
namespace crashpad {
namespace test {
namespace {
class SameBitnessTest : public Multiprocess {
public:
SameBitnessTest() : Multiprocess() {}
SameBitnessTest(const SameBitnessTest&) = delete;
SameBitnessTest& operator=(const SameBitnessTest&) = delete;
~SameBitnessTest() {}
private:
void MultiprocessParent() override {
LinuxVMAddress expected_tls;
CheckedReadFileExactly(
ReadPipeHandle(), &expected_tls, sizeof(expected_tls));
#if defined(ARCH_CPU_64_BITS)
constexpr bool am_64_bit = true;
#else
constexpr bool am_64_bit = false;
#endif // ARCH_CPU_64_BITS
ScopedPtraceAttach attach;
ASSERT_TRUE(attach.ResetAttach(ChildPID()));
Ptracer ptracer(am_64_bit, /* can_log= */ true);
EXPECT_EQ(ptracer.Is64Bit(), am_64_bit);
ThreadInfo thread_info;
ASSERT_TRUE(ptracer.GetThreadInfo(ChildPID(), &thread_info));
#if defined(ARCH_CPU_X86_64)
EXPECT_EQ(thread_info.thread_context.t64.fs_base, expected_tls);
#endif // ARCH_CPU_X86_64
EXPECT_EQ(thread_info.thread_specific_data_address, expected_tls);
}
void MultiprocessChild() override {
LinuxVMAddress expected_tls = GetTLS();
CheckedWriteFile(WritePipeHandle(), &expected_tls, sizeof(expected_tls));
CheckedReadFileAtEOF(ReadPipeHandle());
}
};
TEST(Ptracer, SameBitness) {
SameBitnessTest test;
test.Run();
}
// TODO(jperaza): Test against a process with different bitness.
} // namespace
} // namespace test
} // namespace crashpad
| bsd-3-clause |
leighpauls/k2cro4 | content/common/indexed_db/indexed_db_param_traits.cc | 6904 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/indexed_db/indexed_db_param_traits.h"
#include "content/common/indexed_db/indexed_db_key.h"
#include "content/common/indexed_db/indexed_db_key_path.h"
#include "content/common/indexed_db/indexed_db_key_range.h"
#include "content/public/common/serialized_script_value.h"
#include "ipc/ipc_message_utils.h"
using content::IndexedDBKey;
using content::IndexedDBKeyPath;
using content::IndexedDBKeyRange;
using content::SerializedScriptValue;
namespace IPC {
void ParamTraits<SerializedScriptValue>::Write(Message* m,
const param_type& p) {
WriteParam(m, p.is_null());
WriteParam(m, p.is_invalid());
WriteParam(m, p.data());
}
bool ParamTraits<SerializedScriptValue>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
bool is_null;
bool is_invalid;
string16 data;
bool ok =
ReadParam(m, iter, &is_null) &&
ReadParam(m, iter, &is_invalid) &&
ReadParam(m, iter, &data);
if (!ok)
return false;
r->set_is_null(is_null);
r->set_is_invalid(is_invalid);
r->set_data(data);
return true;
}
void ParamTraits<SerializedScriptValue>::Log(const param_type& p,
std::string* l) {
l->append("<SerializedScriptValue>(");
LogParam(p.is_null(), l);
l->append(", ");
LogParam(p.is_invalid(), l);
l->append(", ");
LogParam(p.data(), l);
l->append(")");
}
void ParamTraits<IndexedDBKey>::Write(Message* m,
const param_type& p) {
WriteParam(m, int(p.type()));
switch (p.type()) {
case WebKit::WebIDBKey::ArrayType:
WriteParam(m, p.array());
return;
case WebKit::WebIDBKey::StringType:
WriteParam(m, p.string());
return;
case WebKit::WebIDBKey::DateType:
WriteParam(m, p.date());
return;
case WebKit::WebIDBKey::NumberType:
WriteParam(m, p.number());
return;
case WebKit::WebIDBKey::InvalidType:
case WebKit::WebIDBKey::NullType:
return;
}
NOTREACHED();
}
bool ParamTraits<IndexedDBKey>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
int type;
if (!ReadParam(m, iter, &type))
return false;
switch (type) {
case WebKit::WebIDBKey::ArrayType: {
std::vector<IndexedDBKey> array;
if (!ReadParam(m, iter, &array))
return false;
r->SetArray(array);
return true;
}
case WebKit::WebIDBKey::StringType: {
string16 string;
if (!ReadParam(m, iter, &string))
return false;
r->SetString(string);
return true;
}
case WebKit::WebIDBKey::DateType: {
double date;
if (!ReadParam(m, iter, &date))
return false;
r->SetDate(date);
return true;
}
case WebKit::WebIDBKey::NumberType: {
double number;
if (!ReadParam(m, iter, &number))
return false;
r->SetNumber(number);
return true;
}
case WebKit::WebIDBKey::InvalidType:
r->SetInvalid();
return true;
case WebKit::WebIDBKey::NullType:
r->SetNull();
return true;
}
NOTREACHED();
return false;
}
void ParamTraits<IndexedDBKey>::Log(const param_type& p,
std::string* l) {
l->append("<IndexedDBKey>(");
LogParam(int(p.type()), l);
l->append(", ");
l->append("[");
std::vector<IndexedDBKey>::const_iterator it = p.array().begin();
while (it != p.array().end()) {
Log(*it, l);
++it;
if (it != p.array().end())
l->append(", ");
}
l->append("], ");
LogParam(p.string(), l);
l->append(", ");
LogParam(p.date(), l);
l->append(", ");
LogParam(p.number(), l);
l->append(")");
}
void ParamTraits<IndexedDBKeyPath>::Write(Message* m,
const param_type& p) {
WriteParam(m, int(p.type()));
switch (p.type()) {
case WebKit::WebIDBKeyPath::ArrayType:
WriteParam(m, p.array());
return;
case WebKit::WebIDBKeyPath::StringType:
WriteParam(m, p.string());
return;
case WebKit::WebIDBKeyPath::NullType:
return;
}
NOTREACHED();
}
bool ParamTraits<IndexedDBKeyPath>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
int type;
if (!ReadParam(m, iter, &type))
return false;
switch (type) {
case WebKit::WebIDBKeyPath::ArrayType: {
std::vector<string16> array;
if (!ReadParam(m, iter, &array))
return false;
r->SetArray(array);
return true;
}
case WebKit::WebIDBKeyPath::StringType: {
string16 string;
if (!ReadParam(m, iter, &string))
return false;
r->SetString(string);
return true;
}
case WebKit::WebIDBKeyPath::NullType:
r->SetNull();
return true;
}
NOTREACHED();
return false;
}
void ParamTraits<IndexedDBKeyPath>::Log(const param_type& p,
std::string* l) {
l->append("<IndexedDBKeyPath>(");
LogParam(int(p.type()), l);
l->append(", ");
LogParam(p.string(), l);
l->append(", ");
l->append("[");
std::vector<string16>::const_iterator it = p.array().begin();
while (it != p.array().end()) {
LogParam(*it, l);
++it;
if (it != p.array().end())
l->append(", ");
}
l->append("])");
}
void ParamTraits<IndexedDBKeyRange>::Write(Message* m,
const param_type& p) {
WriteParam(m, p.lower());
WriteParam(m, p.upper());
WriteParam(m, p.lowerOpen());
WriteParam(m, p.upperOpen());
}
bool ParamTraits<IndexedDBKeyRange>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
IndexedDBKey lower;
if (!ReadParam(m, iter, &lower))
return false;
IndexedDBKey upper;
if (!ReadParam(m, iter, &upper))
return false;
bool lower_open;
if (!ReadParam(m, iter, &lower_open))
return false;
bool upper_open;
if (!ReadParam(m, iter, &upper_open))
return false;
r->Set(lower, upper, lower_open, upper_open);
return true;
}
void ParamTraits<IndexedDBKeyRange>::Log(const param_type& p,
std::string* l) {
l->append("<IndexedDBKeyRange>(lower=");
LogParam(p.lower(), l);
l->append(", upper=");
LogParam(p.upper(), l);
l->append(", lower_open=");
LogParam(p.lowerOpen(), l);
l->append(", upper_open=");
LogParam(p.upperOpen(), l);
l->append(")");
}
} // namespace IPC
| bsd-3-clause |
beni55/dipy | dipy/reconst/tests/test_interpolate.py | 2163 | from __future__ import division, print_function, absolute_import
from ...utils.six.moves import xrange
from nose.tools import assert_equal, assert_raises, assert_true, assert_false
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_equal)
import numpy as np
from ..interpolate import (NearestNeighborInterpolator, TriLinearInterpolator,
OutsideImage)
def test_NearestNeighborInterpolator():
# Place integers values at the center of every voxel
l, m, n, o = np.ogrid[0:6.01, 0:6.01, 0:6.01, 0:4]
data = l + m + n + o
nni = NearestNeighborInterpolator(data, (1,1,1))
a, b, c = np.mgrid[.5:6.5:1.6, .5:6.5:2.7, .5:6.5:3.8]
for ii in xrange(a.size):
x = a.flat[ii]
y = b.flat[ii]
z = c.flat[ii]
expected_result = int(x) + int(y) + int(z) + o.ravel()
assert_array_equal(nni[x, y, z], expected_result)
ind = np.array([x, y, z])
assert_array_equal(nni[ind], expected_result)
assert_raises(OutsideImage, nni.__getitem__, (-.1, 0, 0))
assert_raises(OutsideImage, nni.__getitem__, (0, 8.2, 0))
def test_TriLinearInterpolator():
# Place (0, 0, 0) at the bottom left of the image
l, m, n, o = np.ogrid[.5:6.51, .5:6.51, .5:6.51, 0:4]
data = l + m + n + o
data = data.astype("float32")
tli = TriLinearInterpolator(data, (1,1,1))
a, b, c = np.mgrid[.5:6.5:1.6, .5:6.5:2.7, .5:6.5:3.8]
for ii in xrange(a.size):
x = a.flat[ii]
y = b.flat[ii]
z = c.flat[ii]
expected_result = x + y + z + o.ravel()
assert_array_almost_equal(tli[x, y, z], expected_result, decimal=5)
ind = np.array([x, y, z])
assert_array_almost_equal(tli[ind], expected_result)
# Index at 0
expected_value = np.arange(4) + 1.5
assert_array_almost_equal(tli[0, 0, 0], expected_value)
# Index at shape
expected_value = np.arange(4) + (6.5 * 3)
assert_array_almost_equal(tli[7, 7, 7], expected_value)
assert_raises(OutsideImage, tli.__getitem__, (-.1, 0, 0))
assert_raises(OutsideImage, tli.__getitem__, (0, 7.01, 0))
| bsd-3-clause |
NifTK/MITK | Plugins/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp | 18927 | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryLayoutTreeNode.h"
#include "berryConstants.h"
#include "berryIPageLayout.h"
#include <sstream>
namespace berry
{
LayoutTreeNode::ChildSizes::ChildSizes (int l, int r, bool resize)
{
left = l;
right = r;
resizable = resize;
}
LayoutTreeNode::LayoutTreeNode(LayoutPartSash::Pointer sash)
: LayoutTree(sash)
{
children[0] = nullptr;
children[1] = nullptr;
}
LayoutTreeNode::~LayoutTreeNode()
{
}
void LayoutTreeNode::FlushChildren()
{
LayoutTree::FlushChildren();
children[0]->FlushChildren();
children[1]->FlushChildren();
}
LayoutPart::Pointer LayoutTreeNode::FindPart(const QPoint& toFind)
{
if (!children[0]->IsVisible())
{
if (!children[1]->IsVisible())
{
return LayoutPart::Pointer(nullptr);
}
return children[1]->FindPart(toFind);
}
else
{
if (!children[1]->IsVisible())
{
return children[0]->FindPart(toFind);
}
}
LayoutPartSash::Pointer sash = this->GetSash();
QRect bounds = sash->GetBounds();
if (sash->IsVertical())
{
if (toFind.x() < bounds.x() + (bounds.width() / 2))
{
return children[0]->FindPart(toFind);
}
return children[1]->FindPart(toFind);
}
else
{
if (toFind.y() < bounds.y() + (bounds.height() / 2))
{
return children[0]->FindPart(toFind);
}
return children[1]->FindPart(toFind);
}
}
LayoutPart::Pointer LayoutTreeNode::ComputeRelation(
QList<PartSashContainer::RelationshipInfo>& relations)
{
PartSashContainer::RelationshipInfo r =
PartSashContainer::RelationshipInfo();
r.relative = children[0]->ComputeRelation(relations);
r.part = children[1]->ComputeRelation(relations);
r.left = this->GetSash()->GetLeft();
r.right = this->GetSash()->GetRight();
r.relationship = this->GetSash()->IsVertical() ? IPageLayout::RIGHT : IPageLayout::BOTTOM;
relations.push_front(r);
return r.relative;
}
void LayoutTreeNode::DisposeSashes()
{
children[0]->DisposeSashes();
children[1]->DisposeSashes();
this->GetSash()->Dispose();
}
LayoutTree::Pointer LayoutTreeNode::Find(LayoutPart::Pointer child)
{
LayoutTree::Pointer node = children[0]->Find(child);
if (node != 0)
{
return node;
}
node = children[1]->Find(child);
return node;
}
LayoutPart::Pointer LayoutTreeNode::FindBottomRight()
{
if (children[1]->IsVisible())
{
return children[1]->FindBottomRight();
}
return children[0]->FindBottomRight();
}
LayoutTreeNode* LayoutTreeNode::FindCommonParent(LayoutPart::Pointer child1,
LayoutPart::Pointer child2, bool foundChild1,
bool foundChild2)
{
if (!foundChild1)
{
foundChild1 = this->Find(child1) != 0;
}
if (!foundChild2)
{
foundChild2 = this->Find(child2) != 0;
}
if (foundChild1 && foundChild2)
{
return this;
}
if (parent == nullptr)
{
return nullptr;
}
return parent
->FindCommonParent(child1, child2, foundChild1, foundChild2);
}
LayoutTreeNode::Pointer LayoutTreeNode::FindSash(LayoutPartSash::Pointer sash)
{
if (this->GetSash() == sash)
{
return LayoutTreeNode::Pointer(this);
}
LayoutTreeNode::Pointer node = children[0]->FindSash(sash);
if (node != 0)
{
return node;
}
node = children[1]->FindSash(sash);
if (node != 0)
{
return node;
}
return LayoutTreeNode::Pointer(nullptr);
}
void LayoutTreeNode::FindSashes(LayoutTree::Pointer child, PartPane::Sashes sashes)
{
QWidget* sash = this->GetSash()->GetControl();
bool leftOrTop = children[0] == child;
if (sash != nullptr)
{
LayoutPartSash::Pointer partSash = this->GetSash();
//If the child is in the left, the sash
//is in the rigth and so on.
if (leftOrTop)
{
if (partSash->IsVertical())
{
if (sashes.right == nullptr)
{
sashes.right = sash;
}
}
else
{
if (sashes.bottom == nullptr)
{
sashes.bottom = sash;
}
}
}
else
{
if (partSash->IsVertical())
{
if (sashes.left == nullptr)
{
sashes.left = sash;
}
}
else
{
if (sashes.top == nullptr)
{
sashes.top = sash;
}
}
}
}
if (this->GetParent() != nullptr)
{
this->GetParent()->FindSashes(LayoutTree::Pointer(this), sashes);
}
}
LayoutPartSash::Pointer LayoutTreeNode::GetSash() const
{
return part.Cast<LayoutPartSash>();
}
int LayoutTreeNode::GetSashSize() const
{
return this->GetSash()->GetSashSize();
}
bool LayoutTreeNode::IsVisible()
{
return children[0]->IsVisible() || children[1]->IsVisible();
}
LayoutTree::Pointer LayoutTreeNode::Remove(LayoutTree::Pointer child)
{
this->GetSash()->Dispose();
if (parent == nullptr)
{
//This is the root. Return the other child to be the new root.
if (children[0] == child)
{
children[1]->SetParent(nullptr);
return children[1];
}
children[0]->SetParent(nullptr);
return children[0];
}
LayoutTreeNode::Pointer oldParent(parent);
if (children[0] == child)
{
oldParent->ReplaceChild(LayoutTree::Pointer(this), children[1]);
}
else
{
oldParent->ReplaceChild(LayoutTree::Pointer(this), children[0]);
}
return oldParent;
}
void LayoutTreeNode::ReplaceChild(LayoutTree::Pointer oldChild, LayoutTree::Pointer newChild)
{
if (children[0] == oldChild)
{
children[0] = newChild;
}
else if (children[1] == oldChild)
{
children[1] = newChild;
}
newChild->SetParent(this);
if (!children[0]->IsVisible() || !children[0]->IsVisible())
{
this->GetSash()->Dispose();
}
this->FlushCache();
}
bool LayoutTreeNode::SameDirection(bool isVertical, LayoutTreeNode::Pointer subTree)
{
bool treeVertical = this->GetSash()->IsVertical();
if (treeVertical != isVertical)
{
return false;
}
while (subTree != 0)
{
if (this == subTree.GetPointer())
{
return true;
}
if (subTree->children[0]->IsVisible() && subTree->children[1]->IsVisible())
{
if (subTree->GetSash()->IsVertical() != isVertical)
{
return false;
}
}
subTree = subTree->GetParent();
}
return true;
}
int LayoutTreeNode::DoComputePreferredSize(bool width, int availableParallel,
int availablePerpendicular, int preferredParallel)
{
this->AssertValidSize(availablePerpendicular);
this->AssertValidSize(availableParallel);
this->AssertValidSize(preferredParallel);
// If one child is invisible, defer to the other child
if (!children[0]->IsVisible())
{
return children[1]->ComputePreferredSize(width, availableParallel,
availablePerpendicular, preferredParallel);
}
if (!children[1]->IsVisible())
{
return children[0]->ComputePreferredSize(width, availableParallel,
availablePerpendicular, preferredParallel);
}
if (availableParallel == 0)
{
return 0;
}
// If computing the dimension perpendicular to our sash
if (width == this->GetSash()->IsVertical())
{
// Compute the child sizes
ChildSizes sizes = this->ComputeChildSizes(availableParallel,
availablePerpendicular,
GetSash()->GetLeft(), GetSash()->GetRight(), preferredParallel);
// Return the sum of the child sizes plus the sash size
return this->Add(sizes.left, this->Add(sizes.right, this->GetSashSize()));
}
else
{
// Computing the dimension parallel to the sash. We will compute and return the preferred size
// of whichever child is closest to the ideal size.
// First compute the dimension of the child sizes perpendicular to the sash
ChildSizes sizes = this->ComputeChildSizes(availablePerpendicular, availableParallel,
GetSash()->GetLeft(), GetSash()->GetRight(), availablePerpendicular);
// Use this information to compute the dimension of the child sizes parallel to the sash.
// Return the preferred size of whichever child is largest
int leftSize = children[0]->ComputePreferredSize(width, availableParallel,
sizes.left, preferredParallel);
// Compute the preferred size of the right child
int rightSize = children[1]->ComputePreferredSize(width, availableParallel,
sizes.right, preferredParallel);
// Return leftSize or rightSize: whichever one is largest
int result = rightSize;
if (leftSize > rightSize)
{
result = leftSize;
}
this->AssertValidSize(result);
return result;
}
}
LayoutTreeNode::ChildSizes LayoutTreeNode::ComputeChildSizes(int width, int height, int left,
int right, int preferredWidth)
{
poco_assert(children[0]->IsVisible());
poco_assert(children[1]->IsVisible());
this->AssertValidSize(width);
this->AssertValidSize(height);
this->AssertValidSize(preferredWidth);
poco_assert(left >= 0);
poco_assert(right >= 0);
poco_assert(preferredWidth >= 0);
poco_assert(preferredWidth <= width);
bool vertical = this->GetSash()->IsVertical();
if (width <= this->GetSashSize())
{
return ChildSizes(0,0, false);
}
if (width == INF)
{
if (preferredWidth == INF)
{
return ChildSizes(children[0]->ComputeMaximumSize(vertical, height),
children[1]->ComputeMaximumSize(vertical, height), false);
}
if (preferredWidth == 0)
{
return ChildSizes(children[0]->ComputeMinimumSize(vertical, height),
children[1]->ComputeMinimumSize(vertical, height), false);
}
}
int total = left + right;
// Use all-or-none weighting
double wLeft = left, wRight = right;
switch (this->GetCompressionBias())
{
case -1:
wLeft = 0.0;
break;
case 1:
wRight = 0.0;
break;
default:
break;
}
double wTotal = wLeft + wRight;
// Subtract the SASH_WIDTH from preferredWidth and width. From here on, we'll deal with the
// width available to the controls and neglect the space used by the sash.
preferredWidth = std::max<int>(0, this->Subtract(preferredWidth, this->GetSashSize()));
width = std::max<int>(0, this->Subtract(width, this->GetSashSize()));
int redistribute = this->Subtract(preferredWidth, total);
// Compute the minimum and maximum sizes for each child
int leftMinimum = children[0]->ComputeMinimumSize(vertical, height);
int rightMinimum = children[1]->ComputeMinimumSize(vertical, height);
int leftMaximum = children[0]->ComputeMaximumSize(vertical, height);
int rightMaximum = children[1]->ComputeMaximumSize(vertical, height);
int idealLeft = 0;
int idealRight = 0;
if (PartSashContainer::leftToRight)
{
// Keep track of the available space for each child, given the minimum size of the other child
int leftAvailable = std::min<int>(leftMaximum, std::max<int>(0, this->Subtract(width,
rightMinimum)));
int rightAvailable = std::min<int>(rightMaximum, std::max<int>(0, this->Subtract(width,
leftMinimum)));
// Figure out the ideal size of the left child
idealLeft = std::max<int>(leftMinimum, std::min<int>(preferredWidth, left
+ (int)(redistribute * wLeft / wTotal)));
// If the right child can't use all its available space, let the left child fill it in
idealLeft = std::max<int>(idealLeft, preferredWidth - rightAvailable);
// Ensure the left child doesn't get larger than its available space
idealLeft = std::min<int>(idealLeft, leftAvailable);
// Check if the left child would prefer to be a different size
idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height,
idealLeft);
// Ensure that the left child is larger than its minimum size
idealLeft = std::max<int>(idealLeft, leftMinimum);
idealLeft = std::min<int>(idealLeft, leftAvailable);
// Compute the right child width
idealRight = std::max<int>(rightMinimum, preferredWidth - idealLeft);
rightAvailable = std::max<int>(0, std::min<int>(rightAvailable, this->Subtract(width,
idealLeft)));
idealRight = std::min<int>(idealRight, rightAvailable);
idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable,
height, idealRight);
idealRight = std::max<int>(idealRight, rightMinimum);
}
else
{
// Keep track of the available space for each child, given the minimum size of the other child
int rightAvailable = std::min<int>(rightMaximum, std::max<int>(0, this->Subtract(width,
leftMinimum)));
int leftAvailable = std::min<int>(leftMaximum, std::max<int>(0, this->Subtract(width,
rightMinimum)));
// Figure out the ideal size of the right child
idealRight = std::max<int>(rightMinimum, std::min<int>(preferredWidth, right
+ (int)(redistribute * wRight / wTotal)));
// If the left child can't use all its available space, let the right child fill it in
idealRight = std::max<int>(idealRight, preferredWidth - leftAvailable);
// Ensure the right child doesn't get larger than its available space
idealRight = std::min<int>(idealRight, rightAvailable);
// Check if the right child would prefer to be a different size
idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height,
idealRight);
// Ensure that the right child is larger than its minimum size
idealRight = std::max<int>(idealRight, rightMinimum);
idealRight = std::min<int>(idealRight, rightAvailable);
// Compute the left child width
idealLeft = std::max<int>(leftMinimum, preferredWidth - idealRight);
leftAvailable = std::max<int>(0, std::min<int>(leftAvailable, this->Subtract(width,
idealRight)));
idealLeft = std::min<int>(idealLeft, leftAvailable);
idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable,
height, idealLeft);
idealLeft = std::max<int>(idealLeft, leftMinimum);
}
return ChildSizes(idealLeft, idealRight, leftMaximum> leftMinimum
&& rightMaximum> rightMinimum
&& leftMinimum + rightMinimum < width);
}
int LayoutTreeNode::DoGetSizeFlags(bool width)
{
if (!children[0]->IsVisible())
{
return children[1]->GetSizeFlags(width);
}
if (!children[1]->IsVisible())
{
return children[0]->GetSizeFlags(width);
}
int leftFlags = children[0]->GetSizeFlags(width);
int rightFlags = children[1]->GetSizeFlags(width);
return ((leftFlags | rightFlags) & ~Constants::MAX) | (leftFlags & rightFlags
& Constants::MAX);
}
void LayoutTreeNode::DoSetBounds(const QRect& b)
{
if (!children[0]->IsVisible())
{
children[1]->SetBounds(b);
this->GetSash()->SetVisible(false);
return;
}
if (!children[1]->IsVisible())
{
children[0]->SetBounds(b);
this->GetSash()->SetVisible(false);
return;
}
QRect bounds = b;
bool vertical = this->GetSash()->IsVertical();
// If this is a horizontal sash, flip coordinate systems so
// that we can eliminate special cases
if (!vertical)
{
bounds = FlipRect(bounds);
}
ChildSizes childSizes = this->ComputeChildSizes(bounds.width(), bounds.height(),
this->GetSash()->GetLeft(), this->GetSash()->GetRight(), bounds.width());
this->GetSash()->SetVisible(true);
this->GetSash()->SetEnabled(childSizes.resizable);
QRect leftBounds = QRect(bounds.x(), bounds.y(), childSizes.left, bounds.height());
QRect sashBounds = QRect(leftBounds.x() + leftBounds.width(), bounds.y(), this->GetSashSize(), bounds.height());
QRect rightBounds = QRect(sashBounds.x() + sashBounds.width(), bounds.y(),
childSizes.right, bounds.height());
if (!vertical)
{
leftBounds = FlipRect(leftBounds);
sashBounds = FlipRect(sashBounds);
rightBounds = FlipRect(rightBounds);
}
this->GetSash()->SetBounds(sashBounds);
children[0]->SetBounds(leftBounds);
children[1]->SetBounds(rightBounds);
}
void LayoutTreeNode::CreateControl(QWidget* parent)
{
children[0]->CreateControl(parent);
children[1]->CreateControl(parent);
this->GetSash()->CreateControl(parent);
LayoutTree::CreateControl(parent);
}
bool LayoutTreeNode::IsCompressible()
{
return children[0]->IsCompressible() || children[1]->IsCompressible();
}
int LayoutTreeNode::GetCompressionBias()
{
bool left = children[0]->IsCompressible();
bool right = children[1]->IsCompressible();
if (left == right)
{
return 0;
}
if (right)
{
return -1;
}
return 1;
}
bool LayoutTreeNode::IsLeftChild(LayoutTree::ConstPointer toTest)
{
return children[0] == toTest;
}
LayoutTree::Pointer LayoutTreeNode::GetChild(bool left)
{
int index = left ? 0 : 1;
return (children[index]);
}
void LayoutTreeNode::SetChild(bool left, LayoutPart::Pointer part)
{
LayoutTree::Pointer child(new LayoutTree(part));
this->SetChild(left, child);
this->FlushCache();
}
void LayoutTreeNode::SetChild(bool left, LayoutTree::Pointer child)
{
int index = left ? 0 : 1;
children[index] = child;
child->SetParent(this);
this->FlushCache();
}
QString LayoutTreeNode::ToString() const
{
QString str;
QTextStream s(&str);
s << "<null>\n";
if (part->GetControl() != nullptr)
{
s << "<@" << part->GetControl() << ">\n";
}
QString str2;
QTextStream result(&str2);
result << "[";
if (children[0]->GetParent() != this)
{
result << str2 << "{" << children[0] << "}" << str;
}
else
{
result << str2 << children[0] << str;
}
if (children[1]->GetParent() != this)
{
result << str2 << "{" << children[1] << "}]";
}
else
{
result << str2 << children[1] << "]";
}
return str2;
}
//void LayoutTreeNode::UpdateSashes(QWidget* parent) {
// if (parent == 0)
// return;
// children[0]->UpdateSashes(parent);
// children[1]->UpdateSashes(parent);
// if (children[0]->IsVisible() && children[1]->IsVisible())
// this->GetSash()->CreateControl(parent);
// else
// this->GetSash()->Dispose();
// }
void LayoutTreeNode::DescribeLayout(QString& buf) const
{
if (!(children[0]->IsVisible()))
{
if (!children[1]->IsVisible())
{
return;
}
children[1]->DescribeLayout(buf);
return;
}
if (!children[1]->IsVisible())
{
children[0]->DescribeLayout(buf);
return;
}
buf.append("("); //$NON-NLS-1$
children[0]->DescribeLayout(buf);
buf.append(this->GetSash()->IsVertical() ? "|" : "-");
children[1]->DescribeLayout(buf);
buf.append(")");
}
QRect LayoutTreeNode::FlipRect(const QRect& rect)
{
return QRect(rect.y(), rect.x(), rect.height(), rect.width());
}
}
| bsd-3-clause |
BrandonHe/sdl_core | src/components/policy/src/policy_helper.cc | 28645 | /*
Copyright (c) 2013, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <sstream>
#include <string.h>
#include "utils/logger.h"
#include "utils/custom_string.h"
#include "policy/policy_helper.h"
#include "policy/policy_manager_impl.h"
namespace policy {
namespace custom_str = utils::custom_string;
namespace {
CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
bool Compare(const StringsValueType& first, const StringsValueType& second) {
const std::string& first_str = first;
const std::string& second_str = second;
return (strcasecmp(first_str.c_str(), second_str.c_str()) < 0);
}
struct CheckGroupName {
CheckGroupName(const policy::StringsValueType& value) : value_(value) {}
bool operator()(const FunctionalGroupNames::value_type& value) {
return value.second.second == std::string(value_);
}
private:
const policy::StringsValueType& value_;
};
struct CopyAttributes {
CopyAttributes(const FunctionalGroupNames& groups_attributes,
std::vector<FunctionalGroupPermission>& groups_permissions)
: groups_attributes_(groups_attributes)
, groups_permissions_(groups_permissions) {}
bool operator()(const policy::StringsValueType& value) {
CheckGroupName checker(value);
FunctionalGroupNames::const_iterator it = std::find_if(
groups_attributes_.begin(), groups_attributes_.end(), checker);
if (groups_attributes_.end() == it) {
return false;
}
FunctionalGroupPermission group;
group.group_name = it->second.second;
group.group_alias = it->second.first;
group.group_id = it->first;
groups_permissions_.push_back(group);
return true;
}
private:
const FunctionalGroupNames& groups_attributes_;
std::vector<FunctionalGroupPermission>& groups_permissions_;
};
} // namespace
CompareGroupName::CompareGroupName(const StringsValueType& group_name)
: group_name_(group_name) {}
bool CompareGroupName::operator()(
const StringsValueType& group_name_to_compare) const {
const std::string gn_ = group_name_;
const std::string gn_compare = group_name_to_compare;
return !(strcasecmp(gn_.c_str(), gn_compare.c_str()));
}
bool operator!=(const policy_table::ApplicationParams& first,
const policy_table::ApplicationParams& second) {
if (first.groups.size() != second.groups.size()) {
return true;
}
StringsConstItr it_first = first.groups.begin();
StringsConstItr it_first_end = first.groups.end();
StringsConstItr it_second = second.groups.begin();
StringsConstItr it_second_end = second.groups.end();
for (; it_first != it_first_end; ++it_first) {
CompareGroupName gp(*it_first);
StringsConstItr it = std::find_if(it_second, it_second_end, gp);
if (it_first_end == it) {
return true;
}
}
return false;
}
CheckAppPolicy::CheckAppPolicy(
PolicyManagerImpl* pm,
const utils::SharedPtr<policy_table::Table> update,
const utils::SharedPtr<policy_table::Table> snapshot)
: pm_(pm), update_(update), snapshot_(snapshot) {}
bool policy::CheckAppPolicy::HasRevokedGroups(
const policy::AppPoliciesValueType& app_policy,
policy_table::Strings* revoked_groups) const {
AppPoliciesConstItr it =
snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
policy_table::Strings groups_new = app_policy.second.groups;
std::sort(groups_new.begin(), groups_new.end(), Compare);
policy_table::Strings groups_curr = (*it).second.groups;
std::sort(groups_curr.begin(), groups_curr.end(), Compare);
StringsConstItr it_groups_new = groups_new.begin();
StringsConstItr it_groups_new_end = groups_new.end();
StringsConstItr it_groups_curr = groups_curr.begin();
StringsConstItr it_groups_curr_end = groups_curr.end();
policy_table::Strings revoked_group_list;
std::set_difference(it_groups_curr,
it_groups_curr_end,
it_groups_new,
it_groups_new_end,
std::back_inserter(revoked_group_list),
Compare);
// Remove groups which are not required user consent
policy_table::Strings::iterator it_revoked = revoked_group_list.begin();
for (; revoked_group_list.end() != it_revoked;) {
if (!IsConsentRequired(app_policy.first, std::string(*it_revoked))) {
revoked_group_list.erase(it_revoked);
it_revoked = revoked_group_list.begin();
} else {
++it_revoked;
}
}
if (revoked_groups) {
*revoked_groups = revoked_group_list;
}
return !revoked_group_list.empty();
}
bool policy::CheckAppPolicy::HasNewGroups(
const policy::AppPoliciesValueType& app_policy,
policy_table::Strings* new_groups) const {
AppPoliciesConstItr it =
snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
policy_table::Strings groups_new = app_policy.second.groups;
std::sort(groups_new.begin(), groups_new.end(), Compare);
policy_table::Strings groups_curr = (*it).second.groups;
std::sort(groups_curr.begin(), groups_curr.end(), Compare);
StringsConstItr it_groups_new = groups_new.begin();
StringsConstItr it_groups_new_end = groups_new.end();
StringsConstItr it_groups_curr = groups_curr.begin();
StringsConstItr it_groups_curr_end = groups_curr.end();
policy_table::Strings new_group_list;
std::set_difference(it_groups_new,
it_groups_new_end,
it_groups_curr,
it_groups_curr_end,
std::back_inserter(new_group_list),
Compare);
if (new_groups) {
*new_groups = new_group_list;
}
return !new_group_list.empty();
}
bool policy::CheckAppPolicy::HasConsentNeededGroups(
const policy::AppPoliciesValueType& app_policy) const {
policy_table::Strings new_groups;
if (!HasNewGroups(app_policy, &new_groups)) {
return false;
}
StringsConstItr it_new = new_groups.begin();
StringsConstItr it_new_end = new_groups.end();
for (; it_new != it_new_end; ++it_new) {
if (IsConsentRequired(app_policy.first, *it_new)) {
return true;
}
}
return false;
}
std::vector<FunctionalGroupPermission> policy::CheckAppPolicy::GetRevokedGroups(
const policy::AppPoliciesValueType& app_policy) const {
policy_table::Strings revoked_groups_names;
if (!HasRevokedGroups(app_policy, &revoked_groups_names)) {
return std::vector<FunctionalGroupPermission>();
}
FunctionalGroupNames groups_attributes;
if (!pm_->cache_->GetFunctionalGroupNames(groups_attributes)) {
LOG4CXX_WARN(logger_, "Can't get functional group names");
return std::vector<FunctionalGroupPermission>();
}
std::vector<FunctionalGroupPermission> revoked_groups_permissions;
CopyAttributes copier(groups_attributes, revoked_groups_permissions);
std::for_each(
revoked_groups_names.begin(), revoked_groups_names.end(), copier);
return revoked_groups_permissions;
}
void policy::CheckAppPolicy::RemoveRevokedConsents(
const AppPoliciesValueType& app_policy,
const std::vector<FunctionalGroupPermission>& revoked_groups) const {
std::vector<policy::FunctionalGroupPermission>::const_iterator it =
revoked_groups.begin();
std::vector<policy::FunctionalGroupPermission>::const_iterator it_end =
revoked_groups.end();
for (; it != it_end; ++it) {
pm_->RemoveAppConsentForGroup(app_policy.first, it->group_name);
}
}
bool CheckAppPolicy::IsKnownAppication(
const std::string& application_id) const {
const policy_table::ApplicationPolicies& current_policies =
snapshot_->policy_table.app_policies_section.apps;
return !(current_policies.end() == current_policies.find(application_id));
}
void policy::CheckAppPolicy::NotifySystem(
const policy::AppPoliciesValueType& app_policy) const {
pm_->listener()->OnPendingPermissionChange(app_policy.first);
}
void CheckAppPolicy::SendPermissionsToApp(
const AppPoliciesValueType& app_policy) const {
const std::string app_id = app_policy.first;
const std::string device_id = pm_->GetCurrentDeviceId(app_id);
if (device_id.empty()) {
LOG4CXX_WARN(logger_,
"Couldn't find device info for application id: " << app_id);
return;
}
std::vector<FunctionalGroupPermission> group_permissons;
pm_->GetPermissionsForApp(device_id, app_id, group_permissons);
Permissions notification_data;
pm_->PrepareNotificationData(update_->policy_table.functional_groupings,
app_policy.second.groups,
group_permissons,
notification_data);
LOG4CXX_INFO(logger_, "Send notification for application_id: " << app_id);
// Default_hmi is Ford-specific and should not be used with basic policy
const std::string default_hmi;
pm_->listener()->OnPermissionsUpdated(app_id, notification_data, default_hmi);
}
bool CheckAppPolicy::IsAppRevoked(
const AppPoliciesValueType& app_policy) const {
LOG4CXX_AUTO_TRACE(logger_);
// Application params are not initialized = application revoked
// i.e. "123":null
return app_policy.second.is_null();
}
bool CheckAppPolicy::NicknamesMatch(
const AppPoliciesValueType& app_policy) const {
const std::string& app_id = app_policy.first;
const custom_str::CustomString app_name = pm_->listener()->GetAppName(app_id);
if (!app_name.empty() && app_policy.second.nicknames &&
!app_policy.second.nicknames->empty()) {
for (policy_table::Strings::const_iterator it =
app_policy.second.nicknames->begin();
app_policy.second.nicknames->end() != it;
++it) {
std::string temp = *it;
if (app_name.CompareIgnoreCase(temp.c_str())) {
return true;
}
}
return false;
}
return true;
}
bool CheckAppPolicy::operator()(const AppPoliciesValueType& app_policy) {
const std::string app_id = app_policy.first;
if (!IsKnownAppication(app_id)) {
LOG4CXX_WARN(logger_,
"Application:" << app_id << " is not present in snapshot.");
return true;
}
if (!IsPredefinedApp(app_policy) && IsAppRevoked(app_policy)) {
SetPendingPermissions(app_policy, RESULT_APP_REVOKED);
NotifySystem(app_policy);
return true;
}
if (!IsPredefinedApp(app_policy) && !NicknamesMatch(app_policy)) {
SetPendingPermissions(app_policy, RESULT_NICKNAME_MISMATCH);
NotifySystem(app_policy);
return true;
}
PermissionsCheckResult result = CheckPermissionsChanges(app_policy);
if (!IsPredefinedApp(app_policy) && IsRequestTypeChanged(app_policy)) {
SetPendingPermissions(app_policy, RESULT_REQUEST_TYPE_CHANGED);
NotifySystem(app_policy);
}
if (RESULT_NO_CHANGES == result) {
LOG4CXX_INFO(logger_,
"Permissions for application:" << app_id
<< " wasn't changed.");
return true;
}
LOG4CXX_INFO(logger_,
"Permissions for application:" << app_id
<< " have been changed.");
if (!IsPredefinedApp(app_policy) && RESULT_CONSENT_NOT_REQIURED != result) {
SetPendingPermissions(app_policy, result);
NotifySystem(app_policy);
}
// Don't sent notification for predefined apps (e.g. default, device etc.)
if (!IsPredefinedApp(app_policy)) {
SendPermissionsToApp(app_policy);
}
return true;
}
void policy::CheckAppPolicy::SetPendingPermissions(
const AppPoliciesValueType& app_policy,
PermissionsCheckResult result) const {
const std::string app_id = app_policy.first;
AppPermissions permissions_diff(app_id);
permissions_diff.priority =
policy_table::EnumToJsonString(app_policy.second.priority);
switch (result) {
case RESULT_APP_REVOKED:
permissions_diff.appRevoked = true;
break;
case RESULT_NICKNAME_MISMATCH:
permissions_diff.appUnauthorized = true;
break;
case RESULT_PERMISSIONS_REVOKED:
permissions_diff.isAppPermissionsRevoked = true;
permissions_diff.appRevokedPermissions = GetRevokedGroups(app_policy);
RemoveRevokedConsents(app_policy, permissions_diff.appRevokedPermissions);
break;
case RESULT_CONSENT_NEEDED:
permissions_diff.appPermissionsConsentNeeded = true;
break;
case RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED:
permissions_diff.isAppPermissionsRevoked = true;
permissions_diff.appPermissionsConsentNeeded = true;
permissions_diff.appRevokedPermissions = GetRevokedGroups(app_policy);
RemoveRevokedConsents(app_policy, permissions_diff.appRevokedPermissions);
break;
case RESULT_REQUEST_TYPE_CHANGED:
permissions_diff.priority.clear();
permissions_diff.requestTypeChanged = true;
{
// Getting RequestTypes from PTU (not from cache)
policy_table::RequestTypes::const_iterator it_request_type =
app_policy.second.RequestType->begin();
for (; app_policy.second.RequestType->end() != it_request_type;
++it_request_type) {
permissions_diff.requestType.push_back(
EnumToJsonString(*it_request_type));
}
}
break;
default:
return;
}
pm_->app_permissions_diff_lock_.Acquire();
pm_->app_permissions_diff_.insert(std::make_pair(app_id, permissions_diff));
pm_->app_permissions_diff_lock_.Release();
}
policy::CheckAppPolicy::PermissionsCheckResult
policy::CheckAppPolicy::CheckPermissionsChanges(
const policy::AppPoliciesValueType& app_policy) const {
bool has_revoked_groups = HasRevokedGroups(app_policy);
bool has_consent_needed_groups = HasConsentNeededGroups(app_policy);
bool has_new_groups = HasNewGroups(app_policy);
if (has_revoked_groups && has_consent_needed_groups) {
return RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED;
} else if (has_revoked_groups) {
return RESULT_PERMISSIONS_REVOKED;
} else if (has_consent_needed_groups) {
return RESULT_CONSENT_NEEDED;
} else if (has_new_groups) {
return RESULT_CONSENT_NOT_REQIURED;
}
return RESULT_NO_CHANGES;
}
bool CheckAppPolicy::IsConsentRequired(const std::string& app_id,
const std::string& group_name) const {
const policy_table::FunctionalGroupings& functional_groupings =
snapshot_->policy_table.functional_groupings;
FuncGroupConstItr it = functional_groupings.find(group_name);
if (functional_groupings.end() == it) {
return false;
}
bool is_preconsented = false;
return it->second.user_consent_prompt.is_initialized() && !is_preconsented;
}
bool CheckAppPolicy::IsRequestTypeChanged(
const AppPoliciesValueType& app_policy) const {
policy::AppPoliciesConstItr it =
snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
if (it == snapshot_->policy_table.app_policies_section.apps.end()) {
if (!app_policy.second.RequestType->empty()) {
return true;
}
return false;
}
if (it->second.RequestType->size() != app_policy.second.RequestType->size()) {
return true;
}
policy_table::RequestTypes diff;
std::set_difference(it->second.RequestType->begin(),
it->second.RequestType->end(),
app_policy.second.RequestType->begin(),
app_policy.second.RequestType->end(),
std::back_inserter(diff));
return diff.size();
}
FillNotificationData::FillNotificationData(Permissions& data,
GroupConsent group_state,
GroupConsent undefined_group_consent)
: data_(data) {
switch (group_state) {
case kGroupAllowed:
current_key_ = kAllowedKey;
break;
case kGroupUndefined:
if (kGroupUndefined == undefined_group_consent) {
current_key_ = kUndefinedKey;
break;
}
current_key_ = kGroupAllowed == undefined_group_consent
? kAllowedKey
: kUserDisallowedKey;
break;
default:
current_key_ = kUserDisallowedKey;
break;
}
}
bool FillNotificationData::operator()(const RpcValueType& rpc) {
Permissions::iterator it = data_.find(rpc.first);
// If rpc is present already - update its permissions
if (data_.end() != it) {
UpdateHMILevels(rpc.second.hmi_levels,
(*it).second.hmi_permissions[current_key_]);
// TODO(IKozyrenko): Check logic if optional container is missing
UpdateParameters(*rpc.second.parameters,
(*it).second.parameter_permissions[current_key_]);
ExcludeSame();
} else {
// Init mandatory keys, since they should be present irrespectively of
// values presence
InitRpcKeys(rpc.first);
// If rpc is not present - add its permissions
UpdateHMILevels(rpc.second.hmi_levels,
data_[rpc.first].hmi_permissions[current_key_]);
// TODO(IKozyrenko): Check logic if optional container is missing
UpdateParameters(*rpc.second.parameters,
data_[rpc.first].parameter_permissions[current_key_]);
ExcludeSame();
}
return true;
}
void FillNotificationData::UpdateHMILevels(
const policy_table::HmiLevels& in_hmi, std::set<HMILevel>& out_hmi) {
HMILevelsConstItr it_hmi_levels = in_hmi.begin();
HMILevelsConstItr it_hmi_levels_end = in_hmi.end();
for (; it_hmi_levels != it_hmi_levels_end; ++it_hmi_levels) {
out_hmi.insert(policy_table::EnumToJsonString(*it_hmi_levels));
}
}
void FillNotificationData::UpdateParameters(
const policy_table::Parameters& in_parameters,
std::set<Parameter>& out_parameter) {
ParametersConstItr it_parameters = in_parameters.begin();
ParametersConstItr it_parameters_end = in_parameters.end();
for (; it_parameters != it_parameters_end; ++it_parameters) {
out_parameter.insert(policy_table::EnumToJsonString(*it_parameters));
}
}
void FillNotificationData::ExcludeSame() {
Permissions::iterator it = data_.begin();
Permissions::const_iterator it_end = data_.end();
// Groups
for (; it != it_end; ++it) {
HMIPermissions& rpc_hmi_permissions = (*it).second.hmi_permissions;
HMIPermissions::const_iterator it_hmi_allowed =
(*it).second.hmi_permissions.find(kAllowedKey);
HMIPermissions::const_iterator it_hmi_undefined =
(*it).second.hmi_permissions.find(kUndefinedKey);
HMIPermissions::const_iterator it_hmi_user_disallowed =
(*it).second.hmi_permissions.find(kUserDisallowedKey);
ParameterPermissions& rpc_parameter_permissions =
(*it).second.parameter_permissions;
ParameterPermissions::const_iterator it_parameter_allowed =
(*it).second.parameter_permissions.find(kAllowedKey);
ParameterPermissions::const_iterator it_parameter_undefined =
(*it).second.parameter_permissions.find(kUndefinedKey);
ParameterPermissions::const_iterator it_parameter_user_disallowed =
(*it).second.parameter_permissions.find(kUserDisallowedKey);
// First, remove disallowed from other types
if (rpc_hmi_permissions.end() != it_hmi_user_disallowed) {
if (rpc_hmi_permissions.end() != it_hmi_allowed) {
ExcludeSameHMILevels(rpc_hmi_permissions[kAllowedKey],
rpc_hmi_permissions[kUserDisallowedKey]);
}
if (rpc_hmi_permissions.end() != it_hmi_undefined) {
ExcludeSameHMILevels(rpc_hmi_permissions[kUndefinedKey],
rpc_hmi_permissions[kUserDisallowedKey]);
}
}
if (rpc_parameter_permissions.end() != it_parameter_user_disallowed) {
if (rpc_parameter_permissions.end() != it_parameter_allowed) {
ExcludeSameParameters(rpc_parameter_permissions[kAllowedKey],
rpc_parameter_permissions[kUserDisallowedKey]);
}
if (rpc_parameter_permissions.end() != it_parameter_undefined) {
ExcludeSameParameters(rpc_parameter_permissions[kUndefinedKey],
rpc_parameter_permissions[kUserDisallowedKey]);
}
}
// Then, remove undefined from allowed
if (rpc_hmi_permissions.end() != it_hmi_undefined) {
if (rpc_hmi_permissions.end() != it_hmi_allowed) {
ExcludeSameHMILevels(rpc_hmi_permissions[kAllowedKey],
rpc_hmi_permissions[kUndefinedKey]);
}
}
if (rpc_parameter_permissions.end() != it_parameter_undefined) {
if (rpc_parameter_permissions.end() != it_parameter_allowed) {
ExcludeSameParameters(rpc_parameter_permissions[kAllowedKey],
rpc_parameter_permissions[kUndefinedKey]);
}
}
}
}
void FillNotificationData::ExcludeSameHMILevels(
std::set<HMILevel>& source, const std::set<HMILevel>& target) {
std::set<HMILevel> diff_hmi;
std::set_difference(source.begin(),
source.end(),
target.begin(),
target.end(),
std::inserter(diff_hmi, diff_hmi.begin()));
source = diff_hmi;
}
void FillNotificationData::ExcludeSameParameters(
std::set<Parameter>& source, const std::set<Parameter>& target) {
std::set<Parameter> diff_parameter;
std::set_difference(source.begin(),
source.end(),
target.begin(),
target.end(),
std::inserter(diff_parameter, diff_parameter.begin()));
source = diff_parameter;
}
void FillNotificationData::InitRpcKeys(const std::string& rpc_name) {
data_[rpc_name].hmi_permissions[kAllowedKey];
data_[rpc_name].hmi_permissions[kUserDisallowedKey];
data_[rpc_name].parameter_permissions[kAllowedKey];
data_[rpc_name].parameter_permissions[kUserDisallowedKey];
}
ProcessFunctionalGroup::ProcessFunctionalGroup(
const policy_table::FunctionalGroupings& fg,
const std::vector<FunctionalGroupPermission>& group_permissions,
Permissions& data,
GroupConsent undefined_group_consent)
: fg_(fg)
, group_permissions_(group_permissions)
, data_(data)
, undefined_group_consent_(undefined_group_consent) {}
bool ProcessFunctionalGroup::operator()(const StringsValueType& group_name) {
const std::string group_name_str = group_name;
FuncGroupConstItr it = fg_.find(group_name_str);
if (fg_.end() != it) {
const policy_table::Rpc& rpcs = (*it).second.rpcs;
FillNotificationData filler(
data_, GetGroupState(group_name_str), undefined_group_consent_);
std::for_each(rpcs.begin(), rpcs.end(), filler);
}
return true;
}
GroupConsent ProcessFunctionalGroup::GetGroupState(
const std::string& group_name) {
std::vector<FunctionalGroupPermission>::const_iterator it =
group_permissions_.begin();
std::vector<FunctionalGroupPermission>::const_iterator it_end =
group_permissions_.end();
for (; it != it_end; ++it) {
if (group_name == (*it).group_name) {
return (*it).state;
}
}
return kGroupUndefined;
}
FunctionalGroupInserter::FunctionalGroupInserter(
const policy_table::Strings& preconsented_groups, PermissionsList& list)
: list_(list), preconsented_(preconsented_groups) {}
void FunctionalGroupInserter::operator()(const StringsValueType& group_name) {
CompareGroupName name(group_name);
if (std::find_if(preconsented_.begin(), preconsented_.end(), name) ==
preconsented_.end()) {
list_.push_back(group_name);
}
}
void FillFunctionalGroupPermissions(
FunctionalGroupIDs& ids,
FunctionalGroupNames& names,
GroupConsent state,
std::vector<FunctionalGroupPermission>& permissions) {
LOG4CXX_INFO(logger_, "FillFunctionalGroupPermissions");
FunctionalGroupIDs::const_iterator it = ids.begin();
FunctionalGroupIDs::const_iterator it_end = ids.end();
for (; it != it_end; ++it) {
FunctionalGroupPermission current_group;
current_group.group_id = *it;
current_group.group_alias = names[*it].first;
current_group.group_name = names[*it].second;
current_group.state = state;
permissions.push_back(current_group);
}
}
bool IsPredefinedApp(const AppPoliciesValueType& app) {
return app.first == kDefaultId || app.first == kPreDataConsentId ||
app.first == kDeviceId;
}
FunctionalGroupIDs ExcludeSame(const FunctionalGroupIDs& from,
const FunctionalGroupIDs& what) {
LOG4CXX_INFO(logger_, "Exclude same groups");
FunctionalGroupIDs from_copy(from);
FunctionalGroupIDs what_copy(what);
std::sort(from_copy.begin(), from_copy.end());
std::sort(what_copy.begin(), what_copy.end());
FunctionalGroupIDs no_same;
std::set_difference(from_copy.begin(),
from_copy.end(),
what_copy.begin(),
what_copy.end(),
std::back_inserter(no_same));
no_same.resize(std::distance(no_same.begin(),
std::unique(no_same.begin(), no_same.end())));
return no_same;
}
FunctionalGroupIDs Merge(const FunctionalGroupIDs& first,
const FunctionalGroupIDs& second) {
LOG4CXX_INFO(logger_, "Merge groups");
FunctionalGroupIDs first_copy(first);
FunctionalGroupIDs second_copy(second);
std::sort(first_copy.begin(), first_copy.end());
std::sort(second_copy.begin(), second_copy.end());
FunctionalGroupIDs merged;
std::set_union(first_copy.begin(),
first_copy.end(),
second_copy.begin(),
second_copy.end(),
std::back_inserter(merged));
merged.resize(
std::distance(merged.begin(), std::unique(merged.begin(), merged.end())));
return merged;
}
FunctionalGroupIDs FindSame(const FunctionalGroupIDs& first,
const FunctionalGroupIDs& second) {
LOG4CXX_INFO(logger_, "Find same groups");
FunctionalGroupIDs first_copy(first);
FunctionalGroupIDs second_copy(second);
std::sort(first_copy.begin(), first_copy.end());
std::sort(second_copy.begin(), second_copy.end());
FunctionalGroupIDs same;
std::set_intersection(first_copy.begin(),
first_copy.end(),
second_copy.begin(),
second_copy.end(),
std::back_inserter(same));
same.resize(
std::distance(same.begin(), std::unique(same.begin(), same.end())));
return same;
}
bool UnwrapAppPolicies(policy_table::ApplicationPolicies& app_policies) {
policy_table::ApplicationPolicies::iterator it = app_policies.begin();
policy_table::ApplicationPolicies::iterator it_default =
app_policies.find(kDefaultId);
for (; app_policies.end() != it; ++it) {
// Set default policies for app, if there is record like "123":"default"
if (kDefaultId.compare((*it).second.get_string()) == 0) {
if (it != app_policies.end()) {
(*it).second = (*it_default).second;
it->second.set_to_string(kDefaultId);
} else {
LOG4CXX_ERROR(logger_,
"There is no default application policy was "
"found in PTU.");
return false;
}
}
}
return true;
}
}
| bsd-3-clause |
jamesblunt/sympy | sympy/benchmarks/bench_symbench.py | 3001 | #!/usr/bin/env python
from __future__ import print_function, division
from sympy.core.compatibility import xrange
from random import random
from sympy import factor, I, Integer, pi, simplify, sin, sqrt, Symbol, sympify
from sympy.abc import x, y, z
from timeit import default_timer as clock
def bench_R1():
"real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))"
def f(z):
return sqrt(Integer(1)/3)*z**2 + I/3
e = f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0]
def bench_R2():
"Hermite polynomial hermite(15, y)"
def hermite(n, y):
if n == 1:
return 2*y
if n == 0:
return 1
return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand()
#def phi(n, y):
# return 1/(sqrt(2**n*factorial(n))*pi**(Integer(1)/4))*exp(-y**2/2)* \
# hermite(n,y)
a = hermite(15, y)
def bench_R3():
"a = [bool(f==f) for _ in range(10)]"
f = x + y + z
a = [bool(f == f) for _ in range(10)]
def bench_R4():
# we don't have Tuples
pass
def bench_R5():
"blowup(L, 8); L=uniq(L)"
def blowup(L, n):
for i in range(n):
L.append( (L[i] + L[i + 1]) * L[i + 2] )
def uniq(x):
v = set(x)
return v
L = [x, y, z]
blowup(L, 8)
L = uniq(L)
def bench_R6():
"sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in xrange(100))"
s = sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in xrange(100))
def bench_R7():
"[f.subs(x, random()) for _ in xrange(10**4)]"
f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21
a = [f.subs(x, random()) for _ in xrange(10**4)]
def bench_R8():
"right(x^2,0,5,10^4)"
def right(f, a, b, n):
a = sympify(a)
b = sympify(b)
n = sympify(n)
x = f.atoms(Symbol).pop()
Deltax = (b - a)/n
c = a
est = 0
for i in range(n):
c += Deltax
est += f.subs(x, c)
return est*Deltax
a = right(x**2, 0, 5, 10**4)
def _bench_R9():
"factor(x^20 - pi^5*y^20)"
factor(x**20 - pi**5*y**20)
def bench_R10():
"v = [-pi,-pi+1/10..,pi]"
def srange(min, max, step):
v = [min]
while (max - v[-1]).evalf() > 0:
v.append(v[-1] + step)
return v[:-1]
v = srange(-pi, pi, sympify(1)/10)
def bench_R11():
"a = [random() + random()*I for w in [0..1000]]"
a = [random() + random()*I for w in range(1000)]
def bench_S1():
"e=(x+y+z+1)**7;f=e*(e+1);f.expand()"
e = (x + y + z + 1)**7
f = e*(e + 1)
f = f.expand()
if __name__ == '__main__':
benchmarks = [
bench_R1,
bench_R2,
bench_R3,
bench_R5,
bench_R6,
bench_R7,
bench_R8,
#_bench_R9,
bench_R10,
bench_R11,
#bench_S1,
]
report = []
for b in benchmarks:
t = clock()
b()
t = clock() - t
print("%s%65s: %f" % (b.__name__, b.__doc__, t))
| bsd-3-clause |
stan-dev/math | lib/boost_1.75.0/boost/math/tools/univariate_statistics.hpp | 12465 | // (C) Copyright Nick Thompson 2018.
// Use, modification and distribution are subject to 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)
#ifndef BOOST_MATH_TOOLS_UNIVARIATE_STATISTICS_HPP
#define BOOST_MATH_TOOLS_UNIVARIATE_STATISTICS_HPP
#include <algorithm>
#include <iterator>
#include <tuple>
#include <boost/assert.hpp>
#include <boost/config/header_deprecated.hpp>
BOOST_HEADER_DEPRECATED("<boost/math/statistics/univariate_statistics.hpp>");
namespace boost::math::tools {
template<class ForwardIterator>
auto mean(ForwardIterator first, ForwardIterator last)
{
using Real = typename std::iterator_traits<ForwardIterator>::value_type;
BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute the mean.");
if constexpr (std::is_integral<Real>::value)
{
double mu = 0;
double i = 1;
for(auto it = first; it != last; ++it) {
mu = mu + (*it - mu)/i;
i += 1;
}
return mu;
}
else if constexpr (std::is_same_v<typename std::iterator_traits<ForwardIterator>::iterator_category, std::random_access_iterator_tag>)
{
size_t elements = std::distance(first, last);
Real mu0 = 0;
Real mu1 = 0;
Real mu2 = 0;
Real mu3 = 0;
Real i = 1;
auto end = last - (elements % 4);
for(auto it = first; it != end; it += 4) {
Real inv = Real(1)/i;
Real tmp0 = (*it - mu0);
Real tmp1 = (*(it+1) - mu1);
Real tmp2 = (*(it+2) - mu2);
Real tmp3 = (*(it+3) - mu3);
// please generate a vectorized fma here
mu0 += tmp0*inv;
mu1 += tmp1*inv;
mu2 += tmp2*inv;
mu3 += tmp3*inv;
i += 1;
}
Real num1 = Real(elements - (elements %4))/Real(4);
Real num2 = num1 + Real(elements % 4);
for (auto it = end; it != last; ++it)
{
mu3 += (*it-mu3)/i;
i += 1;
}
return (num1*(mu0+mu1+mu2) + num2*mu3)/Real(elements);
}
else
{
auto it = first;
Real mu = *it;
Real i = 2;
while(++it != last)
{
mu += (*it - mu)/i;
i += 1;
}
return mu;
}
}
template<class Container>
inline auto mean(Container const & v)
{
return mean(v.cbegin(), v.cend());
}
template<class ForwardIterator>
auto variance(ForwardIterator first, ForwardIterator last)
{
using Real = typename std::iterator_traits<ForwardIterator>::value_type;
BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute mean and variance.");
// Higham, Accuracy and Stability, equation 1.6a and 1.6b:
if constexpr (std::is_integral<Real>::value)
{
double M = *first;
double Q = 0;
double k = 2;
for (auto it = std::next(first); it != last; ++it)
{
double tmp = *it - M;
Q = Q + ((k-1)*tmp*tmp)/k;
M = M + tmp/k;
k += 1;
}
return Q/(k-1);
}
else
{
Real M = *first;
Real Q = 0;
Real k = 2;
for (auto it = std::next(first); it != last; ++it)
{
Real tmp = (*it - M)/k;
Q += k*(k-1)*tmp*tmp;
M += tmp;
k += 1;
}
return Q/(k-1);
}
}
template<class Container>
inline auto variance(Container const & v)
{
return variance(v.cbegin(), v.cend());
}
template<class ForwardIterator>
auto sample_variance(ForwardIterator first, ForwardIterator last)
{
size_t n = std::distance(first, last);
BOOST_ASSERT_MSG(n > 1, "At least two samples are required to compute the sample variance.");
return n*variance(first, last)/(n-1);
}
template<class Container>
inline auto sample_variance(Container const & v)
{
return sample_variance(v.cbegin(), v.cend());
}
// Follows equation 1.5 of:
// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
template<class ForwardIterator>
auto skewness(ForwardIterator first, ForwardIterator last)
{
using Real = typename std::iterator_traits<ForwardIterator>::value_type;
BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute skewness.");
if constexpr (std::is_integral<Real>::value)
{
double M1 = *first;
double M2 = 0;
double M3 = 0;
double n = 2;
for (auto it = std::next(first); it != last; ++it)
{
double delta21 = *it - M1;
double tmp = delta21/n;
M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);
M2 = M2 + tmp*(n-1)*delta21;
M1 = M1 + tmp;
n += 1;
}
double var = M2/(n-1);
if (var == 0)
{
// The limit is technically undefined, but the interpretation here is clear:
// A constant dataset has no skewness.
return double(0);
}
double skew = M3/(M2*sqrt(var));
return skew;
}
else
{
Real M1 = *first;
Real M2 = 0;
Real M3 = 0;
Real n = 2;
for (auto it = std::next(first); it != last; ++it)
{
Real delta21 = *it - M1;
Real tmp = delta21/n;
M3 += tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);
M2 += tmp*(n-1)*delta21;
M1 += tmp;
n += 1;
}
Real var = M2/(n-1);
if (var == 0)
{
// The limit is technically undefined, but the interpretation here is clear:
// A constant dataset has no skewness.
return Real(0);
}
Real skew = M3/(M2*sqrt(var));
return skew;
}
}
template<class Container>
inline auto skewness(Container const & v)
{
return skewness(v.cbegin(), v.cend());
}
// Follows equation 1.5/1.6 of:
// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
template<class ForwardIterator>
auto first_four_moments(ForwardIterator first, ForwardIterator last)
{
using Real = typename std::iterator_traits<ForwardIterator>::value_type;
BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute the first four moments.");
if constexpr (std::is_integral<Real>::value)
{
double M1 = *first;
double M2 = 0;
double M3 = 0;
double M4 = 0;
double n = 2;
for (auto it = std::next(first); it != last; ++it)
{
double delta21 = *it - M1;
double tmp = delta21/n;
M4 = M4 + tmp*(tmp*tmp*delta21*((n-1)*(n*n-3*n+3)) + 6*tmp*M2 - 4*M3);
M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);
M2 = M2 + tmp*(n-1)*delta21;
M1 = M1 + tmp;
n += 1;
}
return std::make_tuple(M1, M2/(n-1), M3/(n-1), M4/(n-1));
}
else
{
Real M1 = *first;
Real M2 = 0;
Real M3 = 0;
Real M4 = 0;
Real n = 2;
for (auto it = std::next(first); it != last; ++it)
{
Real delta21 = *it - M1;
Real tmp = delta21/n;
M4 = M4 + tmp*(tmp*tmp*delta21*((n-1)*(n*n-3*n+3)) + 6*tmp*M2 - 4*M3);
M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);
M2 = M2 + tmp*(n-1)*delta21;
M1 = M1 + tmp;
n += 1;
}
return std::make_tuple(M1, M2/(n-1), M3/(n-1), M4/(n-1));
}
}
template<class Container>
inline auto first_four_moments(Container const & v)
{
return first_four_moments(v.cbegin(), v.cend());
}
// Follows equation 1.6 of:
// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
template<class ForwardIterator>
auto kurtosis(ForwardIterator first, ForwardIterator last)
{
auto [M1, M2, M3, M4] = first_four_moments(first, last);
if (M2 == 0)
{
return M2;
}
return M4/(M2*M2);
}
template<class Container>
inline auto kurtosis(Container const & v)
{
return kurtosis(v.cbegin(), v.cend());
}
template<class ForwardIterator>
auto excess_kurtosis(ForwardIterator first, ForwardIterator last)
{
return kurtosis(first, last) - 3;
}
template<class Container>
inline auto excess_kurtosis(Container const & v)
{
return excess_kurtosis(v.cbegin(), v.cend());
}
template<class RandomAccessIterator>
auto median(RandomAccessIterator first, RandomAccessIterator last)
{
size_t num_elems = std::distance(first, last);
BOOST_ASSERT_MSG(num_elems > 0, "The median of a zero length vector is undefined.");
if (num_elems & 1)
{
auto middle = first + (num_elems - 1)/2;
std::nth_element(first, middle, last);
return *middle;
}
else
{
auto middle = first + num_elems/2 - 1;
std::nth_element(first, middle, last);
std::nth_element(middle, middle+1, last);
return (*middle + *(middle+1))/2;
}
}
template<class RandomAccessContainer>
inline auto median(RandomAccessContainer & v)
{
return median(v.begin(), v.end());
}
template<class RandomAccessIterator>
auto gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)
{
using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;
BOOST_ASSERT_MSG(first != last && std::next(first) != last, "Computation of the Gini coefficient requires at least two samples.");
std::sort(first, last);
if constexpr (std::is_integral<Real>::value)
{
double i = 1;
double num = 0;
double denom = 0;
for (auto it = first; it != last; ++it)
{
num += *it*i;
denom += *it;
++i;
}
// If the l1 norm is zero, all elements are zero, so every element is the same.
if (denom == 0)
{
return double(0);
}
return ((2*num)/denom - i)/(i-1);
}
else
{
Real i = 1;
Real num = 0;
Real denom = 0;
for (auto it = first; it != last; ++it)
{
num += *it*i;
denom += *it;
++i;
}
// If the l1 norm is zero, all elements are zero, so every element is the same.
if (denom == 0)
{
return Real(0);
}
return ((2*num)/denom - i)/(i-1);
}
}
template<class RandomAccessContainer>
inline auto gini_coefficient(RandomAccessContainer & v)
{
return gini_coefficient(v.begin(), v.end());
}
template<class RandomAccessIterator>
inline auto sample_gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)
{
size_t n = std::distance(first, last);
return n*gini_coefficient(first, last)/(n-1);
}
template<class RandomAccessContainer>
inline auto sample_gini_coefficient(RandomAccessContainer & v)
{
return sample_gini_coefficient(v.begin(), v.end());
}
template<class RandomAccessIterator>
auto median_absolute_deviation(RandomAccessIterator first, RandomAccessIterator last, typename std::iterator_traits<RandomAccessIterator>::value_type center=std::numeric_limits<typename std::iterator_traits<RandomAccessIterator>::value_type>::quiet_NaN())
{
using std::abs;
using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;
using std::isnan;
if (isnan(center))
{
center = boost::math::tools::median(first, last);
}
size_t num_elems = std::distance(first, last);
BOOST_ASSERT_MSG(num_elems > 0, "The median of a zero-length vector is undefined.");
auto comparator = [¢er](Real a, Real b) { return abs(a-center) < abs(b-center);};
if (num_elems & 1)
{
auto middle = first + (num_elems - 1)/2;
std::nth_element(first, middle, last, comparator);
return abs(*middle);
}
else
{
auto middle = first + num_elems/2 - 1;
std::nth_element(first, middle, last, comparator);
std::nth_element(middle, middle+1, last, comparator);
return (abs(*middle) + abs(*(middle+1)))/abs(static_cast<Real>(2));
}
}
template<class RandomAccessContainer>
inline auto median_absolute_deviation(RandomAccessContainer & v, typename RandomAccessContainer::value_type center=std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())
{
return median_absolute_deviation(v.begin(), v.end(), center);
}
}
#endif
| bsd-3-clause |
Piicksarn/cdnjs | ajax/libs/smalot-bootstrap-datetimepicker/2.3.11/js/locales/bootstrap-datetimepicker.sk.js | 770 | /**
* Slovak translation for bootstrap-datetimepicker
* Marek Lichtner <marek@licht.sk>
* Fixes by Michal Remiš <michal.remis@gmail.com>
*/
;(function($){
$.fn.datetimepicker.dates["sk"] = {
days: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota", "Nedeľa"],
daysShort: ["Ned", "Pon", "Uto", "Str", "Štv", "Pia", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Ut", "St", "Št", "Pi", "So", "Ne"],
months: ["Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Dnes",
suffix: [],
meridiem: [],
weekStart: 1,
format: "dd.mm.yyyy"
};
}(jQuery));
| mit |
joemoore/LicenseFinder | lib/license_finder/packages/activation.rb | 729 | module LicenseFinder
module Activation
# An Activation reports that a license has been activated for a package, and
# tracks the source of that information
Basic = Struct.new(:package, :license)
class FromDecision < Basic
def sources
["from decision"]
end
end
class FromSpec < Basic
def sources
["from spec"]
end
end
class FromFiles < Basic
def initialize(package, license, files)
super(package, license)
@files = files
end
attr_reader :files
def sources
files.map { |file| "from file '#{file.path}'" }
end
end
class None < Basic
def sources
[]
end
end
end
end
| mit |
HeavenIsLost/tibiaapi | tibiaapi/Addresses/Versions/Version850.cs | 11360 | using Tibia.Addresses;
namespace Tibia
{
public partial class Version
{
public static void SetVersion850()
{
BattleList.Start = 0x632F30;
BattleList.End = 0x632F30 + 0xA0 * 250;
BattleList.StepCreatures = 0xA0;
BattleList.MaxCreatures = 250;
Client.StartTime = 0x7913F8;
Client.XTeaKey = 0x78BF34;
Client.SocketStruct = 0x78BF08;
Client.RecvPointer = 0x5B05DC;
Client.SendPointer = 0x5B0608;
Client.FrameRatePointer = 0x7900DC;
Client.FrameRateCurrentOffset = 0x60;
Client.FrameRateLimitOffset = 0x58;
Client.MultiClient = 0x506794;
Client.Status = 0x78F598;
Client.SafeMode = 0x78C35C;
Client.FollowMode = Client.SafeMode + 4;
Client.AttackMode = Client.FollowMode + 4;
Client.ActionState = 0x78F5F8;
Client.LastMSGText = 0x791668;
Client.LastMSGAuthor = Client.LastMSGText - 0x28;
Client.StatusbarText = 0x791418;
Client.StatusbarTime = Client.StatusbarText - 4;
Client.ClickId = 0x78F634;
Client.ClickCount = Client.ClickId + 4;
Client.ClickZ = Client.ClickId - 0x68;
Client.SeeId = Client.ClickId + 12;
Client.SeeCount = Client.SeeId + 4;
Client.SeeZ = Client.SeeId - 0x68;
Client.ClickContextMenuItemId = 0x78F640;
Client.ClickContextMenuItemGroundId = 0x78F64C;
Client.ClickContextMenuCreatureId = 0x78F59C;
Client.SeeText = 0;
Client.LoginServerStart = 0x786E70;
Client.StepLoginServer = 112;
Client.DistancePort = 100;
Client.MaxLoginServers = 10;
Client.RSA = 0x5B0610;
Client.LoginCharList = 0x78F54C;
Client.LoginCharListLength = Client.LoginCharList + 4;
Client.LoginSelectedChar = 0x78F548;
Client.GameWindowRectPointer = 0x63E8D4;
Client.GameWindowBar = 0x641C40;
Client.DatPointer = 0x78BF54;
Client.EventTriggerPointer = 0x519770;
Client.DialogPointer = 0x641C3C;
Client.DialogLeft = 0x14;
Client.DialogTop = 0x18;
Client.DialogWidth = 0x1C;
Client.DialogHeight = 0x20;
Client.DialogCaption = 0x50;
Client.LastRcvPacket = 0x7876E8;
Client.DecryptCall = 0x45B845;
Client.LoginAccountNum = 0;
Client.LoginPassword = 0x78F554;
Client.LoginAccount = Client.LoginPassword + 32;
Client.LoginPatch = 0;
Client.LoginPatch2 = 0;
Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 };
Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 };
Client.ParserFunc = 0x45B810;
Client.GetNextPacketCall = 0x45B845;
Client.RecvStream = 0x78BF24;
Container.Start = 0x63F388;
Container.StepContainer = 492;
Container.StepSlot = 12;
Container.MaxContainers = 16;
Container.MaxStack = 100;
Container.DistanceIsOpen = 0;
Container.DistanceId = 4;
Container.DistanceName = 16;
Container.DistanceVolume = 48;
Container.DistanceAmount = 56;
Container.DistanceItemId = 60;
Container.DistanceItemCount = 64;
Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer);
ContextMenus.AddContextMenuPtr = 0x451830;
ContextMenus.OnClickContextMenuPtr = 0x44DFD0;
ContextMenus.OnClickContextMenuVf = 0x5B5B98;
ContextMenus.AddSetOutfitContextMenu = 0x452762;
ContextMenus.AddPartyActionContextMenu = 0x4527B3;
ContextMenus.AddCopyNameContextMenu = 0x4527CA;
ContextMenus.AddTradeWithContextMenu = 0x4523D9;
ContextMenus.AddLookContextMenu = 0x45228F;
Creature.DistanceId = 0;
Creature.DistanceType = 3;
Creature.DistanceName = 4;
Creature.DistanceX = 36;
Creature.DistanceY = 40;
Creature.DistanceZ = 44;
Creature.DistanceScreenOffsetHoriz = 48;
Creature.DistanceScreenOffsetVert = 52;
Creature.DistanceIsWalking = 76;
Creature.DistanceWalkSpeed = 140;
Creature.DistanceDirection = 80;
Creature.DistanceIsVisible = 144;
Creature.DistanceBlackSquare = 132;
Creature.DistanceLight = 120;
Creature.DistanceLightColor = 124;
Creature.DistanceHPBar = 136;
Creature.DistanceSkull = 148;
Creature.DistanceParty = 152;
Creature.DistanceOutfit = 96;
Creature.DistanceColorHead = 100;
Creature.DistanceColorBody = 104;
Creature.DistanceColorLegs = 108;
Creature.DistanceColorFeet = 112;
Creature.DistanceAddon = 116;
DatItem.StepItems = 0x50;
DatItem.Width = 0;
DatItem.Height = 4;
DatItem.MaxSizeInPixels = 8;
DatItem.Layers = 12;
DatItem.PatternX = 16;
DatItem.PatternY = 20;
DatItem.PatternDepth = 24;
DatItem.Phase = 28;
DatItem.Sprite = 32;
DatItem.Flags = 36;
DatItem.CanLookAt = 40;
DatItem.WalkSpeed = 44;
DatItem.TextLimit = 48;
DatItem.LightRadius = 52;
DatItem.LightColor = 56;
DatItem.ShiftX = 60;
DatItem.ShiftY = 64;
DatItem.WalkHeight = 68;
DatItem.Automap = 72;
DatItem.LensHelp = 76;
DrawItem.DrawItemFunc = 0x4B0BC0;
DrawSkin.DrawSkinFunc = 0x4B4860;
Hotkey.SendAutomaticallyStart = 0x78C558;
Hotkey.SendAutomaticallyStep = 0x01;
Hotkey.TextStart = 0x78C580;
Hotkey.TextStep = 0x100;
Hotkey.ObjectStart = 0x78C4C8;
Hotkey.ObjectStep = 0x04;
Hotkey.ObjectUseTypeStart = 0x78C3A8;
Hotkey.ObjectUseTypeStep = 0x04;
Hotkey.MaxHotkeys = 36;
Map.MapPointer = 0x646790;
Map.StepTile = 168;
Map.StepTileObject = 12;
Map.DistanceTileObjectCount = 0;
Map.DistanceTileObjects = 4;
Map.DistanceObjectId = 0;
Map.DistanceObjectData = 4;
Map.DistanceObjectDataEx = 8;
Map.MaxTileObjects = 10;
Map.MaxX = 18;
Map.MaxY = 14;
Map.MaxZ = 8;
Map.MaxTiles = 2016;
Map.ZAxisDefault = 7;
Map.NameSpy1 = 0x4ED239;
Map.NameSpy2 = 0x4ED243;
Map.NameSpy1Default = 19061;
Map.NameSpy2Default = 16501;
Map.LevelSpy1 = 0x4EF0EA;
Map.LevelSpy2 = 0x4EF1EF;
Map.LevelSpy3 = 0x4EF270;
Map.LevelSpyPtr = 0x63E8D4;
Map.LevelSpyAdd1 = 28;
Map.LevelSpyAdd2 = 0x2A88;
Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0x88, 0x2A, 0x00, 0x00 };
Map.RevealInvisible1 = 0x45F6F3;
Map.RevealInvisible2 = 0x4EC505;
Map.FullLightNop = 0x4E59C9;
Map.FullLightAdr = 0x4E59CC;
Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 };
Map.FullLightNopEdited = new byte[] { 0x90, 0x90 };
Map.FullLightAdrDefault = 0x80;
Map.FullLightAdrEdited = 0xFF;
Player.Experience = 0x632EC4;
Player.Flags = Player.Experience - 108;
Player.Id = Player.Experience + 12;
Player.Health = Player.Experience + 8;
Player.HealthMax = Player.Experience + 4;
Player.Level = Player.Experience - 4;
Player.MagicLevel = Player.Experience - 8;
Player.LevelPercent = Player.Experience - 12;
Player.MagicLevelPercent = Player.Experience - 16;
Player.Mana = Player.Experience - 20;
Player.ManaMax = Player.Experience - 24;
Player.Soul = Player.Experience - 28;
Player.Stamina = Player.Experience - 32;
Player.Capacity = Player.Experience - 36;
Player.FistPercent = 0x632E5C;
Player.ClubPercent = Player.FistPercent + 4;
Player.SwordPercent = Player.FistPercent + 8;
Player.AxePercent = Player.FistPercent + 12;
Player.DistancePercent = Player.FistPercent + 16;
Player.ShieldingPercent = Player.FistPercent + 20;
Player.FishingPercent = Player.FistPercent + 24;
Player.Fist = Player.FistPercent + 28;
Player.Club = Player.FistPercent + 32;
Player.Sword = Player.FistPercent + 36;
Player.Axe = Player.FistPercent + 40;
Player.Distance = Player.FistPercent + 44;
Player.Shielding = Player.FistPercent + 48;
Player.Fishing = Player.FistPercent + 52;
Player.SlotHead = 0x63F310;
Player.SlotNeck = Player.SlotHead + 12;
Player.SlotBackpack = Player.SlotHead + 24;
Player.SlotArmor = Player.SlotHead + 36;
Player.SlotRight = Player.SlotHead + 48;
Player.SlotLeft = Player.SlotHead + 60;
Player.SlotLegs = Player.SlotHead + 72;
Player.SlotFeet = Player.SlotHead + 84;
Player.SlotRing = Player.SlotHead + 96;
Player.SlotAmmo = Player.SlotHead + 108;
Player.MaxSlots = 10;
Player.DistanceSlotCount = 4;
Player.CurrentTileToGo = 0x632ED8;
Player.TilesToGo = 0x632EDC;
Player.GoToX = Player.Experience + 80;
Player.GoToY = Player.GoToX - 4;
Player.GoToZ = Player.GoToX - 8;
Player.RedSquare = 0x632E9C;
Player.GreenSquare = Player.RedSquare - 4;
Player.WhiteSquare = Player.GreenSquare - 8;
Player.AccessN = 0;
Player.AccessS = 0;
Player.TargetId = Player.RedSquare;
Player.TargetBattlelistId = Player.TargetId - 8;
Player.TargetBattlelistType = Player.TargetId - 5;
Player.TargetType = Player.TargetId + 3;
Player.Z = 0x641C78;
TextDisplay.PrintName = 0x4F0221;
TextDisplay.PrintFPS = 0x459728;
TextDisplay.ShowFPS = 0x630B74;
TextDisplay.PrintTextFunc = 0x4B0000;
TextDisplay.NopFPS = 0x459664;
Vip.Start = 0x630BF0;
Vip.StepPlayers = 0x2C;
Vip.MaxPlayers = 200;
Vip.DistanceId = 0;
Vip.DistanceName = 4;
Vip.DistanceStatus = 34;
Vip.DistanceIcon = 40;
Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers);
}
}
}
| mit |
okazia/XChange | xchange-btce/src/main/java/com/xeiam/xchange/btce/v3/dto/marketdata/BTCEDepthWrapper.java | 858 | package com.xeiam.xchange.btce.v3.dto.marketdata;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* Author: brox Since: 11/12/13 11:00 PM Data object representing multi-currency market data from BTCE API v.3
*/
public class BTCEDepthWrapper {
private final Map<String, BTCEDepth> depthMap;
/**
* Constructor
*
* @param resultV3
*/
@JsonCreator
public BTCEDepthWrapper(Map<String, BTCEDepth> resultV3) {
this.depthMap = resultV3;
}
public Map<String, BTCEDepth> getDepthMap() {
return depthMap;
}
public BTCEDepth getDepth(String pair) {
BTCEDepth result = null;
if (depthMap.containsKey(pair)) {
result = depthMap.get(pair);
}
return result;
}
@Override
public String toString() {
return "BTCEDepthV3 [map=" + depthMap.toString() + "]";
}
}
| mit |
ACOKing/ArcherSys | piwik/libs/PclZip/pclzip.lib.php | 196363 | <?php
// --------------------------------------------------------------------------------
// PhpConcept Library - Zip Module 2.8.2
// --------------------------------------------------------------------------------
// License GNU/LGPL - Vincent Blavet - August 2009
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
// PclZip is a PHP library that manage ZIP archives.
// So far tests show that archives generated by PclZip are readable by
// WinZip application and other tools.
//
// Description :
// See readme.txt and http://www.phpconcept.net
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $
// --------------------------------------------------------------------------------
// ----- Constants
if (!defined('PCLZIP_READ_BLOCK_SIZE')) {
define( 'PCLZIP_READ_BLOCK_SIZE', 2048 );
}
// ----- File list separator
// In version 1.x of PclZip, the separator for file list is a space
// (which is not a very smart choice, specifically for windows paths !).
// A better separator should be a comma (,). This constant gives you the
// abilty to change that.
// However notice that changing this value, may have impact on existing
// scripts, using space separated filenames.
// Recommanded values for compatibility with older versions :
//define( 'PCLZIP_SEPARATOR', ' ' );
// Recommanded values for smart separation of filenames.
if (!defined('PCLZIP_SEPARATOR')) {
define( 'PCLZIP_SEPARATOR', ',' );
}
// ----- Error configuration
// 0 : PclZip Class integrated error handling
// 1 : PclError external library error handling. By enabling this
// you must ensure that you have included PclError library.
// [2,...] : reserved for futur use
if (!defined('PCLZIP_ERROR_EXTERNAL')) {
define( 'PCLZIP_ERROR_EXTERNAL', 0 );
}
// ----- Optional static temporary directory
// By default temporary files are generated in the script current
// path.
// If defined :
// - MUST BE terminated by a '/'.
// - MUST be a valid, already created directory
// Samples :
// define( 'PCLZIP_TEMPORARY_DIR', '/temp/' );
// define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' );
if (!defined('PCLZIP_TEMPORARY_DIR')) {
define( 'PCLZIP_TEMPORARY_DIR', '' );
}
// ----- Optional threshold ratio for use of temporary files
// Pclzip sense the size of the file to add/extract and decide to
// use or not temporary file. The algorythm is looking for
// memory_limit of PHP and apply a ratio.
// threshold = memory_limit * ratio.
// Recommended values are under 0.5. Default 0.47.
// Samples :
// define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 );
if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) {
define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 );
}
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------
// ----- Global variables
$g_pclzip_version = "2.8.2";
// ----- Error codes
// -1 : Unable to open file in binary write mode
// -2 : Unable to open file in binary read mode
// -3 : Invalid parameters
// -4 : File does not exist
// -5 : Filename is too long (max. 255)
// -6 : Not a valid zip file
// -7 : Invalid extracted file size
// -8 : Unable to create directory
// -9 : Invalid archive extension
// -10 : Invalid archive format
// -11 : Unable to delete file (unlink)
// -12 : Unable to rename file (rename)
// -13 : Invalid header checksum
// -14 : Invalid archive size
define( 'PCLZIP_ERR_USER_ABORTED', 2 );
define( 'PCLZIP_ERR_NO_ERROR', 0 );
define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 );
define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 );
define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 );
define( 'PCLZIP_ERR_MISSING_FILE', -4 );
define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 );
define( 'PCLZIP_ERR_INVALID_ZIP', -6 );
define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 );
define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 );
define( 'PCLZIP_ERR_BAD_EXTENSION', -9 );
define( 'PCLZIP_ERR_BAD_FORMAT', -10 );
define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 );
define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 );
define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 );
define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 );
define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 );
define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 );
define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 );
define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 );
define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 );
define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 );
define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 );
// ----- Options values
define( 'PCLZIP_OPT_PATH', 77001 );
define( 'PCLZIP_OPT_ADD_PATH', 77002 );
define( 'PCLZIP_OPT_REMOVE_PATH', 77003 );
define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 );
define( 'PCLZIP_OPT_SET_CHMOD', 77005 );
define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 );
define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 );
define( 'PCLZIP_OPT_BY_NAME', 77008 );
define( 'PCLZIP_OPT_BY_INDEX', 77009 );
define( 'PCLZIP_OPT_BY_EREG', 77010 );
define( 'PCLZIP_OPT_BY_PREG', 77011 );
define( 'PCLZIP_OPT_COMMENT', 77012 );
define( 'PCLZIP_OPT_ADD_COMMENT', 77013 );
define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 );
define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 );
define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 );
define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 );
// Having big trouble with crypt. Need to multiply 2 long int
// which is not correctly supported by PHP ...
//define( 'PCLZIP_OPT_CRYPT', 77018 );
define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 );
define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 );
define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias
define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 );
define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias
define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 );
define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias
// ----- File description attributes
define( 'PCLZIP_ATT_FILE_NAME', 79001 );
define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 );
define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 );
define( 'PCLZIP_ATT_FILE_MTIME', 79004 );
define( 'PCLZIP_ATT_FILE_CONTENT', 79005 );
define( 'PCLZIP_ATT_FILE_COMMENT', 79006 );
// ----- Call backs values
define( 'PCLZIP_CB_PRE_EXTRACT', 78001 );
define( 'PCLZIP_CB_POST_EXTRACT', 78002 );
define( 'PCLZIP_CB_PRE_ADD', 78003 );
define( 'PCLZIP_CB_POST_ADD', 78004 );
/* For futur use
define( 'PCLZIP_CB_PRE_LIST', 78005 );
define( 'PCLZIP_CB_POST_LIST', 78006 );
define( 'PCLZIP_CB_PRE_DELETE', 78007 );
define( 'PCLZIP_CB_POST_DELETE', 78008 );
*/
// --------------------------------------------------------------------------------
// Class : PclZip
// Description :
// PclZip is the class that represent a Zip archive.
// The public methods allow the manipulation of the archive.
// Attributes :
// Attributes must not be accessed directly.
// Methods :
// PclZip() : Object creator
// create() : Creates the Zip archive
// listContent() : List the content of the Zip archive
// extract() : Extract the content of the archive
// properties() : List the properties of the archive
// --------------------------------------------------------------------------------
class PclZip
{
// ----- Filename of the zip file
var $zipname = '';
// ----- File descriptor of the zip file
var $zip_fd = 0;
// ----- Internal error handling
var $error_code = 1;
var $error_string = '';
// ----- Current status of the magic_quotes_runtime
// This value store the php configuration for magic_quotes
// The class can then disable the magic_quotes and reset it after
var $magic_quotes_status;
// --------------------------------------------------------------------------------
// Function : PclZip()
// Description :
// Creates a PclZip object and set the name of the associated Zip archive
// filename.
// Note that no real action is taken, if the archive does not exist it is not
// created. Use create() for that.
// --------------------------------------------------------------------------------
function PclZip($p_zipname)
{
// ----- Tests the zlib
if (!function_exists('gzopen'))
{
die('Abort '.basename(__FILE__).' : Missing zlib extensions');
}
// ----- Set the attributes
$this->zipname = $p_zipname;
$this->zip_fd = 0;
$this->magic_quotes_status = -1;
// ----- Return
return;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// create($p_filelist, $p_add_dir="", $p_remove_dir="")
// create($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two different synopsis. The first one is historical.
// This method creates a Zip Archive. The Zip file is created in the
// filesystem. The files and directories indicated in $p_filelist
// are added in the archive. See the parameters description for the
// supported format of $p_filelist.
// When a directory is in the list, the directory and its content is added
// in the archive.
// In this synopsis, the function takes an optional variable list of
// options. See bellow the supported options.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_COMMENT :
// PCLZIP_CB_PRE_ADD :
// PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function create($p_filelist)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove from the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_ADD => 'optional',
PCLZIP_CB_POST_ADD => 'optional',
PCLZIP_OPT_NO_COMPRESSION => 'optional',
PCLZIP_OPT_COMMENT => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Invalid number / type of arguments");
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
if ($v_string != '') {
$v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
}
else {
}
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Call the create fct
$v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Return
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// add($p_filelist, $p_add_dir="", $p_remove_dir="")
// add($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two synopsis. The first one is historical.
// This methods add the list of files in an existing archive.
// If a file with the same name already exists, it is added at the end of the
// archive, the first one is still present.
// If the archive does not exist, it is created.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_COMMENT :
// PCLZIP_OPT_ADD_COMMENT :
// PCLZIP_OPT_PREPEND_COMMENT :
// PCLZIP_CB_PRE_ADD :
// PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function add($p_filelist)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_ADD => 'optional',
PCLZIP_CB_POST_ADD => 'optional',
PCLZIP_OPT_NO_COMPRESSION => 'optional',
PCLZIP_OPT_COMMENT => 'optional',
PCLZIP_OPT_ADD_COMMENT => 'optional',
PCLZIP_OPT_PREPEND_COMMENT => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
$v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Call the create fct
$v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Return
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : listContent()
// Description :
// This public method, gives the list of the files and directories, with their
// properties.
// The properties of each entries in the list are (used also in other functions) :
// filename : Name of the file. For a create or add action it is the filename
// given by the user. For an extract function it is the filename
// of the extracted file.
// stored_filename : Name of the file / directory stored in the archive.
// size : Size of the stored file.
// compressed_size : Size of the file's data compressed in the archive
// (without the headers overhead)
// mtime : Last known modification date of the file (UNIX timestamp)
// comment : Comment associated with the file
// folder : true | false
// index : index of the file in the archive
// status : status of the action (depending of the action) :
// Values are :
// ok : OK !
// filtered : the file / dir is not extracted (filtered by user)
// already_a_directory : the file can not be extracted because a
// directory with the same name already exists
// write_protected : the file can not be extracted because a file
// with the same name already exists and is
// write protected
// newer_exist : the file was not extracted because a newer file exists
// path_creation_fail : the file is not extracted because the folder
// does not exist and can not be created
// write_error : the file was not extracted because there was a
// error while writing the file
// read_error : the file was not extracted because there was a error
// while reading the file
// invalid_header : the file was not extracted because of an archive
// format error (bad file header)
// Note that each time a method can continue operating when there
// is an action error on a file, the error is only logged in the file status.
// Return Values :
// 0 on an unrecoverable failure,
// The list of the files in the archive.
// --------------------------------------------------------------------------------
function listContent()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = $this->privList($p_list)) != 1)
{
unset($p_list);
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extract($p_path="./", $p_remove_path="")
// extract([$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method extract all the files / directories from the archive to the
// folder indicated in $p_path.
// If you want to ignore the 'root' part of path of the memorized files
// you can indicate this in the optional $p_remove_path parameter.
// By default, if a newer file with the same name already exists, the
// file is not extracted.
//
// If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
// are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
// at the end of the path value of PCLZIP_OPT_PATH.
// Parameters :
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 or a negative value on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function extract()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
));
if ($v_result != 1) {
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Trace
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
$v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extractByIndex($p_index, $p_path="./", $p_remove_path="")
// extractByIndex($p_index, [$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method is doing a partial extract of the archive.
// The extracted files or folders are identified by their index in the
// archive (from 0 to n).
// Note that if the index identify a folder, only the folder entry is
// extracted, not all the files included in the archive.
// Parameters :
// $p_index : A single index (integer) or a string of indexes of files to
// extract. The form of the string is "0,4-6,8-12" with only numbers
// and '-' for range or ',' to separate ranges. No spaces or ';'
// are allowed.
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
// not as files.
// The resulting content is in a new field 'content' in the file
// structure.
// This option must be used alone (any other options are ignored).
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
//function extractByIndex($p_index, options...)
function extractByIndex($p_index)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
));
if ($v_result != 1) {
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
}
else {
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Trace
// ----- Trick
// Here I want to reuse extractByRule(), so I need to parse the $p_index
// with privParseOptions()
$v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index);
$v_options_trick = array();
$v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick,
array (PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
return 0;
}
$v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Call the extracting fct
if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// delete([$p_option, $p_option_value, ...])
// Description :
// This method removes files from the archive.
// If no parameters are given, then all the archive is emptied.
// Parameters :
// None or optional arguments.
// Options :
// PCLZIP_OPT_BY_INDEX :
// PCLZIP_OPT_BY_NAME :
// PCLZIP_OPT_BY_EREG :
// PCLZIP_OPT_BY_PREG :
// Return Values :
// 0 on failure,
// The list of the files which are still present in the archive.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function delete()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
return 0;
}
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Call the delete fct
$v_list = array();
if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
$this->privSwapBackMagicQuotes();
unset($v_list);
return(0);
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : deleteByIndex()
// Description :
// ***** Deprecated *****
// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
// --------------------------------------------------------------------------------
function deleteByIndex($p_index)
{
$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : properties()
// Description :
// This method gives the properties of the archive.
// The properties are :
// nb : Number of files in the archive
// comment : Comment associated with the archive file
// status : not_exist, ok
// Parameters :
// None
// Return Values :
// 0 on failure,
// An array with the archive properties.
// --------------------------------------------------------------------------------
function properties()
{
// ----- Reset the error handler
$this->privErrorReset();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check archive
if (!$this->privCheckFormat()) {
$this->privSwapBackMagicQuotes();
return(0);
}
// ----- Default properties
$v_prop = array();
$v_prop['comment'] = '';
$v_prop['nb'] = 0;
$v_prop['status'] = 'not_exist';
// ----- Look if file exists
if (@is_file($this->zipname))
{
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
return 0;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
return 0;
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Set the user attributes
$v_prop['comment'] = $v_central_dir['comment'];
$v_prop['nb'] = $v_central_dir['entries'];
$v_prop['status'] = 'ok';
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_prop;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : duplicate()
// Description :
// This method creates an archive by copying the content of an other one. If
// the archive already exist, it is replaced by the new one without any warning.
// Parameters :
// $p_archive : The filename of a valid archive, or
// a valid PclZip object.
// Return Values :
// 1 on success.
// 0 or a negative value on error (error code).
// --------------------------------------------------------------------------------
function duplicate($p_archive)
{
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the $p_archive is a PclZip object
if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip'))
{
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive->zipname);
}
// ----- Look if the $p_archive is a string (so a filename)
else if (is_string($p_archive))
{
// ----- Check that $p_archive is a valid zip file
// TBC : Should also check the archive format
if (!is_file($p_archive)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
$v_result = PCLZIP_ERR_MISSING_FILE;
}
else {
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive);
}
}
// ----- Invalid variable
else
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : merge()
// Description :
// This method merge the $p_archive_to_add archive at the end of the current
// one ($this).
// If the archive ($this) does not exist, the merge becomes a duplicate.
// If the $p_archive_to_add archive does not exist, the merge is a success.
// Parameters :
// $p_archive_to_add : It can be directly the filename of a valid zip archive,
// or a PclZip object archive.
// Return Values :
// 1 on success,
// 0 or negative values on error (see below).
// --------------------------------------------------------------------------------
function merge($p_archive_to_add)
{
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Look if the $p_archive_to_add is a PclZip object
if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip'))
{
// ----- Merge the archive
$v_result = $this->privMerge($p_archive_to_add);
}
// ----- Look if the $p_archive_to_add is a string (so a filename)
else if (is_string($p_archive_to_add))
{
// ----- Create a temporary archive
$v_object_archive = new PclZip($p_archive_to_add);
// ----- Merge the archive
$v_result = $this->privMerge($v_object_archive);
}
// ----- Invalid variable
else
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorCode()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorCode()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorCode());
}
else {
return($this->error_code);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorName()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorName($p_with_code=false)
{
$v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION'
,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE'
,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION'
);
if (isset($v_name[$this->error_code])) {
$v_value = $v_name[$this->error_code];
}
else {
$v_value = 'NoName';
}
if ($p_with_code) {
return($v_value.' ('.$this->error_code.')');
}
else {
return($v_value);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorInfo()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorInfo($p_full=false)
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorString());
}
else {
if ($p_full) {
return($this->errorName(true)." : ".$this->error_string);
}
else {
return($this->error_string." [code ".$this->error_code."]");
}
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFormat()
// Description :
// This method check that the archive exists and is a valid zip archive.
// Several level of check exists. (futur)
// Parameters :
// $p_level : Level of check. Default 0.
// 0 : Check the first bytes (magic codes) (default value))
// 1 : 0 + Check the central directory (futur)
// 2 : 1 + Check each file header (futur)
// Return Values :
// true on success,
// false on error, the error code is set.
// --------------------------------------------------------------------------------
function privCheckFormat($p_level=0)
{
$v_result = true;
// ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the file exits
if (!is_file($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
return(false);
}
// ----- Check that the file is readeable
if (!is_readable($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
return(false);
}
// ----- Check the magic code
// TBC
// ----- Check the central header
// TBC
// ----- Check each file header
// TBC
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privParseOptions()
// Description :
// This internal methods reads the variable list of arguments ($p_options_list,
// $p_size) and generate an array with the options and values ($v_result_list).
// $v_requested_options contains the options that can be present and those that
// must be present.
// $v_requested_options is an array, with the option value as key, and 'optional',
// or 'mandatory' as value.
// Parameters :
// See above.
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
{
$v_result=1;
// ----- Read the options
$i=0;
while ($i<$p_size) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$p_options_list[$i]])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for next option
switch ($p_options_list[$i]) {
// ----- Look for options that request a path value
case PCLZIP_OPT_PATH :
case PCLZIP_OPT_REMOVE_PATH :
case PCLZIP_OPT_ADD_PATH :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
$i++;
break;
case PCLZIP_OPT_TEMP_FILE_THRESHOLD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
return PclZip::errorCode();
}
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
return PclZip::errorCode();
}
// ----- Check the value
$v_value = $p_options_list[$i+1];
if ((!is_integer($v_value)) || ($v_value<0)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'");
return PclZip::errorCode();
}
// ----- Get the value (and convert it in bytes)
$v_result_list[$p_options_list[$i]] = $v_value*1048576;
$i++;
break;
case PCLZIP_OPT_TEMP_FILE_ON :
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
return PclZip::errorCode();
}
$v_result_list[$p_options_list[$i]] = true;
break;
case PCLZIP_OPT_TEMP_FILE_OFF :
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'");
return PclZip::errorCode();
}
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
return PclZip::errorCode();
}
$v_result_list[$p_options_list[$i]] = true;
break;
case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if ( is_string($p_options_list[$i+1])
&& ($p_options_list[$i+1] != '')) {
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
$i++;
}
else {
}
break;
// ----- Look for options that request an array of string for value
case PCLZIP_OPT_BY_NAME :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that request an EREG or PREG expression
case PCLZIP_OPT_BY_EREG :
// ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG
// to PCLZIP_OPT_BY_PREG
$p_options_list[$i] = PCLZIP_OPT_BY_PREG;
case PCLZIP_OPT_BY_PREG :
//case PCLZIP_OPT_CRYPT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that takes a string
case PCLZIP_OPT_COMMENT :
case PCLZIP_OPT_ADD_COMMENT :
case PCLZIP_OPT_PREPEND_COMMENT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
"Missing parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
"Wrong parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
return PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that request an array of index
case PCLZIP_OPT_BY_INDEX :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_work_list = array();
if (is_string($p_options_list[$i+1])) {
// ----- Remove spaces
$p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
// ----- Parse items
$v_work_list = explode(",", $p_options_list[$i+1]);
}
else if (is_integer($p_options_list[$i+1])) {
$v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_work_list = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Reduce the index list
// each index item in the list must be a couple with a start and
// an end value : [0,3], [5-5], [8-10], ...
// ----- Check the format of each item
$v_sort_flag=false;
$v_sort_value=0;
for ($j=0; $j<sizeof($v_work_list); $j++) {
// ----- Explode the item
$v_item_list = explode("-", $v_work_list[$j]);
$v_size_item_list = sizeof($v_item_list);
// ----- TBC : Here we might check that each item is a
// real integer ...
// ----- Look for single value
if ($v_size_item_list == 1) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
}
elseif ($v_size_item_list == 2) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for list sort
if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
$v_sort_flag=true;
// ----- TBC : An automatic sort should be writen ...
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
$v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
}
// ----- Sort the items
if ($v_sort_flag) {
// TBC : To Be Completed
}
// ----- Next option
$i++;
break;
// ----- Look for options that request no value
case PCLZIP_OPT_REMOVE_ALL_PATH :
case PCLZIP_OPT_EXTRACT_AS_STRING :
case PCLZIP_OPT_NO_COMPRESSION :
case PCLZIP_OPT_EXTRACT_IN_OUTPUT :
case PCLZIP_OPT_REPLACE_NEWER :
case PCLZIP_OPT_STOP_ON_ERROR :
$v_result_list[$p_options_list[$i]] = true;
break;
// ----- Look for options that request an octal value
case PCLZIP_OPT_SET_CHMOD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
$i++;
break;
// ----- Look for options that request a call-back
case PCLZIP_CB_PRE_EXTRACT :
case PCLZIP_CB_POST_EXTRACT :
case PCLZIP_CB_PRE_ADD :
case PCLZIP_CB_POST_ADD :
/* for futur use
case PCLZIP_CB_PRE_DELETE :
case PCLZIP_CB_POST_DELETE :
case PCLZIP_CB_PRE_LIST :
case PCLZIP_CB_POST_LIST :
*/
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_function_name = $p_options_list[$i+1];
// ----- Check that the value is a valid existing function
if (!is_callable($v_function_name)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Set the attribute
$v_result_list[$p_options_list[$i]] = $v_function_name;
$i++;
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '"
.$p_options_list[$i]."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Next options
$i++;
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
// ----- Look if present
if (!isset($v_result_list[$key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Return
return PclZip::errorCode();
}
}
}
}
// ----- Look for default values
if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOptionDefaultThreshold()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privOptionDefaultThreshold(&$p_options)
{
$v_result=1;
if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
|| isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) {
return $v_result;
}
// ----- Get 'memory_limit' configuration value
$v_memory_limit = ini_get('memory_limit');
$v_memory_limit = trim($v_memory_limit);
$last = strtolower(substr($v_memory_limit, -1));
if($last == 'g')
//$v_memory_limit = $v_memory_limit*1024*1024*1024;
$v_memory_limit = $v_memory_limit*1073741824;
if($last == 'm')
//$v_memory_limit = $v_memory_limit*1024*1024;
$v_memory_limit = $v_memory_limit*1048576;
if($last == 'k')
$v_memory_limit = $v_memory_limit*1024;
$p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO);
// ----- Sanity check : No threshold if value lower than 1M
if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) {
unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrParseAtt()
// Description :
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false)
{
$v_result=1;
// ----- For each file in the list check the attributes
foreach ($p_file_list as $v_key => $v_value) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$v_key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for attribute
switch ($v_key) {
case PCLZIP_ATT_FILE_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['filename'] = PclZipUtilPathReduction($v_value);
if ($p_filedescr['filename'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
break;
case PCLZIP_ATT_FILE_NEW_SHORT_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value);
if ($p_filedescr['new_short_name'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
break;
case PCLZIP_ATT_FILE_NEW_FULL_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value);
if ($p_filedescr['new_full_name'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
break;
// ----- Look for options that takes a string
case PCLZIP_ATT_FILE_COMMENT :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['comment'] = $v_value;
break;
case PCLZIP_ATT_FILE_MTIME :
if (!is_integer($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['mtime'] = $v_value;
break;
case PCLZIP_ATT_FILE_CONTENT :
$p_filedescr['content'] = $v_value;
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '".$v_key."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
// ----- Look if present
if (!isset($p_file_list[$key])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
return PclZip::errorCode();
}
}
}
}
// end foreach
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrExpand()
// Description :
// This method look for each item of the list to see if its a file, a folder
// or a string to be added as file. For any other type of files (link, other)
// just ignore the item.
// Then prepare the information that will be stored for that file.
// When its a folder, expand the folder with all the files that are in that
// folder (recursively).
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrExpand(&$p_filedescr_list, &$p_options)
{
$v_result=1;
// ----- Create a result list
$v_result_list = array();
// ----- Look each entry
for ($i=0; $i<sizeof($p_filedescr_list); $i++) {
// ----- Get filedescr
$v_descr = $p_filedescr_list[$i];
// ----- Reduce the filename
$v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false);
$v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']);
// ----- Look for real file or folder
if (file_exists($v_descr['filename'])) {
if (@is_file($v_descr['filename'])) {
$v_descr['type'] = 'file';
}
else if (@is_dir($v_descr['filename'])) {
$v_descr['type'] = 'folder';
}
else if (@is_link($v_descr['filename'])) {
// skip
continue;
}
else {
// skip
continue;
}
}
// ----- Look for string added as file
else if (isset($v_descr['content'])) {
$v_descr['type'] = 'virtual_file';
}
// ----- Missing file
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist");
// ----- Return
return PclZip::errorCode();
}
// ----- Calculate the stored filename
$this->privCalculateStoredFilename($v_descr, $p_options);
// ----- Add the descriptor in result list
$v_result_list[sizeof($v_result_list)] = $v_descr;
// ----- Look for folder
if ($v_descr['type'] == 'folder') {
// ----- List of items in folder
$v_dirlist_descr = array();
$v_dirlist_nb = 0;
if ($v_folder_handler = @opendir($v_descr['filename'])) {
while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
// ----- Skip '.' and '..'
if (($v_item_handler == '.') || ($v_item_handler == '..')) {
continue;
}
// ----- Compose the full filename
$v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
// ----- Look for different stored filename
// Because the name of the folder was changed, the name of the
// files/sub-folders also change
if (($v_descr['stored_filename'] != $v_descr['filename'])
&& (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
if ($v_descr['stored_filename'] != '') {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
}
else {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
}
}
$v_dirlist_nb++;
}
@closedir($v_folder_handler);
}
else {
// TBC : unable to open folder in read mode
}
// ----- Expand each element of the list
if ($v_dirlist_nb != 0) {
// ----- Expand
if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
return $v_result;
}
// ----- Concat the resulting list
$v_result_list = array_merge($v_result_list, $v_dirlist_descr);
}
else {
}
// ----- Free local array
unset($v_dirlist_descr);
}
}
// ----- Get the result list
$p_filedescr_list = $v_result_list;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCreate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the file in write mode
if (($v_result = $this->privOpenFd('wb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Add the list of files
$v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
// ----- Close
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAdd()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Look if the archive exists or is empty
if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0))
{
// ----- Do a create
$v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
// ----- Return
return $v_result;
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
fclose($v_zip_temp_fd);
$this->privCloseFd();
@unlink($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Create the Central Dir files header
for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++)
{
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
fclose($v_zip_temp_fd);
$this->privCloseFd();
@unlink($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = $v_central_dir['comment'];
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) {
$v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT];
}
if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment;
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOpenFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privOpenFd($p_mode)
{
$v_result=1;
// ----- Look if already open
if ($this->zip_fd != 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
// ----- Return
return PclZip::errorCode();
}
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCloseFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privCloseFd()
{
$v_result=1;
if ($this->zip_fd != 0)
@fclose($this->zip_fd);
$this->zip_fd = 0;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddList()
// Description :
// $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
// different from the real path of the file. This is usefull if you want to have PclTar
// running in any directory, and memorize relative path from an other directory.
// Parameters :
// $p_list : An array containing the file or directory names to add in the tar
// $p_result_list : list of added files with their properties (specially the status field)
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// Return Values :
// --------------------------------------------------------------------------------
// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Create the Central Dir files header
for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++)
{
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
// ----- Return
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
// ----- Return
return $v_result;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileList()
// Description :
// Parameters :
// $p_filedescr_list : An array containing the file description
// or directory names to add in the zip
// $p_result_list : list of added files with their properties (specially the status field)
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_header = array();
// ----- Recuperate the current number of elt in list
$v_nb = sizeof($p_result_list);
// ----- Loop on the files
for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) {
// ----- Format the filename
$p_filedescr_list[$j]['filename']
= PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
// ----- Skip empty file names
// TBC : Can this be possible ? not checked in DescrParseAtt ?
if ($p_filedescr_list[$j]['filename'] == "") {
continue;
}
// ----- Check the filename
if ( ($p_filedescr_list[$j]['type'] != 'virtual_file')
&& (!file_exists($p_filedescr_list[$j]['filename']))) {
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist");
return PclZip::errorCode();
}
// ----- Look if it is a file or a dir with no all path remove option
// or a dir with all its path removed
// if ( (is_file($p_filedescr_list[$j]['filename']))
// || ( is_dir($p_filedescr_list[$j]['filename'])
if ( ($p_filedescr_list[$j]['type'] == 'file')
|| ($p_filedescr_list[$j]['type'] == 'virtual_file')
|| ( ($p_filedescr_list[$j]['type'] == 'folder')
&& ( !isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])
|| !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))
) {
// ----- Add the file
$v_result = $this->privAddFile($p_filedescr_list[$j], $v_header,
$p_options);
if ($v_result != 1) {
return $v_result;
}
// ----- Store the file infos
$p_result_list[$v_nb++] = $v_header;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFile($p_filedescr, &$p_header, &$p_options)
{
$v_result=1;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// TBC : Already done in the fileAtt check ... ?
if ($p_filename == "") {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for a stored different filename
/* TBC : Removed
if (isset($p_filedescr['stored_filename'])) {
$v_stored_filename = $p_filedescr['stored_filename'];
}
else {
$v_stored_filename = $p_filedescr['stored_filename'];
}
*/
// ----- Set the file properties
clearstatcache();
$p_header['version'] = 20;
$p_header['version_extracted'] = 10;
$p_header['flag'] = 0;
$p_header['compression'] = 0;
$p_header['crc'] = 0;
$p_header['compressed_size'] = 0;
$p_header['filename_len'] = strlen($p_filename);
$p_header['extra_len'] = 0;
$p_header['disk'] = 0;
$p_header['internal'] = 0;
$p_header['offset'] = 0;
$p_header['filename'] = $p_filename;
// TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
$p_header['stored_filename'] = $p_filedescr['stored_filename'];
$p_header['extra'] = '';
$p_header['status'] = 'ok';
$p_header['index'] = -1;
// ----- Look for regular file
if ($p_filedescr['type']=='file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = filesize($p_filename);
}
// ----- Look for regular folder
else if ($p_filedescr['type']=='folder') {
$p_header['external'] = 0x00000010;
$p_header['mtime'] = filemtime($p_filename);
$p_header['size'] = filesize($p_filename);
}
// ----- Look for virtual file
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = strlen($p_filedescr['content']);
}
// ----- Look for filetime
if (isset($p_filedescr['mtime'])) {
$p_header['mtime'] = $p_filedescr['mtime'];
}
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['mtime'] = time();
}
else {
$p_header['mtime'] = filemtime($p_filename);
}
// ------ Look for file comment
if (isset($p_filedescr['comment'])) {
$p_header['comment_len'] = strlen($p_filedescr['comment']);
$p_header['comment'] = $p_filedescr['comment'];
}
else {
$p_header['comment_len'] = 0;
$p_header['comment'] = '';
}
// ----- Look for pre-add callback
if (isset($p_options[PCLZIP_CB_PRE_ADD])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_header['status'] = "skipped";
$v_result = 1;
}
// ----- Update the informations
// Only some fields can be modified
if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
$p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);
}
}
// ----- Look for empty stored filename
if ($p_header['stored_filename'] == "") {
$p_header['status'] = "filtered";
}
// ----- Check the path length
if (strlen($p_header['stored_filename']) > 0xFF) {
$p_header['status'] = 'filename_too_long';
}
// ----- Look if no error, or file not skipped
if ($p_header['status'] == 'ok') {
// ----- Look for a file
if ($p_filedescr['type'] == 'file') {
// ----- Look for using temporary file to zip
if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF]))
&& (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON])
|| (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
&& ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) {
$v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
if ($v_result < PCLZIP_ERR_NO_ERROR) {
return $v_result;
}
}
// ----- Use "in memory" zip algo
else {
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
return PclZip::errorCode();
}
// ----- Read the file content
$v_content = @fread($v_file, $p_header['size']);
// ----- Close the file
@fclose($v_file);
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
}
// ----- Look for a virtual file (a file from string)
else if ($p_filedescr['type'] == 'virtual_file') {
$v_content = $p_filedescr['content'];
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
// ----- Look for a directory
else if ($p_filedescr['type'] == 'folder') {
// ----- Look for directory last '/'
if (@substr($p_header['stored_filename'], -1) != '/') {
$p_header['stored_filename'] .= '/';
}
// ----- Set the file properties
$p_header['size'] = 0;
//$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
$p_header['external'] = 0x00000010; // Value for a folder : to be checked
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1)
{
return $v_result;
}
}
}
// ----- Look for post-add callback
if (isset($p_options[PCLZIP_CB_POST_ADD])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header);
if ($v_result == 0) {
// ----- Ignored
$v_result = 1;
}
// ----- Update the informations
// Nothing can be modified
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileUsingTempFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
{
$v_result=PCLZIP_ERR_NO_ERROR;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
return PclZip::errorCode();
}
// ----- Creates a compressed temporary file
$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
fclose($v_file);
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
return PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = filesize($p_filename);
while ($v_size != 0) {
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_file, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@gzputs($v_file_compressed, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close the file
@fclose($v_file);
@gzclose($v_file_compressed);
// ----- Check the minimum file size
if (filesize($v_gzip_temp_name) < 18) {
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes');
return PclZip::errorCode();
}
// ----- Extract the compressed attributes
if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return PclZip::errorCode();
}
// ----- Read the gzip file header
$v_binary_data = @fread($v_file_compressed, 10);
$v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
// ----- Check some parameters
$v_data_header['os'] = bin2hex($v_data_header['os']);
// ----- Read the gzip file footer
@fseek($v_file_compressed, filesize($v_gzip_temp_name)-8);
$v_binary_data = @fread($v_file_compressed, 8);
$v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
// ----- Set the attributes
$p_header['compression'] = ord($v_data_header['cm']);
//$p_header['mtime'] = $v_data_header['mtime'];
$p_header['crc'] = $v_data_footer['crc'];
$p_header['compressed_size'] = filesize($v_gzip_temp_name)-18;
// ----- Close the file
@fclose($v_file_compressed);
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
return $v_result;
}
// ----- Add the compressed data
if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0)
{
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
fseek($v_file_compressed, 10);
$v_size = $p_header['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_file_compressed, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close the file
@fclose($v_file_compressed);
// ----- Unlink the temporary file
@unlink($v_gzip_temp_name);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCalculateStoredFilename()
// Description :
// Based on file descriptor properties and global options, this method
// calculate the filename that will be stored in the archive.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCalculateStoredFilename(&$p_filedescr, &$p_options)
{
$v_result=1;
// ----- Working variables
$p_filename = $p_filedescr['filename'];
if (isset($p_options[PCLZIP_OPT_ADD_PATH])) {
$p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH];
}
else {
$p_add_dir = '';
}
if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) {
$p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH];
}
else {
$p_remove_dir = '';
}
if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
else {
$p_remove_all_dir = 0;
}
// ----- Look for full name change
if (isset($p_filedescr['new_full_name'])) {
// ----- Remove drive letter if any
$v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']);
}
// ----- Look for path and/or short name change
else {
// ----- Look for short name change
// Its when we cahnge just the filename but not the path
if (isset($p_filedescr['new_short_name'])) {
$v_path_info = pathinfo($p_filename);
$v_dir = '';
if ($v_path_info['dirname'] != '') {
$v_dir = $v_path_info['dirname'].'/';
}
$v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
}
else {
// ----- Calculate the stored filename
$v_stored_filename = $p_filename;
}
// ----- Look for all path to remove
if ($p_remove_all_dir) {
$v_stored_filename = basename($p_filename);
}
// ----- Look for partial path remove
else if ($p_remove_dir != "") {
if (substr($p_remove_dir, -1) != '/')
$p_remove_dir .= "/";
if ( (substr($p_filename, 0, 2) == "./")
|| (substr($p_remove_dir, 0, 2) == "./")) {
if ( (substr($p_filename, 0, 2) == "./")
&& (substr($p_remove_dir, 0, 2) != "./")) {
$p_remove_dir = "./".$p_remove_dir;
}
if ( (substr($p_filename, 0, 2) != "./")
&& (substr($p_remove_dir, 0, 2) == "./")) {
$p_remove_dir = substr($p_remove_dir, 2);
}
}
$v_compare = PclZipUtilPathInclusion($p_remove_dir,
$v_stored_filename);
if ($v_compare > 0) {
if ($v_compare == 2) {
$v_stored_filename = "";
}
else {
$v_stored_filename = substr($v_stored_filename,
strlen($p_remove_dir));
}
}
}
// ----- Remove drive letter if any
$v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename);
// ----- Look for path to add
if ($p_add_dir != "") {
if (substr($p_add_dir, -1) == "/")
$v_stored_filename = $p_add_dir.$v_stored_filename;
else
$v_stored_filename = $p_add_dir."/".$v_stored_filename;
}
}
// ----- Filename (reduce the path of stored name)
$v_stored_filename = PclZipUtilPathReduction($v_stored_filename);
$p_filedescr['stored_filename'] = $v_stored_filename;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteFileHeader(&$p_header)
{
$v_result=1;
// ----- Store the offset position of the file
$p_header['offset'] = ftell($this->zip_fd);
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
$p_header['version_extracted'], $p_header['flag'],
$p_header['compression'], $v_mtime, $v_mdate,
$p_header['crc'], $p_header['compressed_size'],
$p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len']);
// ----- Write the first 148 bytes of the header in the archive
fputs($this->zip_fd, $v_binary_data, 30);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralFileHeader(&$p_header)
{
$v_result=1;
// TBC
//for(reset($p_header); $key = key($p_header); next($p_header)) {
//}
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
$p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
$v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
$p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
if ($p_header['comment_len'] != 0)
{
fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
{
$v_result=1;
// ----- Packed data
$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
$p_nb_entries, $p_size,
$p_offset, strlen($p_comment));
// ----- Write the 22 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 22);
// ----- Write the variable fields
if (strlen($p_comment) != 0)
{
fputs($this->zip_fd, $p_comment, strlen($p_comment));
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privList()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privList(&$p_list)
{
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of Central Dir
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_central_dir['offset']))
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read each entry
for ($i=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
$v_header['index'] = $i;
// ----- Get the only interesting attributes
$this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
unset($v_header);
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privConvertHeader2FileInfo()
// Description :
// This function takes the file informations from the central directory
// entries and extract the interesting parameters that will be given back.
// The resulting file infos are set in the array $p_info
// $p_info['filename'] : Filename with full path. Given by user (add),
// extracted in the filesystem (extract).
// $p_info['stored_filename'] : Stored filename in the archive.
// $p_info['size'] = Size of the file.
// $p_info['compressed_size'] = Compressed size of the file.
// $p_info['mtime'] = Last modification date of the file.
// $p_info['comment'] = Comment associated with the file.
// $p_info['folder'] = true/false : indicates if the entry is a folder or not.
// $p_info['status'] = status of the action on the file.
// $p_info['crc'] = CRC of the file content.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privConvertHeader2FileInfo($p_header, &$p_info)
{
$v_result=1;
// ----- Get the interesting attributes
$v_temp_path = PclZipUtilPathReduction($p_header['filename']);
$p_info['filename'] = $v_temp_path;
$v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']);
$p_info['stored_filename'] = $v_temp_path;
$p_info['size'] = $p_header['size'];
$p_info['compressed_size'] = $p_header['compressed_size'];
$p_info['mtime'] = $p_header['mtime'];
$p_info['comment'] = $p_header['comment'];
$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
$p_info['index'] = $p_header['index'];
$p_info['status'] = $p_header['status'];
$p_info['crc'] = $p_header['crc'];
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractByRule()
// Description :
// Extract a file or directory depending of rules (by index, by name, ...)
// Parameters :
// $p_file_list : An array where will be placed the properties of each
// extracted file
// $p_path : Path to add while writing the extracted files
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// 1 on success,0 or less on error (see error code list)
// --------------------------------------------------------------------------------
function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check the path
if ( ($p_path == "")
|| ( (substr($p_path, 0, 1) != "/")
&& (substr($p_path, 0, 3) != "../")
&& (substr($p_path,1,2)!=":/")))
$p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
$p_path = substr($p_path, 0, strlen($p_path)-1);
}
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the zip file
if (($v_result = $this->privOpenFd('rb')) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
// ----- Read each entry
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read next Central dir entry
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Store the index
$v_header['index'] = $i;
// ----- Store the file position
$v_pos_entry = ftell($this->zip_fd);
// ----- Look for the specific extract rules
$v_extract = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) {
// ----- Look for a directory
if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
// ----- Look if the directory is in the filename path
if ( (strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
$v_extract = true;
}
}
// ----- Look for a filename
elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
$v_extract = true;
}
}
}
// ----- Look for extract by ereg rule
// ereg() is deprecated with PHP 5.3
/*
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
$v_extract = true;
}
}
*/
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
$v_extract = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) {
if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
$v_extract = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
break;
}
}
}
// ----- Look for no rule, which means extract all the archive
else {
$v_extract = true;
}
// ----- Check compression method
if ( ($v_extract)
&& ( ($v_header['compression'] != 8)
&& ($v_header['compression'] != 0))) {
$v_header['status'] = 'unsupported_compression';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
"Filename '".$v_header['stored_filename']."' is "
."compressed by an unsupported compression "
."method (".$v_header['compression'].") ");
return PclZip::errorCode();
}
}
// ----- Check encrypted files
if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
$v_header['status'] = 'unsupported_encryption';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
"Unsupported encryption for "
." filename '".$v_header['stored_filename']
."'");
return PclZip::errorCode();
}
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
$v_result = $this->privConvertHeader2FileInfo($v_header,
$p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
$v_extract = false;
}
// ----- Look for real extraction
if ($v_extract)
{
// ----- Go to the file position
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_header['offset']))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Look for extraction as string
if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
$v_string = '';
// ----- Extracting the file
$v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Set the file content
$p_file_list[$v_nb_extracted]['content'] = $v_string;
// ----- Next extracted file
$v_nb_extracted++;
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
&& ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
$p_path, $p_remove_path,
$p_remove_all_path,
$p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
}
}
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFile()
// Description :
// Parameters :
// Return Values :
//
// 1 : ... ?
// PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
// --------------------------------------------------------------------------------
function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for all path to remove
if ($p_remove_all_path == true) {
// ----- Look for folder entry that not need to be extracted
if (($p_entry['external']&0x00000010)==0x00000010) {
$p_entry['status'] = "filtered";
return $v_result;
}
// ----- Get the basename of the path
$p_entry['filename'] = basename($p_entry['filename']);
}
// ----- Look for path to remove
else if ($p_remove_path != "")
{
if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2)
{
// ----- Change the file status
$p_entry['status'] = "filtered";
// ----- Return
return $v_result;
}
$p_remove_path_size = strlen($p_remove_path);
if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path)
{
// ----- Remove the path
$p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
}
}
// ----- Add the path
if ($p_path != '') {
$p_entry['filename'] = $p_path."/".$p_entry['filename'];
}
// ----- Check a base_dir_restriction
if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
$v_inclusion
= PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION],
$p_entry['filename']);
if ($v_inclusion == 0) {
PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
"Filename '".$p_entry['filename']."' is "
."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
return PclZip::errorCode();
}
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Look for specific actions while the file exist
if (file_exists($p_entry['filename']))
{
// ----- Look if file is a directory
if (is_dir($p_entry['filename']))
{
// ----- Change the file status
$p_entry['status'] = "already_a_directory";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
"Filename '".$p_entry['filename']."' is "
."already used by an existing directory");
return PclZip::errorCode();
}
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
{
// ----- Change the file status
$p_entry['status'] = "write_protected";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Filename '".$p_entry['filename']."' exists "
."and is write protected");
return PclZip::errorCode();
}
}
// ----- Look if the extracted file is older
else if (filemtime($p_entry['filename']) > $p_entry['mtime'])
{
// ----- Change the file status
if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
&& ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
}
else {
$p_entry['status'] = "newer_exist";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Newer version of '".$p_entry['filename']."' exists "
."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
return PclZip::errorCode();
}
}
}
else {
}
}
// ----- Check the directory availability and create it if necessary
else {
if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/'))
$v_dir_to_check = $p_entry['filename'];
else if (!strstr($p_entry['filename'], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($p_entry['filename']);
if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
// ----- Change the file status
$p_entry['status'] = "path_creation_fail";
// ----- Return
//return $v_result;
$v_result = 1;
}
}
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
// ----- Change the file status
$p_entry['status'] = "write_error";
// ----- Return
return $v_result;
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
/* Try to speed up the code
$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_binary_data, $v_read_size);
*/
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Closing the destination file
fclose($v_dest_file);
// ----- Change the file mtime
@touch($p_entry['filename'], $p_entry['mtime']);
}
else {
// ----- TBC
// Need to be finished
if (($p_entry['flag'] & 1) == 1) {
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.');
return PclZip::errorCode();
}
// ----- Look for using temporary file to unzip
if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF]))
&& (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON])
|| (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
&& ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) {
$v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
if ($v_result < PCLZIP_ERR_NO_ERROR) {
return $v_result;
}
}
// ----- Look for extract in memory
else {
// ----- Read the compressed file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
$v_file_content = @gzinflate($v_buffer);
unset($v_buffer);
if ($v_file_content === FALSE) {
// ----- Change the file status
// TBC
$p_entry['status'] = "error";
return $v_result;
}
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
// ----- Change the file status
$p_entry['status'] = "write_error";
return $v_result;
}
// ----- Write the uncompressed data
@fwrite($v_dest_file, $v_file_content, $p_entry['size']);
unset($v_file_content);
// ----- Closing the destination file
@fclose($v_dest_file);
}
// ----- Change the file mtime
@touch($p_entry['filename'], $p_entry['mtime']);
}
// ----- Look for chmod option
if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
// ----- Change the mode of the file
@chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
}
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileUsingTempFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileUsingTempFile(&$p_entry, &$p_options)
{
$v_result=1;
// ----- Creates a temporary file
$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
fclose($v_file);
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
return PclZip::errorCode();
}
// ----- Write gz file format header
$v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
@fwrite($v_dest_file, $v_binary_data, 10);
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Write gz file format footer
$v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
@fwrite($v_dest_file, $v_binary_data, 8);
// ----- Close the temporary file
@fclose($v_dest_file);
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
$p_entry['status'] = "write_error";
return $v_result;
}
// ----- Open the temporary gz file
if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
@fclose($v_dest_file);
$p_entry['status'] = "read_error";
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['size'];
while ($v_size != 0) {
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($v_src_file, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
@fclose($v_dest_file);
@gzclose($v_src_file);
// ----- Delete the temporary file
@unlink($v_gzip_temp_name);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileInOutput()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileInOutput(&$p_entry, &$p_options)
{
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Trace
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
if ($p_entry['compressed_size'] == $p_entry['size']) {
// ----- Read the file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Send the file to the output
echo $v_buffer;
unset($v_buffer);
}
else {
// ----- Read the compressed file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
$v_file_content = gzinflate($v_buffer);
unset($v_buffer);
// ----- Send the file to the output
echo $v_file_content;
unset($v_file_content);
}
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileAsString()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
{
$v_result=1;
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
// if ($p_entry['compressed_size'] == $p_entry['size'])
if ($p_entry['compression'] == 0) {
// ----- Reading the file
$p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
// ----- Reading the file
$v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
if (($p_string = @gzinflate($v_data)) === FALSE) {
// TBC
}
}
// ----- Trace
}
else {
// TBC : error : can not extract a folder in a string
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Swap the content to header
$v_local_header['content'] = $p_string;
$p_string = '';
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Swap back the content to header
$p_string = $v_local_header['content'];
unset($v_local_header['content']);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadFileHeader(&$p_header)
{
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] != 0x04034b50)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 26);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 26)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
return PclZip::errorCode();
}
// ----- Extract the values
$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
// ----- Get filename
$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
// ----- Get extra_fields
if ($v_data['extra_len'] != 0) {
$p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
}
else {
$p_header['extra'] = '';
}
// ----- Extract properties
$p_header['version_extracted'] = $v_data['version'];
$p_header['compression'] = $v_data['compression'];
$p_header['size'] = $v_data['size'];
$p_header['compressed_size'] = $v_data['compressed_size'];
$p_header['crc'] = $v_data['crc'];
$p_header['flag'] = $v_data['flag'];
$p_header['filename_len'] = $v_data['filename_len'];
// ----- Recuperate date in UNIX format
$p_header['mdate'] = $v_data['mdate'];
$p_header['mtime'] = $v_data['mtime'];
if ($p_header['mdate'] && $p_header['mtime'])
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
}
else
{
$p_header['mtime'] = time();
}
// TBC
//for(reset($v_data); $key = key($v_data); next($v_data)) {
//}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set the status field
$p_header['status'] = "ok";
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadCentralFileHeader(&$p_header)
{
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] != 0x02014b50)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 42);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 42)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
return PclZip::errorCode();
}
// ----- Extract the values
$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
// ----- Get filename
if ($p_header['filename_len'] != 0)
$p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
else
$p_header['filename'] = '';
// ----- Get extra
if ($p_header['extra_len'] != 0)
$p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
else
$p_header['extra'] = '';
// ----- Get comment
if ($p_header['comment_len'] != 0)
$p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
else
$p_header['comment'] = '';
// ----- Extract properties
// ----- Recuperate date in UNIX format
//if ($p_header['mdate'] && $p_header['mtime'])
// TBC : bug : this was ignoring time with 0/0/0
if (1)
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
}
else
{
$p_header['mtime'] = time();
}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set default status to ok
$p_header['status'] = 'ok';
// ----- Look if it is a directory
if (substr($p_header['filename'], -1) == '/') {
//$p_header['external'] = 0x41FF0010;
$p_header['external'] = 0x00000010;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFileHeaders()
// Description :
// Parameters :
// Return Values :
// 1 on success,
// 0 on error;
// --------------------------------------------------------------------------------
function privCheckFileHeaders(&$p_local_header, &$p_central_header)
{
$v_result=1;
// ----- Check the static values
// TBC
if ($p_local_header['filename'] != $p_central_header['filename']) {
}
if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
}
if ($p_local_header['flag'] != $p_central_header['flag']) {
}
if ($p_local_header['compression'] != $p_central_header['compression']) {
}
if ($p_local_header['mtime'] != $p_central_header['mtime']) {
}
if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
}
// ----- Look for flag bit 3
if (($p_local_header['flag'] & 8) == 8) {
$p_local_header['size'] = $p_central_header['size'];
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
$p_local_header['crc'] = $p_central_header['crc'];
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadEndCentralDir()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadEndCentralDir(&$p_central_dir)
{
$v_result=1;
// ----- Go to the end of the zip file
$v_size = filesize($this->zipname);
@fseek($this->zip_fd, $v_size);
if (@ftell($this->zip_fd) != $v_size)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
// ----- Return
return PclZip::errorCode();
}
// ----- First try : look if this is an archive with no commentaries (most of the time)
// in this case the end of central dir is at 22 bytes of the file end
$v_found = 0;
if ($v_size > 26) {
@fseek($this->zip_fd, $v_size-22);
if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
return PclZip::errorCode();
}
// ----- Read for bytes
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = @unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] == 0x06054b50) {
$v_found = 1;
}
$v_pos = ftell($this->zip_fd);
}
// ----- Go back to the maximum possible size of the Central Dir End Record
if (!$v_found) {
$v_maximum_size = 65557; // 0xFFFF + 22;
if ($v_maximum_size > $v_size)
$v_maximum_size = $v_size;
@fseek($this->zip_fd, $v_size-$v_maximum_size);
if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
return PclZip::errorCode();
}
// ----- Read byte per byte in order to find the signature
$v_pos = ftell($this->zip_fd);
$v_bytes = 0x00000000;
while ($v_pos < $v_size)
{
// ----- Read a byte
$v_byte = @fread($this->zip_fd, 1);
// ----- Add the byte
//$v_bytes = ($v_bytes << 8) | Ord($v_byte);
// Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
// Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
$v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
// ----- Compare the bytes
if ($v_bytes == 0x504b0506)
{
$v_pos++;
break;
}
$v_pos++;
}
// ----- Look if not found end of central dir
if ($v_pos == $v_size)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
// ----- Return
return PclZip::errorCode();
}
}
// ----- Read the first 18 bytes of the header
$v_binary_data = fread($this->zip_fd, 18);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 18)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Return
return PclZip::errorCode();
}
// ----- Extract the values
$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
// ----- Check the global size
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
// ----- Removed in release 2.2 see readme file
// The check of the file size is a little too strict.
// Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
// While decrypted, zip has training 0 bytes
if (0) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
'The central dir is not at the end of the archive.'
.' Some trailing bytes exists after the archive.');
// ----- Return
return PclZip::errorCode();
}
}
// ----- Get comment
if ($v_data['comment_size'] != 0) {
$p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
}
else
$p_central_dir['comment'] = '';
$p_central_dir['entries'] = $v_data['entries'];
$p_central_dir['disk_entries'] = $v_data['disk_entries'];
$p_central_dir['offset'] = $v_data['offset'];
$p_central_dir['size'] = $v_data['size'];
$p_central_dir['disk'] = $v_data['disk'];
$p_central_dir['disk_start'] = $v_data['disk_start'];
// TBC
//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
//}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDeleteByRule()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDeleteByRule(&$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Scan all the files
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read each entry
$v_header_list = array();
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
$v_header_list[$v_nb_extracted] = array();
if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
return $v_result;
}
// ----- Store the index
$v_header_list[$v_nb_extracted]['index'] = $i;
// ----- Look for the specific extract rules
$v_found = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) {
// ----- Look for a directory
if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
// ----- Look if the directory is in the filename path
if ( (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
$v_found = true;
}
elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */
&& ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
$v_found = true;
}
}
// ----- Look for a filename
elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
$v_found = true;
}
}
}
// ----- Look for extract by ereg rule
// ereg() is deprecated with PHP 5.3
/*
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
$v_found = true;
}
}
*/
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
$v_found = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) {
if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
$v_found = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
break;
}
}
}
else {
$v_found = true;
}
// ----- Look for deletion
if ($v_found)
{
unset($v_header_list[$v_nb_extracted]);
}
else
{
$v_nb_extracted++;
}
}
// ----- Look if something need to be deleted
if ($v_nb_extracted > 0) {
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Creates a temporary zip archive
$v_temp_zip = new PclZip($v_zip_temp_name);
// ----- Open the temporary zip file in write mode
if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Look which file need to be kept
for ($i=0; $i<sizeof($v_header_list); $i++) {
// ----- Calculate the position of the header
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the file header
$v_local_header = array();
if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Check that local file header is same as central file header
if ($this->privCheckFileHeaders($v_local_header,
$v_header_list[$i]) != 1) {
// TBC
}
unset($v_local_header);
// ----- Write the file header
if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Read/write the data block
if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_temp_zip->zip_fd);
// ----- Re-Create the Central Dir files header
for ($i=0; $i<sizeof($v_header_list); $i++) {
// ----- Create the file header
if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Transform the header to a 'usable' info
$v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
// ----- Reset the file list
unset($v_header_list);
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Close
$v_temp_zip->privCloseFd();
$this->privCloseFd();
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Destroy the temporary archive
unset($v_temp_zip);
}
// ----- Remove every files : reset the file
else if ($v_central_dir['entries'] != 0) {
$this->privCloseFd();
if (($v_result = $this->privOpenFd('wb')) != 1) {
return $v_result;
}
if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
return $v_result;
}
$this->privCloseFd();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check.
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function privDirCheck($p_dir, $p_is_dir=false)
{
$v_result = 1;
// ----- Remove the final '/'
if (($p_is_dir) && (substr($p_dir, -1)=='/'))
{
$p_dir = substr($p_dir, 0, strlen($p_dir)-1);
}
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == ""))
{
return 1;
}
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
// ----- Just a check
if ($p_parent_dir != $p_dir)
{
// ----- Look for parent directory
if ($p_parent_dir != "")
{
if (($v_result = $this->privDirCheck($p_parent_dir)) != 1)
{
return $v_result;
}
}
}
// ----- Create the directory
if (!@mkdir($p_dir, 0777))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
// ----- Return
return PclZip::errorCode();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privMerge()
// Description :
// If $p_archive_to_add does not exist, the function exit with a success result.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privMerge(&$p_archive_to_add)
{
$v_result=1;
// ----- Look if the archive_to_add exists
if (!is_file($p_archive_to_add->zipname))
{
// ----- Nothing to merge, so merge is a success
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Look if the archive exists
if (!is_file($this->zipname))
{
// ----- Do a duplicate
$v_result = $this->privDuplicate($p_archive_to_add->zipname);
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Open the archive_to_add file
if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1)
{
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir_to_add = array();
if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($p_archive_to_add->zip_fd);
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the files from the archive_to_add into the temporary file
$v_size = $v_central_dir_to_add['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_zip_temp_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the block of file headers from the archive_to_add
$v_size = $v_central_dir_to_add['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Merge the file comments
$v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
// ----- Calculate the size of the (new) central header
$v_size = @ftell($v_zip_temp_fd)-$v_offset;
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive fd
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
@fclose($v_zip_temp_fd);
$this->zip_fd = null;
// ----- Reset the file list
unset($v_header_list);
// ----- Return
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDuplicate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDuplicate($p_archive_filename)
{
$v_result=1;
// ----- Look if the $p_archive_filename exists
if (!is_file($p_archive_filename))
{
// ----- Nothing to duplicate, so duplicate is a success.
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result=$this->privOpenFd('wb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0)
{
$this->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = filesize($p_archive_filename);
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorLog($p_error_code=0, $p_error_string='')
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclError($p_error_code, $p_error_string);
}
else {
$this->error_code = $p_error_code;
$this->error_string = $p_error_string;
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorReset()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclErrorReset();
}
else {
$this->error_code = 0;
$this->error_string = '';
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDisableMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDisableMagicQuotes()
{
$v_result=1;
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
}
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
return $v_result;
}
// ----- Get and memorize the magic_quote value
$this->magic_quotes_status = @get_magic_quotes_runtime();
// ----- Disable magic_quotes
if ($this->magic_quotes_status == 1) {
@set_magic_quotes_runtime(0);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privSwapBackMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privSwapBackMagicQuotes()
{
$v_result=1;
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
}
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
return $v_result;
}
// ----- Swap back magic_quotes
if ($this->magic_quotes_status == 1) {
@set_magic_quotes_runtime($this->magic_quotes_status);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
}
// End of class
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathReduction()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclZipUtilPathReduction($p_dir)
{
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "") {
// ----- Explode path by directory names
$v_list = explode("/", $p_dir);
// ----- Study directories from last to first
$v_skip = 0;
for ($i=sizeof($v_list)-1; $i>=0; $i--) {
// ----- Look for current path
if ($v_list[$i] == ".") {
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
$v_skip++;
}
else if ($v_list[$i] == "") {
// ----- First '/' i.e. root slash
if ($i == 0) {
$v_result = "/".$v_result;
if ($v_skip > 0) {
// ----- It is an invalid path, so the path is not modified
// TBC
$v_result = $p_dir;
$v_skip = 0;
}
}
// ----- Last '/' i.e. indicates a directory
else if ($i == (sizeof($v_list)-1)) {
$v_result = $v_list[$i];
}
// ----- Double '/' inside the path
else {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
}
}
else {
// ----- Look for item to skip
if ($v_skip > 0) {
$v_skip--;
}
else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
}
}
}
// ----- Look for skip
if ($v_skip > 0) {
while ($v_skip > 0) {
$v_result = '../'.$v_result;
$v_skip--;
}
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathInclusion()
// Description :
// This function indicates if the path $p_path is under the $p_dir tree. Or,
// said in an other way, if the file or sub-dir $p_path is inside the dir
// $p_dir.
// The function indicates also if the path is exactly the same as the dir.
// This function supports path with duplicated '/' like '//', but does not
// support '.' or '..' statements.
// Parameters :
// Return Values :
// 0 if $p_path is not inside directory $p_dir
// 1 if $p_path is inside directory $p_dir
// 2 if $p_path is exactly the same as $p_dir
// --------------------------------------------------------------------------------
function PclZipUtilPathInclusion($p_dir, $p_path)
{
$v_result = 1;
// ----- Look for path beginning by ./
if ( ($p_dir == '.')
|| ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
$p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1);
}
if ( ($p_path == '.')
|| ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
$p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1);
}
// ----- Explode dir and path by directory separator
$v_list_dir = explode("/", $p_dir);
$v_list_dir_size = sizeof($v_list_dir);
$v_list_path = explode("/", $p_path);
$v_list_path_size = sizeof($v_list_path);
// ----- Study directories paths
$i = 0;
$j = 0;
while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
// ----- Look for empty dir (path reduction)
if ($v_list_dir[$i] == '') {
$i++;
continue;
}
if ($v_list_path[$j] == '') {
$j++;
continue;
}
// ----- Compare the items
if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
$v_result = 0;
}
// ----- Next items
$i++;
$j++;
}
// ----- Look if everything seems to be the same
if ($v_result) {
// ----- Skip all the empty items
while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++;
while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++;
if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
// ----- There are exactly the same
$v_result = 2;
}
else if ($i < $v_list_dir_size) {
// ----- The path is shorter than the dir
$v_result = 0;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilCopyBlock()
// Description :
// Parameters :
// $p_mode : read/write compression mode
// 0 : src & dest normal
// 1 : src gzip, dest normal
// 2 : src normal, dest gzip
// 3 : src & dest gzip
// Return Values :
// --------------------------------------------------------------------------------
function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0)
{
$v_result = 1;
if ($p_mode==0)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==1)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==2)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==3)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilRename()
// Description :
// This function tries to do a simple rename() function. If it fails, it
// tries to copy the $p_src file in a new $p_dest file and then unlink the
// first one.
// Parameters :
// $p_src : Old filename
// $p_dest : New filename
// Return Values :
// 1 on success, 0 on failure.
// --------------------------------------------------------------------------------
function PclZipUtilRename($p_src, $p_dest)
{
$v_result = 1;
// ----- Try to rename the files
if (!@rename($p_src, $p_dest)) {
// ----- Try to copy & unlink the src
if (!@copy($p_src, $p_dest)) {
$v_result = 0;
}
else if (!@unlink($p_src)) {
$v_result = 0;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilOptionText()
// Description :
// Translate option value in text. Mainly for debug purpose.
// Parameters :
// $p_option : the option value.
// Return Values :
// The option text value.
// --------------------------------------------------------------------------------
function PclZipUtilOptionText($p_option)
{
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
$v_prefix = substr($v_key, 0, 10);
if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
&& ($v_list[$v_key] == $p_option)) {
return $v_key;
}
}
$v_result = 'Unknown';
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilTranslateWinPath()
// Description :
// Translate windows path by replacing '\' by '/' and optionally removing
// drive letter.
// Parameters :
// $p_path : path to translate.
// $p_remove_disk_letter : true | false
// Return Values :
// The path translated.
// --------------------------------------------------------------------------------
function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
{
if (stristr(php_uname(), 'windows')) {
// ----- Look for potential disk letter
if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
return $p_path;
}
// --------------------------------------------------------------------------------
?>
| mit |
jorik041/Terraformer | dist/node/Parsers/WKT/node_modules/jison/node_modules/nomnom/test/noopts.js | 390 | var nomnom = require("../nomnom"),
assert = require("assert");
var options = nomnom().parseArgs(["-d", "file.js", "--atomic=true", "addon.xpi"]);
var url = options[0]; // get the first positional arg
var debug = options.debug; // see if --debug was specified
assert.ok(options.d);
assert.equal(options[0], "file.js");
assert.ok(options.atomic);
assert.equal(options[1], "addon.xpi"); | mit |
grgr/pageflow | lib/generators/pageflow/assets/templates/editor.js | 80 | //= require i18n
//= require i18n/translations
//= require pageflow/editor/base | mit |
mikeymckay/formtastic.us | vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/new_erb_spec.rb | 1032 | require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper'
describe "/<%= table_name %>/new.<%= default_file_extension %>" do
include <%= controller_class_name %>Helper
before do
@<%= file_name %> = mock_model(<%= class_name %>)
@<%= file_name %>.stub!(:new_record?).and_return(true)
<% for attribute in attributes -%>
@<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
<% end -%>
assigns[:<%= file_name %>] = @<%= file_name %>
end
it "should render new form" do
render "/<%= table_name %>/new.<%= default_file_extension %>"
response.should have_tag("form[action=?][method=post]", <%= table_name %>_path) do
<% for attribute in attributes -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
with_tag("<%= attribute.input_type -%>#<%= file_name %>_<%= attribute.name %>[name=?]", "<%= file_name %>[<%= attribute.name %>]")
<% end -%><% end -%>
end
end
end
| mit |
cdnjs/cdnjs | ajax/libs/dojo/1.16.3/cldr/nls/en/currency.min.js | 321 | define({HKD_displayName:"Hong Kong Dollar",CHF_displayName:"Swiss Franc",JPY_symbol:"¥",CAD_displayName:"Canadian Dollar",CNY_displayName:"Chinese Yuan",USD_symbol:"$",AUD_displayName:"Australian Dollar",JPY_displayName:"Japanese Yen",USD_displayName:"US Dollar",GBP_displayName:"British Pound",EUR_displayName:"Euro"}); | mit |
unscriptable/e4e-2013-es6 | app/slides/tx/markdown.js | 228 | /* @license Copyright (c) 2011-2013 Brian Cavalier */
define(['marked'], function(marked) {
return function(options) {
return function(markdownText) {
marked.setOptions(options);
return marked(markdownText);
};
};
}) | mit |
CaoPhiHung/CRM | vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php | 1943 | <?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\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
/**
* Merges extension configs into the container builder
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class MergeExtensionConfigurationPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
$parameters = $container->getParameterBag()->all();
$definitions = $container->getDefinitions();
$aliases = $container->getAliases();
foreach ($container->getExtensions() as $extension) {
if ($extension instanceof PrependExtensionInterface) {
$extension->prepend($container);
}
}
foreach ($container->getExtensions() as $name => $extension) {
if (!$config = $container->getExtensionConfig($name)) {
// this extension was not called
continue;
}
$config = $container->getParameterBag()->resolveValue($config);
$tmpContainer = new ContainerBuilder($container->getParameterBag());
$tmpContainer->setResourceTracking($container->isTrackingResources());
$tmpContainer->addObjectResource($extension);
$extension->load($config, $tmpContainer);
$container->merge($tmpContainer);
}
$container->addDefinitions($definitions);
$container->addAliases($aliases);
$container->getParameterBag()->add($parameters);
}
}
| mit |
SonarSystems/Cocos-Helper | External Cocos Helper Android Frameworks/Libs/facebook-android-sdk-3.23.0/facebook-android-sdk-3.23.0/AudienceNetwork/samples/AdUnitsSample/src/com/facebook/samples/AdUnitsSample/AdUnitsSampleActivity.java | 3345 | /**
* Copyright 2014 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web and mobile services and APIs
* provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright 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.
*
*/
package com.facebook.samples.AdUnitsSample;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class AdUnitsSampleActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsViewPagerAdapter tabsViewPagerAdapter;
private ActionBar actionBar;
private String[] tabNames = { "Banner", "Rectangle", "Interstitial" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ad_sample);
viewPager = (ViewPager) findViewById(R.id.viewPager);
actionBar = getActionBar();
tabsViewPagerAdapter = new TabsViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsViewPagerAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tabName : tabNames) {
actionBar.addTab(actionBar.newTab().setText(tabName).setTabListener(this));
}
// When testing on a device, add its hashed ID to force test ads.
// The hash ID is printed to log cat when running on a device and loading an ad.
// AdSettings.addTestDevice("THE HASHED ID AS PRINTED TO LOG CAT");
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
| mit |
DixonD-git/cake | src/Cake.Common/Tools/InspectCode/InspectCodeSettings.cs | 4288 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Cake.Core.IO;
using Cake.Core.Tooling;
namespace Cake.Common.Tools.InspectCode
{
/// <summary>
/// Contains settings used by <see cref="InspectCodeRunner" />.
/// </summary>
public sealed class InspectCodeSettings : ToolSettings
{
/*
Not (yet) supported options:
- /toolset MsBuild toolset version. Highest available is used by default. Example: /toolset=12.0.
- /dumpIssuesTypes (/it) Dump issues types (default: False).
- /targets-for-references MSBuild targets. These targets will be executed to get referenced assemblies of projects..
- /targets-for-items MSBuild targets. These targets will be executed to get other items (e.g. Compile item) of projects..
*/
/// <summary>
/// Gets or sets the location InspectCode should write its output.
/// </summary>
/// <value>The location that InspectCode should write its output</value>
public FilePath OutputFile { get; set; }
/// <summary>
/// Gets or sets a value indicating whether enable solution-wide analysis should be forced.
/// Default value is <c>false</c>.
/// </summary>
/// <value>
/// <c>true</c> if solution-wide analysis should be enabled by force; otherwise, <c>fault</c>.
/// </value>
public bool SolutionWideAnalysis { get; set; }
/// <summary>
/// Gets or sets a value indicating whether disable solution-wide analysis should be forced.
/// Default value is <c>false</c>
/// </summary>
/// <value>
/// <c>true</c> if solution-wide analysis should be disabled by force; otherwise, <c>fault</c>.
/// </value>
public bool NoSolutionWideAnalysis { get; set; }
/// <summary>
/// Gets or sets a filter to analyze only particular project(s) instead of the whole solution.
/// Supports wildcards.
/// </summary>
/// <value>The filter to analyze only particular projects(s).</value>
public string ProjectFilter { get; set; }
/// <summary>
/// Gets or sets MSBuild properties.
/// </summary>
/// <value>The MSBuild properties to override</value>
public Dictionary<string, string> MsBuildProperties { get; set; }
/// <summary>
/// Gets or sets a list of Resharper extensions which will be used.
/// </summary>
public string[] Extensions { get; set; }
/// <summary>
/// Gets or sets the directory where caches will be stored.
/// The default is %TEMP%.
/// </summary>
/// <value>The directory where caches will be stored.</value>
public DirectoryPath CachesHome { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the debug output should be enabled.
/// </summary>
/// <value>
/// <c>true</c> if the debug output should be enabled; otherwise, <c>false</c>.
/// </value>
public bool Debug { get; set; }
/// <summary>
/// Gets or sets a value indicating whether all global, solution and project settings should be ignored.
/// Alias for disabling the settings layers GlobalAll, GlobalPerProduct, SolutionShared, SolutionPersonal, ProjectShared and ProjectPersonal.
/// </summary>
public bool NoBuildinSettings { get; set; }
/// <summary>
/// Gets or sets a list of <c>InspectCodeSettings</c> which will be disabled.
/// </summary>
public SettingsLayer[] DisabledSettingsLayers { get; set; }
/// <summary>
/// Gets or sets the path to the file to use custom settings from.
/// </summary>
public FilePath Profile { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to throw an exception on finding violations
/// </summary>
public bool ThrowExceptionOnFindingViolations { get; set; }
}
} | mit |
Milstein/controllerODP | opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java | 1362 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.northbound.commons.exception;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
/**
* Status Code 404 (Not Found)
*
* The server has not found anything matching the Request-URI.
* No indication is given of whether the condition is temporary or permanent.
* The 410 (Gone) status code SHOULD be used if the server knows,
* through some internally configurable mechanism, that an old resource
* is permanently unavailable and has no forwarding address.
* This status code is commonly used when the server does not wish to
* reveal exactly why the request has been refused, or when no other
* response is applicable.
*
*
*
*/
public class ResourceNotFoundException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String string) {
super(Response.status(Response.Status.NOT_FOUND).entity(string).type(
MediaType.TEXT_PLAIN).build());
}
}
| epl-1.0 |
yodaaut/icingaweb2 | modules/monitoring/library/Monitoring/Command/IcingaCommand.php | 473 | <?php
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */
namespace Icinga\Module\Monitoring\Command;
/**
* Base class for commands sent to an Icinga instance
*/
abstract class IcingaCommand
{
/**
* Get the name of the command
*
* @return string
*/
public function getName()
{
$nsParts = explode('\\', get_called_class());
return substr_replace(end($nsParts), '', -7); // Remove 'Command' Suffix
}
}
| gpl-2.0 |
davilamr/collaborativeEditor | dojo/public/ace_src_noconflict/mode-scss.js | 37180 | ace.define("ace/mode/scss_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var ScssHighlightRules = function() {
var properties = lang.arrayToMap( (function () {
var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|");
var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" +
"background-size|binding|border-bottom-colors|border-left-colors|" +
"border-right-colors|border-top-colors|border-end|border-end-color|" +
"border-end-style|border-end-width|border-image|border-start|" +
"border-start-color|border-start-style|border-start-width|box-align|" +
"box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" +
"box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" +
"column-rule-width|column-rule-style|column-rule-color|float-edge|" +
"font-feature-settings|font-language-override|force-broken-image-icon|" +
"image-region|margin-end|margin-start|opacity|outline|outline-color|" +
"outline-offset|outline-radius|outline-radius-bottomleft|" +
"outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" +
"outline-style|outline-width|padding-end|padding-start|stack-sizing|" +
"tab-size|text-blink|text-decoration-color|text-decoration-line|" +
"text-decoration-style|transform|transform-origin|transition|" +
"transition-delay|transition-duration|transition-property|" +
"transition-timing-function|user-focus|user-input|user-modify|user-select|" +
"window-shadow|border-radius").split("|");
var properties = ("azimuth|background-attachment|background-color|background-image|" +
"background-position|background-repeat|background|border-bottom-color|" +
"border-bottom-style|border-bottom-width|border-bottom|border-collapse|" +
"border-color|border-left-color|border-left-style|border-left-width|" +
"border-left|border-right-color|border-right-style|border-right-width|" +
"border-right|border-spacing|border-style|border-top-color|" +
"border-top-style|border-top-width|border-top|border-width|border|bottom|" +
"box-shadow|box-sizing|caption-side|clear|clip|color|content|counter-increment|" +
"counter-reset|cue-after|cue-before|cue|cursor|direction|display|" +
"elevation|empty-cells|float|font-family|font-size-adjust|font-size|" +
"font-stretch|font-style|font-variant|font-weight|font|height|left|" +
"letter-spacing|line-height|list-style-image|list-style-position|" +
"list-style-type|list-style|margin-bottom|margin-left|margin-right|" +
"margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" +
"min-width|opacity|orphans|outline-color|" +
"outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" +
"padding-left|padding-right|padding-top|padding|page-break-after|" +
"page-break-before|page-break-inside|page|pause-after|pause-before|" +
"pause|pitch-range|pitch|play-during|position|quotes|richness|right|" +
"size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" +
"stress|table-layout|text-align|text-decoration|text-indent|" +
"text-shadow|text-transform|top|unicode-bidi|vertical-align|" +
"visibility|voice-family|volume|white-space|widows|width|word-spacing|" +
"z-index").split("|");
var ret = [];
for (var i=0, ln=browserPrefix.length; i<ln; i++) {
Array.prototype.push.apply(
ret,
(( browserPrefix[i] + prefixProperties.join("|" + browserPrefix[i]) ).split("|"))
);
}
Array.prototype.push.apply(ret, prefixProperties);
Array.prototype.push.apply(ret, properties);
return ret;
})() );
var functions = lang.arrayToMap(
("hsl|hsla|rgb|rgba|url|attr|counter|counters|abs|adjust_color|adjust_hue|" +
"alpha|join|blue|ceil|change_color|comparable|complement|darken|desaturate|" +
"floor|grayscale|green|hue|if|invert|join|length|lighten|lightness|mix|" +
"nth|opacify|opacity|percentage|quote|red|round|saturate|saturation|" +
"scale_color|transparentize|type_of|unit|unitless|unqoute").split("|")
);
var constants = lang.arrayToMap(
("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" +
"block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" +
"char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" +
"decimal-leading-zero|decimal|default|disabled|disc|" +
"distribute-all-lines|distribute-letter|distribute-space|" +
"distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" +
"hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" +
"ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" +
"ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" +
"inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" +
"keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" +
"lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" +
"medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" +
"nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" +
"overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" +
"ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" +
"solid|square|static|strict|super|sw-resize|table-footer-group|" +
"table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" +
"transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" +
"vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" +
"zero").split("|")
);
var colors = lang.arrayToMap(
("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" +
"purple|red|silver|teal|white|yellow").split("|")
);
var keywords = lang.arrayToMap(
("@mixin|@extend|@include|@import|@media|@debug|@warn|@if|@for|@each|@while|@else|@font-face|@-webkit-keyframes|if|and|!default|module|def|end|declare").split("|")
)
var tags = lang.arrayToMap(
("a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdo|" +
"big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" +
"command|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|" +
"figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|" +
"header|hgroup|hr|html|i|iframe|img|input|ins|keygen|kbd|label|legend|li|" +
"link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|" +
"option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|" +
"small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|" +
"textarea|tfoot|th|thead|time|title|tr|tt|u|ul|var|video|wbr|xmp").split("|")
);
var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
this.$rules = {
"start" : [
{
token : "comment",
regex : "\\/\\/.*$"
},
{
token : "comment", // multi line comment
regex : "\\/\\*",
next : "comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // multi line string start
regex : '["].*\\\\$',
next : "qqstring"
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "string", // multi line string start
regex : "['].*\\\\$",
next : "qstring"
}, {
token : "constant.numeric",
regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)"
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : "constant.numeric",
regex : numRe
}, {
token : ["support.function", "string", "support.function"],
regex : "(url\\()(.*)(\\))"
}, {
token : function(value) {
if (properties.hasOwnProperty(value.toLowerCase()))
return "support.type";
if (keywords.hasOwnProperty(value))
return "keyword";
else if (constants.hasOwnProperty(value))
return "constant.language";
else if (functions.hasOwnProperty(value))
return "support.function";
else if (colors.hasOwnProperty(value.toLowerCase()))
return "support.constant.color";
else if (tags.hasOwnProperty(value.toLowerCase()))
return "variable.language";
else
return "text";
},
regex : "\\-?[@a-z_][@a-z0-9_\\-]*"
}, {
token : "variable",
regex : "[a-z_\\-$][a-z0-9_\\-$]*\\b"
}, {
token: "variable.language",
regex: "#[a-z0-9-_]+"
}, {
token: "variable.language",
regex: "\\.[a-z0-9-_]+"
}, {
token: "variable.language",
regex: ":[a-z0-9-_]+"
}, {
token: "constant",
regex: "[a-z0-9-_]+"
}, {
token : "keyword.operator",
regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}, {
caseInsensitive: true
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
],
"qqstring" : [
{
token : "string",
regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
next : "start"
}, {
token : "string",
regex : '.+'
}
],
"qstring" : [
{
token : "string",
regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
next : "start"
}, {
token : "string",
regex : '.+'
}
]
};
};
oop.inherits(ScssHighlightRules, TextHighlightRules);
exports.ScssHighlightRules = ScssHighlightRules;
});
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {};
var initContext = function(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.index;
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
contextCache = {rangeCount: editor.multiSelect.rangeCount};
}
if (contextCache[id])
return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var CstyleBehaviour = function() {
this.add("braces", "insertion", function(state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
if (!openBracePos)
return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function(state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function(state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
if (text == '"' || text == "'") {
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else if (!selected) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var token = session.getTokenAt(cursor.row, cursor.column);
var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
if (leftChar == "\\" && token && /escape/.test(token.type))
return null;
var stringBefore = token && /string/.test(token.type);
var stringAfter = !rightToken || /string/.test(rightToken.type);
var pair;
if (rightChar == quote) {
pair = stringBefore !== stringAfter;
} else {
if (stringBefore && !stringAfter)
return null; // wrap string with different quote
if (stringBefore && stringAfter)
return null; // do not pair quotes inside strings
var wordRe = session.$mode.tokenRe;
wordRe.lastIndex = 0;
var isWordBefore = wordRe.test(leftChar);
wordRe.lastIndex = 0;
var isWordAfter = wordRe.test(leftChar);
if (isWordBefore || isWordAfter)
return null; // before or after alphanumeric
if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
return null; // there is rightChar and it isn't closing
pair = true;
}
return {
text: pair ? quote + quote : "",
selection: [1,1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return context.autoInsertedBrackets > 0 &&
cursor.row === context.autoInsertedRow &&
bracket === context.autoInsertedLineEnd[0] &&
line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return context.maybeInsertedBrackets > 0 &&
cursor.row === context.maybeInsertedRow &&
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var CssBehaviour = function () {
this.inherit(CstyleBehaviour);
this.add("colon", "insertion", function (state, action, editor, session, text) {
if (text === ':') {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === 'support.type') {
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ':') {
return {
text: '',
selection: [1, 1]
}
}
if (!line.substring(cursor.column).match(/^\s*;/)) {
return {
text: ':;',
selection: [1, 1]
}
}
}
}
});
this.add("colon", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected === ':') {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === 'support.type') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar === ';') {
range.end.column ++;
return range;
}
}
}
});
this.add("semicolon", "insertion", function (state, action, editor, session, text) {
if (text === ';') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ';') {
return {
text: '',
selection: [1, 1]
}
}
}
});
}
oop.inherits(CssBehaviour, CstyleBehaviour);
exports.CssBehaviour = CssBehaviour;
});
ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*(\/\*|\/\/)#region\b/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.singleLineBlockCommentRe.test(line)) {
if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line))
return "start"; // lineCommentRegionStart
return fw;
};
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
this.getCommentRegionBlock = function(session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*(?:\/\*|\/\/)#(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/scss",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/scss_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var ScssHighlightRules = require("./scss_highlight_rules").ScssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CssBehaviour = require("./behaviour/css").CssBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = ScssHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CssBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokens = this.getTokenizer().getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.$id = "ace/mode/scss";
}).call(Mode.prototype);
exports.Mode = Mode;
});
| gpl-2.0 |
YouDiSN/OpenJDK-Research | jdk9/jdk/test/tools/jmod/src/apa/jdk/test/apa/Apa.java | 1252 | /*
* Copyright (c) 2016, 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 jdk.test.apa;
public class Apa { }
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/nio/channels/DatagramChannel/SendExceptions.java | 3214 | /*
* Copyright (c) 2018, 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.
*
* 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.
*/
/* @test
* @bug 4675045 8198753
* @summary Test DatagramChannel send exceptions
* @library ..
* @run testng SendExceptions
*/
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class SendExceptions {
static DatagramChannel sndChannel;
static DatagramChannel rcvChannel;
static InetSocketAddress sender;
static InetSocketAddress receiver;
static ByteBuffer buf = ByteBuffer.allocate(17);
@BeforeTest
public static void setup() throws Exception {
sndChannel = DatagramChannel.open();
sndChannel.bind(null);
InetAddress address = InetAddress.getLocalHost();
if (address.isLoopbackAddress()) {
address = InetAddress.getLoopbackAddress();
}
sender = new InetSocketAddress(address,
sndChannel.socket().getLocalPort());
rcvChannel = DatagramChannel.open();
rcvChannel.bind(null);
receiver = new InetSocketAddress(address,
rcvChannel.socket().getLocalPort());
}
@Test(expectedExceptions = UnsupportedAddressTypeException.class)
public static void unsupportedAddressTypeException() throws Exception {
rcvChannel.connect(sender);
sndChannel.send(buf, new SocketAddress() {});
}
@Test(expectedExceptions = UnresolvedAddressException.class)
public static void unresolvedAddressException() throws Exception {
String host = TestUtil.UNRESOLVABLE_HOST;
InetSocketAddress unresolvable = new InetSocketAddress (host, 37);
sndChannel.send(buf, unresolvable);
}
@Test(expectedExceptions = AlreadyConnectedException.class)
public static void alreadyConnectedException() throws Exception {
sndChannel.connect(receiver);
InetSocketAddress random = new InetSocketAddress(0);
sndChannel.send(buf, random);
}
@AfterTest
public static void cleanup() throws Exception {
rcvChannel.close();
sndChannel.close();
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/share/jpda/AbstractDebuggeeTest.java | 13554 | /*
* Copyright (c) 2006, 2018, 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.
*
* 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.
*/
// THIS TEST IS LINE NUMBER SENSITIVE
package nsk.share.jpda;
import java.io.*;
import java.util.*;
import nsk.share.*;
import nsk.share.test.*;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
/*
* Class can be used as base debuggee class in jdi and jdwp tests.
* Class contains common method for initializing log, pipe, vm, and several common auxiliary methods. Subclass should implement parseCommand() and, if needed, doInit(parse command line parameters)
* !!! Edit carefully, value of 'DEFAULT_BREAKPOINT_LINE' is hardcoded !!!
*/
public class AbstractDebuggeeTest {
protected DebugeeArgumentHandler argHandler;
protected IOPipe pipe;
protected Log log;
protected boolean callExit = true;
private boolean success = true;
protected void setSuccess(boolean value) {
success = value;
}
public boolean getSuccess() {
return success;
}
public final static int DEFAULT_BREAKPOINT_LINE = 63;
public final static String DEFAULT_BREAKPOINT_METHOD_NAME = "breakpointMethod";
public void breakpointMethod() {
log.display("In breakpoint method: 'AbstractDebuggeeTest.breakpointMethod()'"); // DEFAULT_BREAKPOINT_LINE
}
protected Map<String, ClassUnloader> loadedClasses = new TreeMap<String, ClassUnloader>();
public final static String COMMAND_FORCE_BREAKPOINT = "forceBreakpoint";
//load class with given name with possibility to unload it
static public final String COMMAND_LOAD_CLASS = "loadClass";
// unload class with given name(it is possible for classes loaded via loadTestClass method)
// command:className[:<unloadResult>], <unloadResult> - one of UNLOAD_RESULT_TRUE or UNLOAD_RESULT_FALSE
static public final String COMMAND_UNLOAD_CLASS = "unloadClass";
// Optional arguments of COMMAND_UNLOAD_CLASS
// (is after unloading class should be really unloaded, default value is UNLOAD_RESULT_TRUE)
static public final String UNLOAD_RESULT_TRUE = "unloadResultTrue";
static public final String UNLOAD_RESULT_FALSE = "unloadResultFalse";
static public final String COMMAND_CREATE_STATETESTTHREAD = "createStateTestThread";
static public final String COMMAND_NEXTSTATE_STATETESTTHREAD = "stateTestThreadNextState";
//force GC using AbstractDebuggeeTest.eatMemory()
static public final String COMMAND_FORCE_GC = "forceGC";
// GCcount is used to get information about GC activity during test
static public final String COMMAND_GC_COUNT = "GCcount";
private int lastGCCount;
static public final String stateTestThreadName = "stateTestThread";
static public final String stateTestThreadClassName = StateTestThread.class.getName();
// path to classes intended for loading/unloading
protected String classpath;
// classloader loads only test classes from nsk.*
public static class TestClassLoader extends CustomClassLoader {
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("nsk."))
return findClass(name);
else
return super.loadClass(name);
}
}
protected StressOptions stressOptions;
protected Stresser stresser;
// initialize test and remove unsupported by nsk.share.jdi.ArgumentHandler arguments
// (ArgumentHandler constructor throws BadOption exception if command line contains unrecognized by ArgumentHandler options)
// support -testClassPath parameter: path to find classes for custom classloader
protected String[] doInit(String[] args) {
stressOptions = new StressOptions(args);
stresser = new Stresser(stressOptions);
ArrayList<String> standardArgs = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-testClassPath") && (i < args.length - 1)) {
classpath = args[i + 1];
i++;
} else
standardArgs.add(args[i]);
}
return standardArgs.toArray(new String[] {});
}
public void loadTestClass(String className) {
if (classpath == null) {
throw new TestBug("Debuggee requires 'testClassPath' parameter");
}
try {
ClassUnloader classUnloader = new ClassUnloader();
classUnloader.setClassLoader(new TestClassLoader());
classUnloader.loadClass(className, classpath);
loadedClasses.put(className, classUnloader);
} catch (ClassNotFoundException e) {
log.complain("Unexpected 'ClassNotFoundException' on loading of the requested class(" + className + ")");
e.printStackTrace(log.getOutStream());
throw new TestBug("Unexpected 'ClassNotFoundException' on loading of the requested class(" + className + ")");
}
}
public static final int MAX_UNLOAD_ATTEMPS = 5;
public void unloadTestClass(String className, boolean expectedUnloadingResult) {
ClassUnloader classUnloader = loadedClasses.get(className);
int unloadAttemps = 0;
if (classUnloader != null) {
boolean wasUnloaded = false;
while (!wasUnloaded && (unloadAttemps++ < MAX_UNLOAD_ATTEMPS)) {
wasUnloaded = classUnloader.unloadClass();
}
if (wasUnloaded)
loadedClasses.remove(className);
else {
log.display("Class " + className + " was not unloaded");
}
if (wasUnloaded != expectedUnloadingResult) {
setSuccess(false);
if (wasUnloaded)
log.complain("Class " + className + " was unloaded!");
else
log.complain("Class " + className + " wasn't unloaded!");
}
} else {
log.complain("Invalid command 'unloadClass' is requested: class " + className + " was not loaded via ClassUnloader");
throw new TestBug("Invalid command 'unloadClass' is requested: class " + className + " was not loaded via ClassUnloader");
}
}
static public void sleep1sec() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
private StateTestThread stateTestThread;
public static final String COMMAND_QUIT = "quit";
public static final String COMMAND_READY = "ready";
private void createStateTestThread() {
if (stateTestThread != null)
throw new TestBug("StateTestThread already created");
stateTestThread = new StateTestThread(stateTestThreadName);
}
private void stateTestThreadNextState() {
if (stateTestThread == null)
throw new TestBug("StateTestThread not created");
stateTestThread.nextState();
}
public boolean parseCommand(String command) {
try {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(command));
tokenizer.whitespaceChars(':', ':');
tokenizer.wordChars('_', '_');
tokenizer.wordChars('$', '$');
tokenizer.wordChars('[', ']');
if (command.equals(COMMAND_FORCE_GC)) {
forceGC();
lastGCCount = getCurrentGCCount();
return true;
} else if (command.equals(COMMAND_GC_COUNT)) {
pipe.println(COMMAND_GC_COUNT + ":" + (getCurrentGCCount() - lastGCCount));
return true;
} else if (command.equals(COMMAND_FORCE_BREAKPOINT)) {
breakpointMethod();
return true;
} else if (command.equals(COMMAND_CREATE_STATETESTTHREAD)) {
createStateTestThread();
return true;
} else if (command.equals(COMMAND_NEXTSTATE_STATETESTTHREAD)) {
stateTestThreadNextState();
return true;
} else if (command.startsWith(COMMAND_LOAD_CLASS)) {
tokenizer.nextToken();
if (tokenizer.nextToken() != StreamTokenizer.TT_WORD)
throw new TestBug("Invalid command format: " + command);
String className = tokenizer.sval;
loadTestClass(className);
return true;
} else if (command.startsWith(COMMAND_UNLOAD_CLASS)) {
tokenizer.nextToken();
if (tokenizer.nextToken() != StreamTokenizer.TT_WORD)
throw new TestBug("Invalid command format: " + command);
String className = tokenizer.sval;
boolean expectedUnloadingResult = true;
if (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
if (tokenizer.sval.equals(UNLOAD_RESULT_TRUE))
expectedUnloadingResult = true;
else if (tokenizer.sval.equals(UNLOAD_RESULT_FALSE))
expectedUnloadingResult = false;
else
throw new TestBug("Invalid command format: " + command);
}
unloadTestClass(className, expectedUnloadingResult);
return true;
}
} catch (IOException e) {
throw new TestBug("Invalid command format: " + command);
}
return false;
}
protected DebugeeArgumentHandler createArgumentHandler(String args[]) {
return new DebugeeArgumentHandler(args);
}
protected void init(String args[]) {
argHandler = createArgumentHandler(doInit(args));
pipe = argHandler.createDebugeeIOPipe();
log = argHandler.createDebugeeLog();
lastGCCount = getCurrentGCCount();
}
public void initDebuggee(DebugeeArgumentHandler argHandler, Log log, IOPipe pipe, String[] args, boolean callExit) {
this.argHandler = argHandler;
this.log = log;
this.pipe = pipe;
this.callExit = callExit;
doInit(args);
}
public void doTest(String args[]) {
init(args);
doTest();
}
public void doTest() {
do {
log.display("Debuggee " + getClass().getName() + " : sending the command: " + AbstractDebuggeeTest.COMMAND_READY);
pipe.println(AbstractDebuggeeTest.COMMAND_READY);
String command = pipe.readln();
log.display("Debuggee: received the command: " + command);
if (command.equals(AbstractDebuggeeTest.COMMAND_QUIT)) {
break;
} else {
try {
if (!parseCommand(command)) {
log.complain("TEST BUG: unknown debugger command: " + command);
System.exit(Consts.JCK_STATUS_BASE + Consts.TEST_FAILED);
}
} catch (Throwable t) {
log.complain("Unexpected exception in debuggee: " + t);
t.printStackTrace(log.getOutStream());
System.exit(Consts.JCK_STATUS_BASE + Consts.TEST_FAILED);
}
}
} while (true);
log.display("Debuggee: exiting");
if (callExit) {
if (success)
System.exit(Consts.JCK_STATUS_BASE + Consts.TEST_PASSED);
else
System.exit(Consts.JCK_STATUS_BASE + Consts.TEST_FAILED);
}
}
public static void eatMemory() {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
int memoryChunk = (int) (maxMemory / 50);
try {
List<Object> list = new ArrayList<Object>();
while (true) {
list.add(new byte[memoryChunk]);
}
} catch (OutOfMemoryError e) {
// expected exception
}
}
public static int getCurrentGCCount() {
int result = 0;
List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean bean : gcBeans) {
result += bean.getCollectionCount();
}
return result;
}
public void forceGC() {
eatMemory();
}
public void voidValueMethod() {
}
public void unexpectedException(Throwable t) {
setSuccess(false);
t.printStackTrace(log.getOutStream());
log.complain("Unexpected exception: " + t);
}
}
| gpl-2.0 |
Shutok/OregonCustom | src/scripts/EasternKingdoms/loch_modan.cpp | 6148 | /*
* Copyright (C) 2010-2012 OregonCore <http://www.oregoncore.com/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2012 ScriptDev2 <http://www.scriptdev2.com/>
*
* 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/>.
*/
/* ScriptData
SDName: Loch_Modan
SD%Complete: 100
SDComment: Quest support: 3181, 309
SDCategory: Loch Modan
EndScriptData */
/* ContentData
npc_mountaineer_pebblebitty
npc_miran
EndContentData */
#include "ScriptPCH.h"
#include "ScriptedEscortAI.h"
/*######
## npc_mountaineer_pebblebitty
######*/
#define GOSSIP_MP "Open the gate please, i need to get to Searing Gorge"
#define GOSSIP_MP1 "But i need to get there, now open the gate!"
#define GOSSIP_MP2 "Ok, so what is this other way?"
#define GOSSIP_MP3 "Doesn't matter, i'm invulnerable."
#define GOSSIP_MP4 "Yes..."
#define GOSSIP_MP5 "Ok, i'll try to remember that."
#define GOSSIP_MP6 "A key? Ok!"
bool GossipHello_npc_mountaineer_pebblebitty(Player* pPlayer, Creature* pCreature)
{
if (pCreature->isQuestGiver())
pPlayer->PrepareQuestMenu(pCreature->GetGUID());
if (!pPlayer->GetQuestRewardStatus(3181) == 1)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID());
return true;
}
bool GossipSelect_npc_mountaineer_pebblebitty(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF+1:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
pPlayer->SEND_GOSSIP_MENU(1833, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+2:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3);
pPlayer->SEND_GOSSIP_MENU(1834, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+3:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4);
pPlayer->SEND_GOSSIP_MENU(1835, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+4:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5);
pPlayer->SEND_GOSSIP_MENU(1836, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+5:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6);
pPlayer->SEND_GOSSIP_MENU(1837, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+6:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7);
pPlayer->SEND_GOSSIP_MENU(1838, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+7:
pPlayer->CLOSE_GOSSIP_MENU();
break;
}
return true;
}
/*#########
##npc_miran
#########*/
enum eMiran
{
MIRAN_SAY_AMBUSH_ONE = -1000571,
DARK_IRON_RAIDER_SAY_AMBUSH = -1000572,
MIRAN_SAY_AMBUSH_TWO = -1000573,
MIRAN_SAY_QUEST_END = -1000574,
QUEST_PROTECTING_THE_SHIPMENT = 309,
DARK_IRON_RAIDER = 2149
};
struct npc_miranAI : public npc_escortAI
{
npc_miranAI(Creature* pCreature) : npc_escortAI(pCreature) { }
void Reset() { }
void WaypointReached(uint32 uiPointId)
{
Player* pPlayer = GetPlayerForEscort();
if (!pPlayer)
return;
switch(uiPointId)
{
case 8:
DoScriptText(MIRAN_SAY_AMBUSH_ONE, me);
me->SummonCreature(DARK_IRON_RAIDER, -5697.27f,-3736.36f,318.54f, 2.02f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 30000);
me->SummonCreature(DARK_IRON_RAIDER, -5697.27f,-3736.36f,318.54f, 2.07f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 30000);
if (Unit* scoff = me->FindNearestCreature(DARK_IRON_RAIDER, 30))
DoScriptText(DARK_IRON_RAIDER_SAY_AMBUSH, scoff);
DoScriptText(MIRAN_SAY_AMBUSH_TWO, me);
break;
case 11:
DoScriptText(MIRAN_SAY_QUEST_END, me);
if (Player* pPlayer = GetPlayerForEscort())
pPlayer->GroupEventHappens(QUEST_PROTECTING_THE_SHIPMENT, me);
break;
}
}
void JustSummoned(Creature* pSummoned)
{
pSummoned->AI()->AttackStart(me);
}
};
bool QuestAccept_npc_miran(Player* pPlayer, Creature* pCreature, const Quest* pQuest)
{
if (pQuest->GetQuestId() == QUEST_PROTECTING_THE_SHIPMENT)
{
pCreature->setFaction(231);
if (npc_miranAI* pEscortAI = CAST_AI(npc_miranAI,pCreature->AI()))
pEscortAI->Start(false, false, pPlayer->GetGUID(), pQuest);
}
return true;
}
CreatureAI* GetAI_npc_miran(Creature *pCreature)
{
return new npc_miranAI(pCreature);
}
void AddSC_loch_modan()
{
Script *newscript;
newscript = new Script;
newscript->Name = "npc_mountaineer_pebblebitty";
newscript->pGossipHello = &GossipHello_npc_mountaineer_pebblebitty;
newscript->pGossipSelect = &GossipSelect_npc_mountaineer_pebblebitty;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_miran";
newscript->GetAI = &GetAI_npc_miran;
newscript->pQuestAccept = &QuestAccept_npc_miran;
newscript->RegisterSelf();
}
| gpl-2.0 |
gggeek/ezpublish-legacy | lib/ezdiff/classes/ezdiffcontainerobject.php | 482 | <?php
/**
* File containing the eZDiffContainerObject class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
* @package lib
*/
/*!
\class eZDiffContainerObject ezdiffcontainerobject.php
\ingroup eZDiff
Contains data from two versions of an content object.
*/
class eZDiffContainerObject extends eZDiffContent
{
}
?>
| gpl-2.0 |
Poxleit/s-core | src/game/BattleGround/BattleGroundRL.cpp | 3332 | /*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Object.h"
#include "Player.h"
#include "BattleGround.h"
#include "BattleGroundRL.h"
#include "ObjectMgr.h"
#include "Language.h"
#include "WorldPacket.h"
BattleGroundRL::BattleGroundRL()
{
m_StartDelayTimes[BG_STARTING_EVENT_FIRST] = BG_START_DELAY_1M;
m_StartDelayTimes[BG_STARTING_EVENT_SECOND] = BG_START_DELAY_30S;
m_StartDelayTimes[BG_STARTING_EVENT_THIRD] = BG_START_DELAY_15S;
m_StartDelayTimes[BG_STARTING_EVENT_FOURTH] = BG_START_DELAY_NONE;
// we must set messageIds
m_StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_ARENA_ONE_MINUTE;
m_StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_ARENA_THIRTY_SECONDS;
m_StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_ARENA_FIFTEEN_SECONDS;
m_StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_ARENA_HAS_BEGUN;
}
void BattleGroundRL::StartingEventOpenDoors()
{
OpenDoorEvent(BG_EVENT_DOOR);
}
void BattleGroundRL::AddPlayer(Player* plr)
{
BattleGround::AddPlayer(plr);
// create score and add it to map, default values are set in constructor
BattleGroundRLScore* sc = new BattleGroundRLScore;
m_PlayerScores[plr->GetObjectGuid()] = sc;
UpdateWorldState(0xbb8, GetAlivePlayersCountByTeam(ALLIANCE));
UpdateWorldState(0xbb9, GetAlivePlayersCountByTeam(HORDE));
}
void BattleGroundRL::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/)
{
if (GetStatus() == STATUS_WAIT_LEAVE)
return;
UpdateWorldState(0xbb8, GetAlivePlayersCountByTeam(ALLIANCE));
UpdateWorldState(0xbb9, GetAlivePlayersCountByTeam(HORDE));
CheckArenaWinConditions();
}
void BattleGroundRL::HandleKillPlayer(Player* player, Player* killer)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
if (!killer)
{
sLog.outError("Killer player not found");
return;
}
BattleGround::HandleKillPlayer(player, killer);
UpdateWorldState(0xbb8, GetAlivePlayersCountByTeam(ALLIANCE));
UpdateWorldState(0xbb9, GetAlivePlayersCountByTeam(HORDE));
CheckArenaWinConditions();
}
bool BattleGroundRL::HandlePlayerUnderMap(Player* player)
{
player->TeleportTo(GetMapId(), 1285.810547f, 1667.896851f, 39.957642f, player->GetOrientation());
return true;
}
void BattleGroundRL::FillInitialWorldStates(WorldPacket& data, uint32& count)
{
FillInitialWorldState(data, count, 0xbb8, GetAlivePlayersCountByTeam(ALLIANCE));
FillInitialWorldState(data, count, 0xbb9, GetAlivePlayersCountByTeam(HORDE));
FillInitialWorldState(data, count, 0xbba, 1);
}
| gpl-2.0 |
jacksonwilliams/arsenalsuite | cpp/lib/PyQt4/examples/tutorial/t2.py | 293 | #!/usr/bin/env python
# PyQt tutorial 2
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
quit = QtGui.QPushButton("Quit")
quit.resize(75, 30)
quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold))
quit.clicked.connect(app.quit)
quit.show()
sys.exit(app.exec_())
| gpl-2.0 |
SuriyaaKudoIsc/wikia-app-test | lib/vendor/HTML/QuickForm/Renderer/ITDynamic.php | 9900 | <?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4.0 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Alexey Borzov <borz_off@cs.msu.su> |
// +----------------------------------------------------------------------+
//
// $Id: ITDynamic.php,v 1.5 2004/10/15 13:04:36 avb Exp $
require_once 'HTML/QuickForm/Renderer.php';
/**
* A concrete renderer for HTML_QuickForm, using Integrated Templates.
*
* This is a "dynamic" renderer, which means that concrete form look
* is defined at runtime. This also means that you can define
* <b>one</b> template file for <b>all</b> your forms. That template
* should contain a block for every element 'look' appearing in your
* forms and also some special blocks (consult the examples). If a
* special block is not set for an element, the renderer falls back to
* a default one.
*
* @author Alexey Borzov <borz_off@cs.msu.su>
* @access public
*/
class HTML_QuickForm_Renderer_ITDynamic extends HTML_QuickForm_Renderer
{
/**
* A template class (HTML_Template_ITX or HTML_Template_Sigma) instance
* @var object
*/
var $_tpl = null;
/**
* The errors that were not shown near concrete fields go here
* @var array
*/
var $_errors = array();
/**
* Show the block with required note?
* @var bool
*/
var $_showRequired = false;
/**
* A separator for group elements
* @var mixed
*/
var $_groupSeparator = null;
/**
* The current element index inside a group
* @var integer
*/
var $_groupElementIdx = 0;
/**
* Blocks to use for different elements
* @var array
*/
var $_elementBlocks = array();
/**
* Block to use for headers
* @var string
*/
var $_headerBlock = null;
/**
* Constructor
*
* @param object An HTML_Template_ITX/HTML_Template_Sigma object to use
*/
function HTML_QuickForm_Renderer_ITDynamic(&$tpl)
{
$this->HTML_QuickForm_Renderer();
$this->_tpl =& $tpl;
$this->_tpl->setCurrentBlock('qf_main_loop');
}
function finishForm(&$form)
{
// display errors above form
if (!empty($this->_errors) && $this->_tpl->blockExists('qf_error_loop')) {
foreach ($this->_errors as $error) {
$this->_tpl->setVariable('qf_error', $error);
$this->_tpl->parse('qf_error_loop');
}
}
// show required note
if ($this->_showRequired) {
$this->_tpl->setVariable('qf_required_note', $form->getRequiredNote());
}
// assign form attributes
$this->_tpl->setVariable('qf_attributes', $form->getAttributes(true));
// assign javascript validation rules
$this->_tpl->setVariable('qf_javascript', $form->getValidationScript());
}
function renderHeader(&$header)
{
$blockName = $this->_matchBlock($header);
if ('qf_header' == $blockName && isset($this->_headerBlock)) {
$blockName = $this->_headerBlock;
}
$this->_tpl->setVariable('qf_header', $header->toHtml());
$this->_tpl->parse($blockName);
$this->_tpl->parse('qf_main_loop');
}
function renderElement(&$element, $required, $error)
{
$blockName = $this->_matchBlock($element);
// are we inside a group?
if ('qf_main_loop' != $this->_tpl->currentBlock) {
if (0 != $this->_groupElementIdx && $this->_tpl->placeholderExists('qf_separator', $blockName)) {
if (is_array($this->_groupSeparator)) {
$this->_tpl->setVariable('qf_separator', $this->_groupSeparator[($this->_groupElementIdx - 1) % count($this->_groupSeparator)]);
} else {
$this->_tpl->setVariable('qf_separator', (string)$this->_groupSeparator);
}
}
$this->_groupElementIdx++;
} elseif(!empty($error)) {
// show the error message or keep it for later use
if ($this->_tpl->blockExists($blockName . '_error')) {
$this->_tpl->setVariable('qf_error', $error);
} else {
$this->_errors[] = $error;
}
}
// show an '*' near the required element
if ($required) {
$this->_showRequired = true;
if ($this->_tpl->blockExists($blockName . '_required')) {
$this->_tpl->touchBlock($blockName . '_required');
}
}
// Prepare multiple labels
$labels = $element->getLabel();
if (is_array($labels)) {
$mainLabel = array_shift($labels);
} else {
$mainLabel = $labels;
}
// render the element itself with its main label
$this->_tpl->setVariable('qf_element', $element->toHtml());
if ($this->_tpl->placeholderExists('qf_label', $blockName)) {
$this->_tpl->setVariable('qf_label', $mainLabel);
}
// render extra labels, if any
if (is_array($labels)) {
foreach($labels as $key => $label) {
$key = is_int($key)? $key + 2: $key;
if ($this->_tpl->blockExists($blockName . '_label_' . $key)) {
$this->_tpl->setVariable('qf_label_' . $key, $label);
}
}
}
$this->_tpl->parse($blockName);
$this->_tpl->parseCurrentBlock();
}
function renderHidden(&$element)
{
$this->_tpl->setVariable('qf_hidden', $element->toHtml());
$this->_tpl->parse('qf_hidden_loop');
}
function startGroup(&$group, $required, $error)
{
$blockName = $this->_matchBlock($group);
$this->_tpl->setCurrentBlock($blockName . '_loop');
$this->_groupElementIdx = 0;
$this->_groupSeparator = is_null($group->_separator)? ' ': $group->_separator;
// show an '*' near the required element
if ($required) {
$this->_showRequired = true;
if ($this->_tpl->blockExists($blockName . '_required')) {
$this->_tpl->touchBlock($blockName . '_required');
}
}
// show the error message or keep it for later use
if (!empty($error)) {
if ($this->_tpl->blockExists($blockName . '_error')) {
$this->_tpl->setVariable('qf_error', $error);
} else {
$this->_errors[] = $error;
}
}
$this->_tpl->setVariable('qf_group_label', $group->getLabel());
}
function finishGroup(&$group)
{
$this->_tpl->parse($this->_matchBlock($group));
$this->_tpl->setCurrentBlock('qf_main_loop');
$this->_tpl->parseCurrentBlock();
}
/**
* Returns the name of a block to use for element rendering
*
* If a name was not explicitly set via setElementBlock(), it tries
* the names '{prefix}_{element type}' and '{prefix}_{element}', where
* prefix is either 'qf' or the name of the current group's block
*
* @param object An HTML_QuickForm_element object
* @access private
* @return string block name
*/
function _matchBlock(&$element)
{
$name = $element->getName();
$type = $element->getType();
if (isset($this->_elementBlocks[$name]) && $this->_tpl->blockExists($this->_elementBlocks[$name])) {
if (('group' == $type) || ($this->_elementBlocks[$name] . '_loop' != $this->_tpl->currentBlock)) {
return $this->_elementBlocks[$name];
}
}
if ('group' != $type && 'qf_main_loop' != $this->_tpl->currentBlock) {
$prefix = substr($this->_tpl->currentBlock, 0, -5); // omit '_loop' postfix
} else {
$prefix = 'qf';
}
if ($this->_tpl->blockExists($prefix . '_' . $type)) {
return $prefix . '_' . $type;
} elseif ($this->_tpl->blockExists($prefix . '_' . $name)) {
return $prefix . '_' . $name;
} else {
return $prefix . '_element';
}
}
/**
* Sets the block to use for element rendering
*
* @param mixed element name or array ('element name' => 'block name')
* @param string block name if $elementName is not an array
* @access public
* @return void
*/
function setElementBlock($elementName, $blockName = null)
{
if (is_array($elementName)) {
$this->_elementBlocks = array_merge($this->_elementBlocks, $elementName);
} else {
$this->_elementBlocks[$elementName] = $blockName;
}
}
/**
* Sets the name of a block to use for header rendering
*
* @param string block name
* @access public
* @return void
*/
function setHeaderBlock($blockName)
{
$this->_headerBlock = $blockName;
}
}
?>
| gpl-2.0 |
anieminen/moodle | cache/stores/mongodb/MongoDB/functions.php | 5945 | <?php
/*
* Copyright 2015-2017 MongoDB, 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.
*/
namespace MongoDB;
use MongoDB\BSON\Serializable;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\Server;
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\InvalidArgumentException;
use stdClass;
use ReflectionClass;
/**
* Applies a type map to a document.
*
* This function is used by operations where it is not possible to apply a type
* map to the cursor directly because the root document is a command response
* (e.g. findAndModify).
*
* @internal
* @param array|object $document Document to which the type map will be applied
* @param array $typeMap Type map for BSON deserialization.
* @return array|object
* @throws InvalidArgumentException
*/
function apply_type_map_to_document($document, array $typeMap)
{
if ( ! is_array($document) && ! is_object($document)) {
throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
}
return \MongoDB\BSON\toPHP(\MongoDB\BSON\fromPHP($document), $typeMap);
}
/**
* Generate an index name from a key specification.
*
* @internal
* @param array|object $document Document containing fields mapped to values,
* which denote order or an index type
* @return string
* @throws InvalidArgumentException
*/
function generate_index_name($document)
{
if ($document instanceof Serializable) {
$document = $document->bsonSerialize();
}
if (is_object($document)) {
$document = get_object_vars($document);
}
if ( ! is_array($document)) {
throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
}
$name = '';
foreach ($document as $field => $type) {
$name .= ($name != '' ? '_' : '') . $field . '_' . $type;
}
return $name;
}
/**
* Return whether the first key in the document starts with a "$" character.
*
* This is used for differentiating update and replacement documents.
*
* @internal
* @param array|object $document Update or replacement document
* @return boolean
* @throws InvalidArgumentException
*/
function is_first_key_operator($document)
{
if ($document instanceof Serializable) {
$document = $document->bsonSerialize();
}
if (is_object($document)) {
$document = get_object_vars($document);
}
if ( ! is_array($document)) {
throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
}
reset($document);
$firstKey = (string) key($document);
return (isset($firstKey[0]) && $firstKey[0] === '$');
}
/**
* Return whether the aggregation pipeline ends with an $out operator.
*
* This is used for determining whether the aggregation pipeline must be
* executed against a primary server.
*
* @internal
* @param array $pipeline List of pipeline operations
* @return boolean
*/
function is_last_pipeline_operator_out(array $pipeline)
{
$lastOp = end($pipeline);
if ($lastOp === false) {
return false;
}
$lastOp = (array) $lastOp;
return key($lastOp) === '$out';
}
/**
* Return whether the "out" option for a mapReduce operation is "inline".
*
* This is used to determine if a mapReduce command requires a primary.
*
* @internal
* @see https://docs.mongodb.com/manual/reference/command/mapReduce/#output-inline
* @param string|array|object $out Output specification
* @return boolean
* @throws InvalidArgumentException
*/
function is_mapreduce_output_inline($out)
{
if ( ! is_array($out) && ! is_object($out)) {
return false;
}
if ($out instanceof Serializable) {
$out = $out->bsonSerialize();
}
if (is_object($out)) {
$out = get_object_vars($out);
}
if ( ! is_array($out)) {
throw InvalidArgumentException::invalidType('$out', $out, 'array or object');
}
reset($out);
return key($out) === 'inline';
}
/**
* Return whether the server supports a particular feature.
*
* @internal
* @param Server $server Server to check
* @param integer $feature Feature constant (i.e. wire protocol version)
* @return boolean
*/
function server_supports_feature(Server $server, $feature)
{
$info = $server->getInfo();
$maxWireVersion = isset($info['maxWireVersion']) ? (integer) $info['maxWireVersion'] : 0;
$minWireVersion = isset($info['minWireVersion']) ? (integer) $info['minWireVersion'] : 0;
return ($minWireVersion <= $feature && $maxWireVersion >= $feature);
}
function is_string_array($input) {
if (!is_array($input)){
return false;
}
foreach($input as $item) {
if (!is_string($item)) {
return false;
}
}
return true;
}
/**
* Performs a deep copy of a value.
*
* This function will clone objects and recursively copy values within arrays.
*
* @internal
* @see https://bugs.php.net/bug.php?id=49664
* @param mixed $element Value to be copied
* @return mixed
*/
function recursive_copy($element) {
if (is_array($element)) {
foreach ($element as $key => $value) {
$element[$key] = recursive_copy($value);
}
return $element;
}
if ( ! is_object($element)) {
return $element;
}
if ( ! (new ReflectionClass($element))->isCloneable()) {
return $element;
}
return clone $element;
}
| gpl-3.0 |
deemaxx/PixelSplashTheme | wp-content/themes/responsive/front-page.php | 3754 | <?php
// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) {
exit;
}
/**
* Site Front Page
*
* Note: You can overwrite front-page.php as well as any other Template in Child Theme.
* Create the same file (name) include in /responsive-child-theme/ and you're all set to go!
* @see http://codex.wordpress.org/Child_Themes and
* http://themeid.com/forum/topic/505/child-theme-example/
*
* @file front-page.php
* @package Responsive
* @author Emil Uzelac
* @copyright 2003 - 2013 ThemeID
* @license license.txt
* @version Release: 1.0
* @filesource wp-content/themes/responsive/front-page.php
* @link http://codex.wordpress.org/Template_Hierarchy
* @since available since Release 1.0
*/
/**
* Globalize Theme Options
*/
$responsive_options = responsive_get_options();
/**
* If front page is set to display the
* blog posts index, include home.php;
* otherwise, display static front page
* content
*/
if( 'posts' == get_option( 'show_on_front' ) && $responsive_options['front_page'] != 1 ) {
get_template_part( 'home' );
}
elseif( 'page' == get_option( 'show_on_front' ) && $responsive_options['front_page'] != 1 ) {
$template = get_post_meta( get_option( 'page_on_front' ), '_wp_page_template', true );
$template = ( $template == 'default' ) ? 'index.php' : $template;
locate_template( $template, true );
}
else {
get_header();
//test for first install no database
$db = get_option( 'responsive_theme_options' );
//test if all options are empty so we can display default text if they are
$empty = ( empty( $responsive_options['home_headline'] ) && empty( $responsive_options['home_subheadline'] ) && empty( $responsive_options['home_content_area'] ) ) ? false : true;
?>
<div id="featured" class="grid col-940">
<div class="grid col-460">
<h1 class="featured-title">
<?php
if( isset( $responsive_options['home_headline'] ) && $db && $empty )
echo $responsive_options['home_headline'];
else {
_e( 'Hello, World!', 'responsive' );
}
?>
</h1>
<h2 class="featured-subtitle">
<?php
if( isset( $responsive_options['home_subheadline'] ) && $db && $empty )
echo $responsive_options['home_subheadline'];
else
_e( 'Your H2 subheadline here', 'responsive' );
?>
</h2>
<p>
<?php
if( isset( $responsive_options['home_content_area'] ) && $db && $empty )
echo do_shortcode( $responsive_options['home_content_area'] );
else
_e( 'Your title, subtitle and this very content is editable from Theme Option. Call to Action button and its destination link as well. Image on your right can be an image or even YouTube video if you like.', 'responsive' );
?>
</p>
<?php if( $responsive_options['cta_button'] == 0 ): ?>
<div class="call-to-action">
<a href="<?php echo $responsive_options['cta_url']; ?>" class="blue button">
<?php
if( isset( $responsive_options['cta_text'] ) && $db )
echo $responsive_options['cta_text'];
else
_e( 'Call to Action', 'responsive' );
?>
</a>
</div><!-- end of .call-to-action -->
<?php endif; ?>
</div>
<!-- end of .col-460 -->
<div id="featured-image" class="grid col-460 fit">
<?php $featured_content = ( !empty( $responsive_options['featured_content'] ) ) ? $responsive_options['featured_content'] : '<img class="aligncenter" src="' . get_template_directory_uri() . '/core/images/featured-image.png" width="440" height="300" alt="" />'; ?>
<?php echo do_shortcode( $featured_content ); ?>
</div>
<!-- end of #featured-image -->
</div><!-- end of #featured -->
<?php
get_sidebar( 'home' );
get_footer();
}
?>
| gpl-3.0 |
Ahava/gtaivtools | RageLib/FileSystem/RPF/MagicId.cs | 1101 | /**********************************************************************\
RageLib
Copyright (C) 2008 Arushan/Aru <oneforaru at gmail.com>
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/>.
\**********************************************************************/
using System.Reflection;
namespace RageLib.FileSystem.RPF
{
internal enum MagicId
{
//Version0 = 0x30465052,
//Version1 = 0x31465052,
Version2 = 0x32465052,
Version3 = 0x33465052,
}
} | gpl-3.0 |
Morerice/piwik | tests/lib/mocha-3.1.2/test/browser-fixtures/bdd.fixture.js | 81 | 'use strict';
/* eslint-env browser */
window.mocha.timeout(200)
.ui('bdd');
| gpl-3.0 |
cychiang/webcamstudio | src/webcamstudio/WebcamStudio.java | 135404 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* WebcamStudio.java
*
* Created on 4-Apr-2012, 3:48:07 PM
*/
package webcamstudio;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import org.xml.sax.SAXException;
import webcamstudio.channels.MasterChannels;
import webcamstudio.components.MasterPanel;
import static webcamstudio.components.MasterPanel.spinFPS;
import static webcamstudio.components.MasterPanel.spinHeight;
import static webcamstudio.components.MasterPanel.spinWidth;
import webcamstudio.components.OutputPanel;
import static webcamstudio.components.OutputPanel.execPACTL;
import webcamstudio.components.ResourceMonitor;
import webcamstudio.components.ResourceMonitorLabel;
import webcamstudio.components.SourceControls;
import webcamstudio.components.StreamDesktop;
import webcamstudio.components.VideoDeviceInfo;
import webcamstudio.exporter.vloopback.VideoDevice;
import webcamstudio.externals.ProcessRenderer;
import webcamstudio.mixers.MasterMixer;
import webcamstudio.mixers.PrePlayer;
import webcamstudio.mixers.PreviewMixer;
import webcamstudio.mixers.SystemPlayer;
import webcamstudio.streams.SourceAudioSource;
import webcamstudio.streams.SourceChannel;
import webcamstudio.streams.SourceCustom;
import webcamstudio.streams.SourceDV;
import webcamstudio.streams.SourceDVB;
import webcamstudio.streams.SourceDesktop;
import webcamstudio.streams.SourceIPCam;
import webcamstudio.streams.SourceImage;
import webcamstudio.streams.SourceImageGif;
import webcamstudio.streams.SourceImageU;
import webcamstudio.streams.SourceMovie;
import webcamstudio.streams.SourceMusic;
import webcamstudio.streams.SourceText;
import webcamstudio.streams.SourceURL;
import webcamstudio.streams.SourceWebcam;
import webcamstudio.streams.Stream;
import webcamstudio.studio.Studio;
import webcamstudio.util.Screen;
import webcamstudio.util.Tools;
import webcamstudio.util.Tools.OS;
/**
*
* @author patrick (modified by karl)
*/
public final class WebcamStudio extends JFrame implements StreamDesktop.Listener {
public static Preferences prefs = null;
public static Properties animations = new Properties();
public static Properties facesW = new Properties();
// FF = 0 ; AV = 1 ; GS = 2
public static int outFMEbe = 1;
private final static String userHomeDir = Tools.getUserHome();
OutputPanel recorder = new OutputPanel(this);
Frame about = new Frame();
Frame vDevInfo = new Frame();
Stream stream = null;
private static File cmdFile = null;
private static String cmdOut = null;
private static boolean cmdAutoStart = false;
private static boolean cmdRemote = false;
public static int audioFreq = 22050;
public static String theme = "Classic";
ArrayList<Stream> streamS = MasterChannels.getInstance().getStreams();
private File lastFolder = null;
boolean ffmpeg = Screen.ffmpegDetected();
boolean avconv = Screen.avconvDetected();
boolean firstRun = true;
static boolean autoAR = false;
@SuppressWarnings("unchecked")
private void initFaceDetection() throws IOException {
File dir = new File(System.getProperty("user.home"), ".webcamstudio/faces");
if (!dir.exists()) {
dir.mkdir();
}
facesW.load(getClass().getResourceAsStream("/webcamstudio/resources/faces/Faces.properties"));
ArrayList faceNames = new ArrayList();
String faceL = null;
for (Object o : facesW.keySet()) {
faceNames.add(o);
}
for (int i=0 ; i < faceNames.size(); i++){
faceL = faceNames.get(i).toString();
// System.out.println(faceL);
File destination = new File(System.getProperty("user.home")+"/.webcamstudio/faces/"+faceL+".png");
try (InputStream is = getClass().getResourceAsStream("/webcamstudio/resources/faces/"+faceL+".png"); OutputStream os = new FileOutputStream(destination)) {
byte[] buffer = new byte[4096];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}
}
faceNames.clear();
File destination = new File(System.getProperty("user.home")+"/.webcamstudio/faces/haarcascade_frontalface_alt2.xml");
InputStream is = getClass().getResourceAsStream("/webcamstudio/resources/haarcascade_frontalface_alt2.xml");
OutputStream os = new FileOutputStream(destination);
byte[] buffer = new byte[4096];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.close();
is.close();
destination = new File(System.getProperty("user.home")+"/.webcamstudio/faces/lbpcascade_frontalface.xml");
is = getClass().getResourceAsStream("/webcamstudio/resources/lbpcascade_frontalface.xml");
os = new FileOutputStream(destination);
buffer = new byte[4096];
int length2;
while ((length2 = is.read(buffer)) > 0) {
os.write(buffer, 0, length2);
}
os.close();
is.close();
}
@Override
public void closeSource() {
lblSourceSelected.setText("");
}
public interface Listener {
public void stopChTime(java.awt.event.ActionEvent evt);
public void resetBtnStates(java.awt.event.ActionEvent evt);
public void resetAutoPLBtnState(java.awt.event.ActionEvent evt);
public void resetSinks(java.awt.event.ActionEvent evt);
public void addLoadingChannel(String name);
public void removeChannels(String removeSc, int a);
public void setRemoteOn();
}
static Listener listenerCP = null;
public static void setListenerCP(Listener l) {
listenerCP = l;
}
static Listener listenerOP = null;
public static void setListenerOP(Listener l) {
listenerOP = l;
}
/**
* Creates new form WebcamStudio
* @throws java.io.IOException
*/
public WebcamStudio() throws IOException {
initComponents();
if (theme.equals("Dark")) {
// setting WS Dark Theme
UIManager.put("text", Color.WHITE);
UIManager.put("control", Color.darkGray);
UIManager.put("nimbusBlueGrey", Color.darkGray);
UIManager.put("nimbusBase", Color.darkGray);
UIManager.put("nimbusLightBackground", new Color(134,137,143));
UIManager.put("info", new Color(195,160,0));
UIManager.put("nimbusDisabledText", Color.black);
UIManager.put("nimbusSelectionBackground", Color.yellow);
UIManager.put("nimbusSelectedText", Color.blue);
UIManager.put("nimbusSelectionBackground", new Color(255,220,35));
}
setTitle("WebcamStudio " + Version.version);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/webcamstudio/resources/icon.png"));
this.setIconImage(icon.getImage());
desktop.setDropTarget(new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent evt) {
try {
String fileName = "";
evt.acceptDrop(DnDConstants.ACTION_REFERENCE);
boolean success = false;
DataFlavor dataFlavor = null;
if (evt.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dataFlavor = DataFlavor.javaFileListFlavor;
} else if (evt.isDataFlavorSupported(DataFlavor.stringFlavor)) {
dataFlavor = DataFlavor.stringFlavor;
} else {
for (DataFlavor d : evt.getTransferable().getTransferDataFlavors()) {
if (evt.getTransferable().isDataFlavorSupported(d)) {
System.out.println("Supported: " + d.getDefaultRepresentationClassAsString());
dataFlavor = d;
break;
}
}
}
Object data = evt.getTransferable().getTransferData(dataFlavor);
String files = "";
if (data instanceof Reader) {
char[] text = new char[65536];
files = new String(text).trim();
} else if (data instanceof InputStream) {
char[] text = new char[65536];
files = new String(text).trim();
} else if (data instanceof String) {
files = data.toString().trim();
} else {
List list = (List) data;
for (Object o : list) {
files += new File(o.toString()).toURI().toURL().toString() + "\n";
}
}
if (files.length() > 0) {
String[] lines = files.split("\n");
for (String line : lines) {
File file = new File(new URL(line.trim()).toURI());
if (file.exists()) {
fileName = file.getName();
Stream stream = Stream.getInstance(file);
if (stream != null) {
if (stream instanceof SourceMovie || stream instanceof SourceMusic || stream instanceof SourceImage || stream instanceof SourceImageU || stream instanceof SourceImageGif) {
getVideoParams(stream, file, null);
}
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
stream.addChannel(SourceChannel.getChannel(sc, stream));
}
StreamDesktop frame = getNewStreamDesktop(stream);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
frame.setLocation(evt.getLocation());
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
success = true;
}
}
}
}
evt.dropComplete(success);
if (!success) {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis() + 5000, "Unsupported file: " + fileName);
ResourceMonitor.getInstance().addMessage(label);
}
} catch (UnsupportedFlavorException | IOException | URISyntaxException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
this.add(ResourceMonitor.getInstance(), BorderLayout.SOUTH);
prefs = Preferences.userNodeForPackage(this.getClass());
panControls.add(recorder, BorderLayout.NORTH);
loadPrefs();
if (theme.equals("Dark")) {
// setting WS Dark Theme
UIManager.put("text", Color.WHITE);
UIManager.put("control", Color.darkGray);
UIManager.put("nimbusBlueGrey", Color.darkGray);
UIManager.put("nimbusBase", Color.darkGray);
UIManager.put("nimbusLightBackground", new Color(134,137,143));
UIManager.put("info", new Color(195,160,0));
UIManager.put("nimbusDisabledText", Color.black);
UIManager.put("nimbusSelectionBackground", Color.yellow);
UIManager.put("nimbusSelectedText", Color.blue);
UIManager.put("nimbusSelectionBackground", new Color(255,220,35));
}
// if (theme.equals("Green")) {
// // setting WS Green Theme
// UIManager.put("text", Color.WHITE);
// UIManager.put("control", new Color(0,80,1));
// UIManager.put("nimbusBlueGrey", new Color(0,80,30));
// UIManager.put("nimbusBase", new Color(10,110,10));
// UIManager.put("nimbusLightBackground", new Color(0,150,1));
// UIManager.put("info", new Color(195,160,0));
// UIManager.put("nimbusDisabledText", Color.black);
// UIManager.put("nimbusSelectionBackground", Color.yellow);
// UIManager.put("nimbusSelectedText", Color.blue);
// UIManager.put("nimbusSelectionBackground", new Color(255,220,35));
// }
MasterMixer.getInstance().start();
PreviewMixer.getInstance().start();
this.add(new MasterPanel(), BorderLayout.WEST);
initAnimations();
initFaceDetection();
initWebcam();
initAudioMainSW();
initThemeMainSW();
initMainOutBE();
tglAutoAR.setSelected(autoAR);
listenerOP.resetSinks(null);
loadCustomSources();
if (cmdFile != null){
loadAtStart(cmdFile,null);
btnMinimizeAllActionPerformed(null);
}
if (cmdOut != null) {
listenerOP.addLoadingChannel(cmdOut); // used addLoadingChannel to activate Output from command line.
}
if (cmdAutoStart) {
listenerCP.resetSinks(null); // used resetSinks to AutoPlay from command line.
}
if (cmdRemote) {
listenerCP.setRemoteOn();
}
firstRun = false;
}
private StreamDesktop getNewStreamDesktop(Stream s) {
return new StreamDesktop(s, this);
}
private void loadCustomSources() {
File userSettings = new File(userHomeDir + "/.webcamstudio");
if (userSettings.exists() && userSettings.isDirectory()) {
File sources = new File(userSettings, "sources");
if (sources.exists() && sources.isDirectory()) {
File[] custom = sources.listFiles();
for (File f : custom) {
if (f.getName().toLowerCase().endsWith(".wss")) {
SourceCustom streamCST;
streamCST = new SourceCustom(f);
StreamDesktop frame = new StreamDesktop(streamCST, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
frame.setClosable(false);
try {
frame.setIcon(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
}
@SuppressWarnings("unchecked")
private void initAnimations() {
try {
animations.load(getClass().getResourceAsStream("/webcamstudio/resources/animations/animations.properties"));
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (Object o : animations.keySet()) {
model.addElement(o);
}
cboAnimations.setModel(model);
} catch (IOException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
@SuppressWarnings("unchecked")
private void initWebcam() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
if (Tools.getOS() == OS.LINUX) {
for (VideoDevice d : VideoDevice.getOutputDevices()) {
model.addElement(d.getName());
}
}
cboWebcam.setModel(model);
}
@SuppressWarnings("unchecked")
private void initAudioMainSW() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement("22050Hz");
model.addElement("44100Hz");
cboAudioHz.setModel(model);
if (audioFreq == 22050) {
cboAudioHz.setSelectedItem("22050Hz");
} else {
cboAudioHz.setSelectedItem("44100Hz");
}
}
@SuppressWarnings("unchecked")
private void initThemeMainSW() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement("Classic");
model.addElement("Dark");
cboTheme.setModel(model);
if (theme.equals("Classic")) {
cboTheme.setSelectedItem("Classic");
} else {
cboTheme.setSelectedItem("Dark");
}
}
private void initMainOutBE() {
// FF = 0 ; AV = 1 ; GS = 2
if (ffmpeg && !avconv){
if (outFMEbe == 0 || outFMEbe == 1) {
outFMEbe = 0;
tglFFmpeg.setSelected(true);
tglAVconv.setEnabled(false);
tglGst.setEnabled(true);
} else if (outFMEbe == 2) {
tglFFmpeg.setSelected(false);
tglFFmpeg.setEnabled(true);
tglAVconv.setEnabled(false);
tglGst.setSelected(true);
}
} else if (ffmpeg && avconv) {
switch (outFMEbe) {
case 0:
tglFFmpeg.setSelected(true);
tglAVconv.setEnabled(true);
tglGst.setEnabled(true);
break;
case 1:
tglFFmpeg.setEnabled(true);
tglAVconv.setSelected(true);
tglGst.setEnabled(true);
break;
case 2:
tglFFmpeg.setEnabled(true);
tglAVconv.setEnabled(true);
tglGst.setSelected(true);
break;
}
} else if (!ffmpeg && avconv){
if (outFMEbe == 1 || outFMEbe == 0) {
outFMEbe = 1;
tglAVconv.setSelected(true);
tglFFmpeg.setEnabled(false);
tglGst.setEnabled(true);
} else if (outFMEbe == 2) {
tglFFmpeg.setEnabled(false);
tglAVconv.setEnabled(true);
tglGst.setSelected(true);
}
}
// System.out.println("OutFMEbe: "+outFMEbe);
}
private void loadPrefs() {
int x = prefs.getInt("main-x", 100);
int y = prefs.getInt("main-y", 100);
int w = prefs.getInt("main-w", 800);
int h = prefs.getInt("main-h", 400);
MasterMixer.getInstance().setWidth(prefs.getInt("mastermixer-w", MasterMixer.getInstance().getWidth()));
MasterMixer.getInstance().setHeight(prefs.getInt("mastermixer-h", MasterMixer.getInstance().getHeight()));
MasterMixer.getInstance().setRate(prefs.getInt("mastermixer-r", MasterMixer.getInstance().getRate()));
PreviewMixer.getInstance().setWidth(prefs.getInt("mastermixer-w", MasterMixer.getInstance().getWidth()));
PreviewMixer.getInstance().setHeight(prefs.getInt("mastermixer-h", MasterMixer.getInstance().getHeight()));
// PreviewMixer.getInstance().setRate(prefs.getInt("mastermixer-r", MasterMixer.getInstance().getRate()));
PreviewMixer.getInstance().setRate(5);
mainSplit.setDividerLocation(prefs.getInt("split-x", mainSplit.getDividerLocation()));
mainSplit.setDividerLocation(prefs.getInt("split-last-x", mainSplit.getLastDividerLocation()));
lastFolder = new File(prefs.get("lastfolder", "."));
audioFreq = prefs.getInt("audio-freq", audioFreq);
theme = prefs.get("theme", theme);
outFMEbe = prefs.getInt("out-FME", outFMEbe);
autoAR = prefs.getBoolean("autoar", autoAR);
this.setLocation(x, y);
this.setSize(w, h);
recorder.loadPrefs(prefs);
}
private void savePrefs() {
prefs.putInt("main-x", this.getX());
prefs.putInt("main-y", this.getY());
prefs.putInt("main-w", this.getWidth());
prefs.putInt("main-h", this.getHeight());
prefs.putInt("mastermixer-w", MasterMixer.getInstance().getWidth());
prefs.putInt("mastermixer-h", MasterMixer.getInstance().getHeight());
prefs.putInt("mastermixer-r", MasterMixer.getInstance().getRate());
prefs.putInt("split-x", mainSplit.getDividerLocation());
prefs.putInt("split-last-x", mainSplit.getLastDividerLocation());
if (lastFolder != null) {
prefs.put("lastfolder", lastFolder.getAbsolutePath());
}
prefs.putInt("audio-freq", audioFreq);
prefs.put("theme", theme);
// System.out.println("Theme:"+theme);
prefs.putInt("out-FME", outFMEbe);
prefs.putBoolean("autoar", autoAR);
recorder.savePrefs(prefs);
try {
prefs.flush();
} catch (BackingStoreException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainSplit = new javax.swing.JSplitPane();
panSources = new javax.swing.JPanel();
toolbar = new javax.swing.JToolBar();
btnAddFile = new javax.swing.JButton();
btnAddFolder = new javax.swing.JButton();
tglAutoAR = new javax.swing.JToggleButton();
jSeparator3 = new javax.swing.JToolBar.Separator();
btnAddDVB = new javax.swing.JButton();
btnAddURL = new javax.swing.JButton();
btnAddIPCam = new javax.swing.JButton();
btnAddDVCam = new javax.swing.JButton();
btnAddDesktop = new javax.swing.JButton();
btnAddText = new javax.swing.JButton();
btnAddAudioSrc = new javax.swing.JButton();
jSeparator1 = new javax.swing.JToolBar.Separator();
cboAnimations = new javax.swing.JComboBox();
btnAddAnimation = new javax.swing.JButton();
jSeparator2 = new javax.swing.JToolBar.Separator();
btnMinimizeAll = new javax.swing.JButton();
desktop = new javax.swing.JDesktopPane();
panControls = new javax.swing.JPanel();
tabControls = new javax.swing.JTabbedPane();
lblSourceSelected = new javax.swing.JLabel();
mainToolbar = new javax.swing.JToolBar();
btnNewStudio = new javax.swing.JButton();
btnImportStudio = new javax.swing.JButton();
btnSaveStudio = new javax.swing.JButton();
WCSAbout = new javax.swing.JButton();
jSeparator16 = new javax.swing.JToolBar.Separator();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(3, 0), new java.awt.Dimension(0, 0));
cboWebcam = new javax.swing.JComboBox();
btnAddWebcams = new javax.swing.JButton();
btnRefreshWebcam = new javax.swing.JButton();
btnVideoDevInfo = new javax.swing.JButton();
jSeparator17 = new javax.swing.JToolBar.Separator();
jLabel2 = new javax.swing.JLabel();
cboAudioHz = new javax.swing.JComboBox();
filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(2, 0), new java.awt.Dimension(0, 0));
jSeparator10 = new javax.swing.JToolBar.Separator();
jLabel3 = new javax.swing.JLabel();
cboTheme = new javax.swing.JComboBox();
filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(2, 0), new java.awt.Dimension(0, 0));
jSeparator7 = new javax.swing.JToolBar.Separator();
btnSysGC = new javax.swing.JButton();
lblClrRam = new javax.swing.JLabel();
filler5 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(2, 0), new java.awt.Dimension(0, 0));
jSeparator12 = new javax.swing.JToolBar.Separator();
filler4 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(3, 0), new java.awt.Dimension(0, 0));
filler7 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
lblFFmpeg3 = new javax.swing.JLabel();
tglFFmpeg = new javax.swing.JToggleButton();
lblFFmpeg = new javax.swing.JLabel();
tglAVconv = new javax.swing.JToggleButton();
lblAVconv = new javax.swing.JLabel();
tglGst = new javax.swing.JToggleButton();
lblGst = new javax.swing.JLabel();
filler6 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(3, 0), new java.awt.Dimension(0, 0));
jSeparator13 = new javax.swing.JToolBar.Separator();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("WebcamStudio");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
mainSplit.setDividerLocation(500);
mainSplit.setName("mainSplit"); // NOI18N
mainSplit.setOneTouchExpandable(true);
panSources.setName("panSources"); // NOI18N
toolbar.setFloatable(false);
toolbar.setRollover(true);
toolbar.setMinimumSize(new java.awt.Dimension(200, 34));
toolbar.setName("toolbar"); // NOI18N
btnAddFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/studio-add.png"))); // NOI18N
btnAddFile.setToolTipText("Load Media");
btnAddFile.setFocusable(false);
btnAddFile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddFile.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddFile.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddFile.setName("btnAddFile"); // NOI18N
btnAddFile.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddFile.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddFileActionPerformed(evt);
}
});
toolbar.add(btnAddFile);
btnAddFolder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/media-add-folder.png"))); // NOI18N
btnAddFolder.setToolTipText("Load Media Folder");
btnAddFolder.setFocusable(false);
btnAddFolder.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddFolder.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddFolder.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddFolder.setName("btnAddFolder"); // NOI18N
btnAddFolder.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddFolder.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddFolder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddFolderActionPerformed(evt);
}
});
toolbar.add(btnAddFolder);
tglAutoAR.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/ar_button.png"))); // NOI18N
tglAutoAR.setToolTipText("Automatic A/R detection Switch.");
tglAutoAR.setFocusable(false);
tglAutoAR.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
tglAutoAR.setMaximumSize(new java.awt.Dimension(29, 28));
tglAutoAR.setMinimumSize(new java.awt.Dimension(25, 25));
tglAutoAR.setName("tglAutoAR"); // NOI18N
tglAutoAR.setPreferredSize(new java.awt.Dimension(28, 29));
tglAutoAR.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/ar_button.png"))); // NOI18N
tglAutoAR.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/ar_button_selected.png"))); // NOI18N
tglAutoAR.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
tglAutoAR.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tglAutoARActionPerformed(evt);
}
});
toolbar.add(tglAutoAR);
jSeparator3.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator3.setName("jSeparator3"); // NOI18N
jSeparator3.setOpaque(true);
toolbar.add(jSeparator3);
btnAddDVB.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/dvb.png"))); // NOI18N
btnAddDVB.setToolTipText("Add DVB-T Stream");
btnAddDVB.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
btnAddDVB.setFocusable(false);
btnAddDVB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddDVB.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddDVB.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddDVB.setName("btnAddDVB"); // NOI18N
btnAddDVB.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddDVB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddDVB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddDVBActionPerformed(evt);
}
});
toolbar.add(btnAddDVB);
btnAddURL.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/url5.png"))); // NOI18N
btnAddURL.setToolTipText("Add URL Stream");
btnAddURL.setFocusable(false);
btnAddURL.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddURL.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddURL.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddURL.setName("btnAddURL"); // NOI18N
btnAddURL.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddURL.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddURL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddURLActionPerformed(evt);
}
});
toolbar.add(btnAddURL);
btnAddIPCam.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/ip-cam-2.png"))); // NOI18N
btnAddIPCam.setToolTipText("Add IPCam Stream");
btnAddIPCam.setFocusable(false);
btnAddIPCam.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddIPCam.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddIPCam.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddIPCam.setName("btnAddIPCam"); // NOI18N
btnAddIPCam.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddIPCam.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddIPCam.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddIPCamActionPerformed(evt);
}
});
toolbar.add(btnAddIPCam);
btnAddDVCam.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/Firewire.png"))); // NOI18N
btnAddDVCam.setToolTipText("Add DVCam Stream");
btnAddDVCam.setFocusable(false);
btnAddDVCam.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddDVCam.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddDVCam.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddDVCam.setName("btnAddDVCam"); // NOI18N
btnAddDVCam.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddDVCam.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddDVCam.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddDVCamActionPerformed(evt);
}
});
toolbar.add(btnAddDVCam);
btnAddDesktop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/user-desktop.png"))); // NOI18N
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("webcamstudio/Languages"); // NOI18N
btnAddDesktop.setToolTipText(bundle.getString("DESKTOP")); // NOI18N
btnAddDesktop.setFocusable(false);
btnAddDesktop.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddDesktop.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddDesktop.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddDesktop.setName("btnAddDesktop"); // NOI18N
btnAddDesktop.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddDesktop.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddDesktop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddDesktopActionPerformed(evt);
}
});
toolbar.add(btnAddDesktop);
btnAddText.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/accessories-text-editor.png"))); // NOI18N
btnAddText.setToolTipText("Text/QRCode");
btnAddText.setFocusable(false);
btnAddText.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddText.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddText.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddText.setName("btnAddText"); // NOI18N
btnAddText.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddText.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddTextActionPerformed(evt);
}
});
toolbar.add(btnAddText);
btnAddAudioSrc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/audio-volume-high.png"))); // NOI18N
btnAddAudioSrc.setToolTipText("AudioSource");
btnAddAudioSrc.setFocusable(false);
btnAddAudioSrc.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddAudioSrc.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddAudioSrc.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddAudioSrc.setName("btnAddAudioSrc"); // NOI18N
btnAddAudioSrc.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddAudioSrc.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddAudioSrc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddAudioSrcActionPerformed(evt);
}
});
toolbar.add(btnAddAudioSrc);
jSeparator1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator1.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator1.setName("jSeparator1"); // NOI18N
jSeparator1.setOpaque(true);
toolbar.add(jSeparator1);
cboAnimations.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboAnimations.setToolTipText(bundle.getString("ANIMATIONS")); // NOI18N
cboAnimations.setName("cboAnimations"); // NOI18N
toolbar.add(cboAnimations);
btnAddAnimation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/Anim-add.png"))); // NOI18N
btnAddAnimation.setToolTipText(bundle.getString("ADD_ANIMATION")); // NOI18N
btnAddAnimation.setFocusable(false);
btnAddAnimation.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddAnimation.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddAnimation.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddAnimation.setName("btnAddAnimation"); // NOI18N
btnAddAnimation.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddAnimation.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddAnimation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddAnimationActionPerformed(evt);
}
});
toolbar.add(btnAddAnimation);
jSeparator2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator2.setName("jSeparator2"); // NOI18N
jSeparator2.setOpaque(true);
toolbar.add(jSeparator2);
btnMinimizeAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/go-down.png"))); // NOI18N
btnMinimizeAll.setToolTipText(bundle.getString("ICON_ALL")); // NOI18N
btnMinimizeAll.setFocusable(false);
btnMinimizeAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnMinimizeAll.setMaximumSize(new java.awt.Dimension(29, 28));
btnMinimizeAll.setMinimumSize(new java.awt.Dimension(25, 25));
btnMinimizeAll.setName("btnMinimizeAll"); // NOI18N
btnMinimizeAll.setPreferredSize(new java.awt.Dimension(28, 28));
btnMinimizeAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnMinimizeAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMinimizeAllActionPerformed(evt);
}
});
toolbar.add(btnMinimizeAll);
desktop.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("SOURCES"))); // NOI18N
desktop.setToolTipText(bundle.getString("DROP_SOURCSE")); // NOI18N
desktop.setAutoscrolls(true);
desktop.setName("desktop"); // NOI18N
javax.swing.GroupLayout panSourcesLayout = new javax.swing.GroupLayout(panSources);
panSources.setLayout(panSourcesLayout);
panSourcesLayout.setHorizontalGroup(
panSourcesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktop)
.addComponent(toolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
);
panSourcesLayout.setVerticalGroup(
panSourcesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panSourcesLayout.createSequentialGroup()
.addComponent(toolbar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(desktop, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
.addContainerGap())
);
mainSplit.setLeftComponent(panSources);
panControls.setName("panControls"); // NOI18N
panControls.setPreferredSize(new java.awt.Dimension(200, 455));
panControls.setLayout(new java.awt.BorderLayout());
tabControls.setBorder(javax.swing.BorderFactory.createTitledBorder("Source Properties"));
tabControls.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
tabControls.setName("tabControls"); // NOI18N
tabControls.setPreferredSize(new java.awt.Dimension(200, 455));
panControls.add(tabControls, java.awt.BorderLayout.CENTER);
lblSourceSelected.setName("lblSourceSelected"); // NOI18N
panControls.add(lblSourceSelected, java.awt.BorderLayout.SOUTH);
mainSplit.setRightComponent(panControls);
getContentPane().add(mainSplit, java.awt.BorderLayout.CENTER);
mainToolbar.setFloatable(false);
mainToolbar.setMargin(new java.awt.Insets(0, 0, 0, 50));
mainToolbar.setName("mainToolbar"); // NOI18N
btnNewStudio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/document-new.png"))); // NOI18N
btnNewStudio.setToolTipText("New Studio");
btnNewStudio.setFocusable(false);
btnNewStudio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnNewStudio.setMaximumSize(new java.awt.Dimension(29, 28));
btnNewStudio.setMinimumSize(new java.awt.Dimension(25, 25));
btnNewStudio.setName("btnNewStudio"); // NOI18N
btnNewStudio.setPreferredSize(new java.awt.Dimension(28, 28));
btnNewStudio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnNewStudio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNewStudioActionPerformed(evt);
}
});
mainToolbar.add(btnNewStudio);
btnLoadStudio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/document-open.png"))); // NOI18N
btnLoadStudio.setToolTipText(bundle.getString("LOAD")); // NOI18N
btnLoadStudio.setFocusable(false);
btnLoadStudio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnLoadStudio.setMaximumSize(new java.awt.Dimension(29, 28));
btnLoadStudio.setMinimumSize(new java.awt.Dimension(25, 25));
btnLoadStudio.setName("btnLoadStudio"); // NOI18N
btnLoadStudio.setPreferredSize(new java.awt.Dimension(28, 28));
btnLoadStudio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnLoadStudio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadStudioActionPerformed(evt);
}
});
mainToolbar.add(btnLoadStudio);
btnImportStudio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/chan-add.png"))); // NOI18N
btnImportStudio.setToolTipText("Import Studio");
btnImportStudio.setFocusable(false);
btnImportStudio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnImportStudio.setMaximumSize(new java.awt.Dimension(29, 28));
btnImportStudio.setMinimumSize(new java.awt.Dimension(25, 25));
btnImportStudio.setName("btnImportStudio"); // NOI18N
btnImportStudio.setPreferredSize(new java.awt.Dimension(28, 28));
btnImportStudio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnImportStudio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnImportStudioActionPerformed(evt);
}
});
mainToolbar.add(btnImportStudio);
btnSaveStudio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/document-save.png"))); // NOI18N
btnSaveStudio.setToolTipText(bundle.getString("SAVE")); // NOI18N
btnSaveStudio.setFocusable(false);
btnSaveStudio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnSaveStudio.setMaximumSize(new java.awt.Dimension(29, 28));
btnSaveStudio.setMinimumSize(new java.awt.Dimension(25, 25));
btnSaveStudio.setName("btnSaveStudio"); // NOI18N
btnSaveStudio.setPreferredSize(new java.awt.Dimension(28, 28));
btnSaveStudio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnSaveStudio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveStudioActionPerformed(evt);
}
});
mainToolbar.add(btnSaveStudio);
WCSAbout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/user-info.png"))); // NOI18N
WCSAbout.setToolTipText("About");
WCSAbout.setFocusable(false);
WCSAbout.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
WCSAbout.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
WCSAbout.setMaximumSize(new java.awt.Dimension(29, 28));
WCSAbout.setMinimumSize(new java.awt.Dimension(25, 25));
WCSAbout.setName("WCSAbout"); // NOI18N
WCSAbout.setPreferredSize(new java.awt.Dimension(28, 28));
WCSAbout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
WCSAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WCSAboutActionPerformed(evt);
}
});
mainToolbar.add(WCSAbout);
jSeparator16.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator16.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator16.setName("jSeparator16"); // NOI18N
jSeparator16.setOpaque(true);
jSeparator16.setSeparatorSize(new java.awt.Dimension(3, 10));
mainToolbar.add(jSeparator16);
filler1.setName("filler1"); // NOI18N
mainToolbar.add(filler1);
cboWebcam.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboWebcam.setToolTipText("Detected Video Devices");
cboWebcam.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
cboWebcam.setName("cboWebcam"); // NOI18N
mainToolbar.add(cboWebcam);
btnAddWebcams.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/camera-video.png"))); // NOI18N
btnAddWebcams.setToolTipText("Add Selected Device");
btnAddWebcams.setFocusable(false);
btnAddWebcams.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAddWebcams.setMaximumSize(new java.awt.Dimension(29, 28));
btnAddWebcams.setMinimumSize(new java.awt.Dimension(25, 25));
btnAddWebcams.setName("btnAddWebcams"); // NOI18N
btnAddWebcams.setPreferredSize(new java.awt.Dimension(28, 28));
btnAddWebcams.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAddWebcams.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddWebcamsActionPerformed(evt);
}
});
mainToolbar.add(btnAddWebcams);
btnRefreshWebcam.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/view-refresh.png"))); // NOI18N
btnRefreshWebcam.setToolTipText("Refresh Video Devices Detection");
btnRefreshWebcam.setFocusable(false);
btnRefreshWebcam.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnRefreshWebcam.setMaximumSize(new java.awt.Dimension(29, 28));
btnRefreshWebcam.setMinimumSize(new java.awt.Dimension(25, 25));
btnRefreshWebcam.setName("btnRefreshWebcam"); // NOI18N
btnRefreshWebcam.setPreferredSize(new java.awt.Dimension(28, 28));
btnRefreshWebcam.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnRefreshWebcam.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshWebcamActionPerformed(evt);
}
});
mainToolbar.add(btnRefreshWebcam);
btnVideoDevInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/camera-info.png"))); // NOI18N
btnVideoDevInfo.setToolTipText(bundle.getString("VIDEO_DEVICE_INFO")); // NOI18N
btnVideoDevInfo.setFocusable(false);
btnVideoDevInfo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnVideoDevInfo.setMaximumSize(new java.awt.Dimension(29, 28));
btnVideoDevInfo.setMinimumSize(new java.awt.Dimension(25, 25));
btnVideoDevInfo.setName("btnVideoDevInfo"); // NOI18N
btnVideoDevInfo.setPreferredSize(new java.awt.Dimension(28, 28));
btnVideoDevInfo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnVideoDevInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnVideoDevInfoActionPerformed(evt);
}
});
mainToolbar.add(btnVideoDevInfo);
jSeparator17.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator17.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator17.setName("jSeparator17"); // NOI18N
jSeparator17.setOpaque(true);
jSeparator17.setSeparatorSize(new java.awt.Dimension(5, 10));
mainToolbar.add(jSeparator17);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/audio-Hz.png"))); // NOI18N
jLabel2.setToolTipText("Master Audio Sample Rate");
jLabel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 1));
jLabel2.setName("jLabel2"); // NOI18N
mainToolbar.add(jLabel2);
cboAudioHz.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboAudioHz.setToolTipText("Choose Default Audio Output Quality.");
cboAudioHz.setName("cboAudioHz"); // NOI18N
cboAudioHz.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboAudioHzActionPerformed(evt);
}
});
mainToolbar.add(cboAudioHz);
filler2.setName("filler2"); // NOI18N
mainToolbar.add(filler2);
jSeparator10.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator10.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator10.setName("jSeparator10"); // NOI18N
jSeparator10.setOpaque(true);
jSeparator10.setSeparatorSize(new java.awt.Dimension(5, 10));
mainToolbar.add(jSeparator10);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/image-x-generic.png"))); // NOI18N
jLabel3.setToolTipText("Master Theme Selector");
jLabel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 1));
jLabel3.setName("jLabel3"); // NOI18N
mainToolbar.add(jLabel3);
cboTheme.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboTheme.setToolTipText("Choose Default WS Theme.");
cboTheme.setName("cboTheme"); // NOI18N
cboTheme.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboThemeActionPerformed(evt);
}
});
mainToolbar.add(cboTheme);
filler3.setName("filler3"); // NOI18N
mainToolbar.add(filler3);
jSeparator7.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator7.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator7.setName("jSeparator7"); // NOI18N
jSeparator7.setOpaque(true);
jSeparator7.setSeparatorSize(new java.awt.Dimension(5, 10));
mainToolbar.add(jSeparator7);
btnSysGC.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/button-small-clear.png"))); // NOI18N
btnSysGC.setToolTipText("Try to Clean Up some memory");
btnSysGC.setFocusable(false);
btnSysGC.setName("btnSysGC"); // NOI18N
btnSysGC.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnSysGC.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSysGCActionPerformed(evt);
}
});
mainToolbar.add(btnSysGC);
lblClrRam.setFont(new java.awt.Font("Ubuntu Condensed", 0, 12)); // NOI18N
lblClrRam.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblClrRam.setText("RAM");
lblClrRam.setToolTipText("Try to Clean Up some memory");
lblClrRam.setName("lblClrRam"); // NOI18N
mainToolbar.add(lblClrRam);
filler5.setName("filler5"); // NOI18N
mainToolbar.add(filler5);
jSeparator12.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator12.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator12.setName("jSeparator12"); // NOI18N
jSeparator12.setOpaque(true);
jSeparator12.setSeparatorSize(new java.awt.Dimension(5, 10));
mainToolbar.add(jSeparator12);
filler4.setName("filler4"); // NOI18N
mainToolbar.add(filler4);
filler7.setName("filler7"); // NOI18N
mainToolbar.add(filler7);
lblFFmpeg3.setBackground(new java.awt.Color(102, 102, 102));
lblFFmpeg3.setFont(new java.awt.Font("Ubuntu Condensed", 1, 14)); // NOI18N
lblFFmpeg3.setText("OUT BackEnd: ");
lblFFmpeg3.setToolTipText("Select Available Outputs Back-Ends");
lblFFmpeg3.setName("lblFFmpeg3"); // NOI18N
mainToolbar.add(lblFFmpeg3);
tglFFmpeg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/FFmpeg.png"))); // NOI18N
tglFFmpeg.setToolTipText("Use FFmpeg Output Backend.");
tglFFmpeg.setFocusable(false);
tglFFmpeg.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
tglFFmpeg.setMaximumSize(new java.awt.Dimension(29, 28));
tglFFmpeg.setMinimumSize(new java.awt.Dimension(25, 25));
tglFFmpeg.setName("tglFFmpeg"); // NOI18N
tglFFmpeg.setPreferredSize(new java.awt.Dimension(28, 29));
tglFFmpeg.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/FFmpeg.png"))); // NOI18N
tglFFmpeg.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/FFmpegSelected.png"))); // NOI18N
tglFFmpeg.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
tglFFmpeg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tglFFmpegActionPerformed(evt);
}
});
mainToolbar.add(tglFFmpeg);
lblFFmpeg.setFont(new java.awt.Font("Ubuntu Condensed", 0, 12)); // NOI18N
lblFFmpeg.setText("FFmpeg ");
lblFFmpeg.setName("lblFFmpeg"); // NOI18N
mainToolbar.add(lblFFmpeg);
tglAVconv.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/FFmpeg.png"))); // NOI18N
tglAVconv.setToolTipText("Use Libav Output Backend.");
tglAVconv.setFocusable(false);
tglAVconv.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
tglAVconv.setMaximumSize(new java.awt.Dimension(29, 28));
tglAVconv.setMinimumSize(new java.awt.Dimension(25, 25));
tglAVconv.setName("tglAVconv"); // NOI18N
tglAVconv.setPreferredSize(new java.awt.Dimension(28, 29));
tglAVconv.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/FFmpeg.png"))); // NOI18N
tglAVconv.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/FFmpegSelected.png"))); // NOI18N
tglAVconv.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
tglAVconv.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tglAVconvActionPerformed(evt);
}
});
mainToolbar.add(tglAVconv);
lblAVconv.setFont(new java.awt.Font("Ubuntu Condensed", 0, 12)); // NOI18N
lblAVconv.setText("Libav ");
lblAVconv.setName("lblAVconv"); // NOI18N
mainToolbar.add(lblAVconv);
tglGst.setIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/gstreamer.png"))); // NOI18N
tglGst.setToolTipText("Use GStreamer Output Backend.");
tglGst.setFocusable(false);
tglGst.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
tglGst.setMaximumSize(new java.awt.Dimension(29, 28));
tglGst.setMinimumSize(new java.awt.Dimension(25, 25));
tglGst.setName("tglGst"); // NOI18N
tglGst.setPreferredSize(new java.awt.Dimension(28, 29));
tglGst.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/gstreamer.png"))); // NOI18N
tglGst.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/webcamstudio/resources/tango/gstreamerSelected.png"))); // NOI18N
tglGst.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
tglGst.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tglGstActionPerformed(evt);
}
});
mainToolbar.add(tglGst);
lblGst.setFont(new java.awt.Font("Ubuntu Condensed", 0, 12)); // NOI18N
lblGst.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
lblGst.setText("GStreamer");
lblGst.setName("lblGst"); // NOI18N
mainToolbar.add(lblGst);
filler6.setName("filler6"); // NOI18N
mainToolbar.add(filler6);
jSeparator13.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSeparator13.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jSeparator13.setName("jSeparator13"); // NOI18N
jSeparator13.setOpaque(true);
jSeparator13.setSeparatorSize(new java.awt.Dimension(5, 10));
mainToolbar.add(jSeparator13);
getContentPane().add(mainToolbar, java.awt.BorderLayout.PAGE_START);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
boolean close = true;
ArrayList<Stream> streamzI = MasterChannels.getInstance().getStreams();
ArrayList<String> sourceChI = MasterChannels.getInstance().getChannels();
if (streamzI.size()>0 || sourceChI.size()>0) {
int result = JOptionPane.showConfirmDialog(this,"Really Close WebcamStudio ?","Save Studio Remainder",JOptionPane.YES_NO_CANCEL_OPTION);
switch(result){
case JOptionPane.YES_OPTION:
close = true;
break;
case JOptionPane.NO_OPTION:
close = false;
break;
case JOptionPane.CANCEL_OPTION:
close = false;
break;
case JOptionPane.CLOSED_OPTION:
close = false;
break;
}
if (close) {
savePrefs();
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
Tools.sleep(10);
MasterMixer.getInstance().stop();
PreviewMixer.getInstance().stop();
try {
execPACTL("pactl unload-module module-null-sink");
} catch (IOException | InterruptedException ex) {
Logger.getLogger(OutputPanel.class.getName()).log(Level.SEVERE, null, ex);
}
Tools.sleep(100);
listenerOP.resetBtnStates(null);
listenerOP.resetSinks(null);
tabControls.removeAll();
tabControls.repaint();
Tools.sleep(300);
desktop.removeAll();
Tools.sleep(10);
System.out.println("Cleaning up ...");
File directory = new File(userHomeDir+"/.webcamstudio");
for(File f: directory.listFiles()) {
if(f.getName().startsWith("WSU") || f.getName().startsWith("WSC")) {
f.delete();
}
}
System.out.println("Thanks for using WebcamStudio ...");
System.out.println("GoodBye!");
System.exit(0);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "WebcamStudio Quit Action Cancelled.");
ResourceMonitor.getInstance().addMessage(label);
}
} else {
savePrefs();
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
Tools.sleep(10);
MasterMixer.getInstance().stop();
PreviewMixer.getInstance().stop();
System.out.println("Thanks for using WebcamStudio ...");
System.out.println("GoodBye!");
System.exit(0);
}
}//GEN-LAST:event_formWindowClosing
private void btnAddDesktopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddDesktopActionPerformed
SourceDesktop streamDesk;
streamDesk = new SourceDesktop();
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamDesk.addChannel(SourceChannel.getChannel(sc, streamDesk));
}
StreamDesktop frame = new StreamDesktop(streamDesk, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddDesktopActionPerformed
private void btnAddTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddTextActionPerformed
SourceText streamTXT;
streamTXT = new SourceText("ws");
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamTXT.addChannel(SourceChannel.getChannel(sc, streamTXT));
}
StreamDesktop frame = new StreamDesktop(streamTXT, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddTextActionPerformed
private void btnAddFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFileActionPerformed
JFileChooser chooser = new JFileChooser(lastFolder);
FileNameExtensionFilter mediaFilter = new FileNameExtensionFilter("Supported Media files", "avi", "ogg", "jpeg", "ogv", "mp4", "m4v", "mpg", "divx", "wmv", "flv", "mov", "mkv", "vob", "jpg", "bmp", "png", "gif", "mp3", "wav", "wma", "m4a", ".mp2");
chooser.setFileFilter(mediaFilter);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("Add Media file ...");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int retVal = chooser.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (file != null) {
lastFolder = file.getParentFile();
String FileName = file.getName();
System.out.println("Name: " + FileName);
}
if (file != null) {
Stream s = Stream.getInstance(file);
if (s != null) {
if (s instanceof SourceMovie || s instanceof SourceMusic || s instanceof SourceImage || s instanceof SourceImageU || s instanceof SourceImageGif) {
getVideoParams(s, file, null);
}
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
s.addChannel(SourceChannel.getChannel(sc, s));
}
StreamDesktop frame = new StreamDesktop(s, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "No File Selected!");
ResourceMonitor.getInstance().addMessage(label);
}
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Loading Cancelled!");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_btnAddFileActionPerformed
private void btnAddAnimationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddAnimationActionPerformed
try {
String key = cboAnimations.getSelectedItem().toString();
String res = animations.getProperty(key);
URL url = getClass().getResource("/webcamstudio/resources/animations/" + res);
Stream streamAnm;
streamAnm = new SourceImageGif(key, url);
BufferedImage gifImage = ImageIO.read(url);
getVideoParams(streamAnm, null, gifImage);
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamAnm.addChannel(SourceChannel.getChannel(sc, streamAnm));
}
StreamDesktop frame = new StreamDesktop(streamAnm, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddAnimationActionPerformed
private void btnMinimizeAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMinimizeAllActionPerformed
for (Component c : desktop.getComponents()) {
if (c instanceof StreamDesktop) {
StreamDesktop d = (StreamDesktop) c;
try {
Tools.sleep(20);
d.setIcon(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_btnMinimizeAllActionPerformed
private void btnSaveStudioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveStudioActionPerformed
final java.awt.event.ActionEvent sEvt = evt;
try {
File file;
boolean overWrite = true;
ArrayList<Stream> streamzI = MasterChannels.getInstance().getStreams();
ArrayList<String> sourceChI = MasterChannels.getInstance().getChannels();
if (streamzI.size()>0 || sourceChI.size()>0) {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(this,
"All Playing Streams will be Stopped !!!","Attention",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]);
}
JFileChooser chooser = new JFileChooser(lastFolder);
FileNameExtensionFilter studioFilter = new FileNameExtensionFilter("Studio files (*.studio)", "studio");
chooser.setFileFilter(studioFilter);
chooser.setDialogTitle("Save a Studio ...");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int retval = chooser.showSaveDialog(this);
file = chooser.getSelectedFile();
if (retval == JFileChooser.APPROVE_OPTION && file!=null && file.exists()) {
int result = JOptionPane.showConfirmDialog(this,"File exists, overwrite?","Attention",JOptionPane.YES_NO_CANCEL_OPTION);
switch(result){
case JOptionPane.YES_OPTION:
overWrite = true;
break;
case JOptionPane.NO_OPTION:
overWrite = false;
break;
case JOptionPane.CANCEL_OPTION:
overWrite = false;
break;
case JOptionPane.CLOSED_OPTION:
overWrite = false;
break;
}
}
if (retval == JFileChooser.APPROVE_OPTION && overWrite) {
final WaitingDialog waitingD = new WaitingDialog(this);
final File fileF = file;
lblSourceSelected.setText("");
waitingD.setModal(true);
SwingWorker<?,?> worker = new SwingWorker<Void,Integer>(){
@Override
protected Void doInBackground() throws InterruptedException{
if (fileF!=null){
File fileS = fileF;
lastFolder = fileS.getParentFile();
SystemPlayer.getInstance(null).stop();
Tools.sleep(100);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(100);
MasterChannels.getInstance().stopAllStream();
Tools.sleep(100);
listenerCP.stopChTime(sEvt);
for (Stream s : MasterChannels.getInstance().getStreams()){
s.updateStatus();
}
if (!fileS.getName().endsWith(".studio")){
fileS = new File(fileS.getParent(),fileS.getName()+".studio");
}
try {
Studio.save(fileS);
} catch (IOException | XMLStreamException | IllegalArgumentException | IllegalAccessException | TransformerException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Studio is saved!");
ResourceMonitor.getInstance().addMessage(label);
// String build = new Version().getBuild();
setTitle("WebcamStudio " + Version.version + " ("+fileS.getName()+")");
}
return null;
}
@Override
protected void done(){
Tools.sleep(10);
waitingD.dispose();
}
};
worker.execute();
waitingD.toFront();
waitingD.setVisible(true);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Saving Cancelled!");
ResourceMonitor.getInstance().addMessage(label);
}
} catch (HeadlessException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Error: " + ex.getMessage());
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_btnSaveStudioActionPerformed
public static class WaitingDialog extends JDialog {
private final JLabel workingLabel = new JLabel();
public WaitingDialog(JFrame owner) {
workingLabel.setBorder(BorderFactory.createLineBorder(Color.black));
workingLabel.setIcon(new ImageIcon(getClass().getResource("/webcamstudio/resources/tango/working-4.png"))); // NOI18N
workingLabel.setText(" Working... ");
this.setUndecorated(true);
this.add(workingLabel);
this.pack();
// move window to center of owner
int x = owner.getX()
+ (owner.getWidth() - this.getPreferredSize().width) / 2;
int y = owner.getY()
+ (owner.getHeight() - this.getPreferredSize().height) / 2;
this.setLocation(x, y);
this.repaint();
}
}
public static void getWebcamParams(Stream stream, VideoDevice d) {
String infoCmd;
Runtime rt = Runtime.getRuntime();
infoCmd = "v4l2-ctl --get-fmt-video --device " + d.getFile();
// System.out.println("infoCmd: "+infoCmd);
File fileD = new File(userHomeDir+"/.webcamstudio/"+"dSize.sh");
FileOutputStream fosD;
DataOutputStream dosD = null;
try {
fosD = new FileOutputStream(fileD);
dosD= new DataOutputStream(fosD);
} catch (FileNotFoundException ex) {
Logger.getLogger(ProcessRenderer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (dosD != null) {
dosD.writeBytes("#!/bin/bash\n");
dosD.writeBytes(infoCmd+"\n");
dosD.close();
}
} catch (IOException ex) {
Logger.getLogger(ProcessRenderer.class.getName()).log(Level.SEVERE, null, ex);
}
fileD.setExecutable(true);
String batchDurationComm = userHomeDir+"/.webcamstudio/"+"dSize.sh";
try {
Process infoP = rt.exec(batchDurationComm);
Tools.sleep(10);
infoP.waitFor(); //Author spoonybard896
InputStream lsOut = infoP.getInputStream();
InputStreamReader isr = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(isr);
String lineR;
while ((lineR = in.readLine()) != null) {
// System.out.println("lineR: "+lineR);
if(lineR.contains("Width")) {
lineR = lineR.trim();
String[] temp;
temp = lineR.split(":");
// System.out.println("Split:"+temp[0]+" Split:"+temp[1]);
String Res = temp[1].replaceAll(" ", "");
String[] wh;
wh = Res.split("/");
int w = Integer.parseInt(wh[0]);
int h = Integer.parseInt(wh[1]);
// System.out.println("W:"+w+" H:"+h);
int mixerW = MasterMixer.getInstance().getWidth();
int mixerH = MasterMixer.getInstance().getHeight();
int hAR = (mixerW*h)/w;
int wAR = (mixerH*w)/h;
if (hAR > mixerH) {
hAR = mixerH;
int xPos = (mixerW - wAR)/2;
stream.setX(xPos);
stream.setWidth(wAR);
}
if (w > mixerW) {
int yPos = (mixerH- hAR)/2;
stream.setY(yPos);
stream.setHeight(hAR);
} else {
if (h < mixerH) {
int yPos = (mixerH- hAR)/2;
stream.setY(yPos);
} else {
hAR = mixerH;
}
}
stream.setHeight(hAR);
}
}
} catch (IOException | InterruptedException | NumberFormatException e) {
}
}
public static void getVideoParams(Stream stream, File file, BufferedImage image) {
if (image != null) {
if (autoAR) {
int w = image.getWidth();
int h = image.getHeight();
int mixerW = MasterMixer.getInstance().getWidth();
int mixerH = MasterMixer.getInstance().getHeight();
int hAR = (mixerW*h)/w;
int wAR = (mixerH*w)/h;
if (hAR > mixerH) {
hAR = mixerH;
int xPos = (mixerW - wAR)/2;
stream.setX(xPos);
stream.setWidth(wAR);
}
if (w > mixerW) {
int yPos = (mixerH- hAR)/2;
stream.setY(yPos);
stream.setHeight(hAR);
} else {
if (h < mixerH) {
int yPos = (mixerH- hAR)/2;
stream.setY(yPos);
} else {
hAR = mixerH;
}
}
stream.setHeight(hAR);
}
} else {
String infoCmd;
Runtime rt = Runtime.getRuntime();
if (Screen.avconvDetected()){
infoCmd = "avconv -i " + "\"" + file.getAbsolutePath() + "\"";
} else {
infoCmd = "ffmpeg -i " + "\"" + file.getAbsolutePath() + "\"";
}
File fileD = new File(userHomeDir+"/.webcamstudio/"+"DCalc.sh");
FileOutputStream fosD;
DataOutputStream dosD = null;
try {
fosD = new FileOutputStream(fileD);
dosD= new DataOutputStream(fosD);
} catch (FileNotFoundException ex) {
Logger.getLogger(ProcessRenderer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (dosD != null) {
dosD.writeBytes("#!/bin/bash\n");
dosD.writeBytes(infoCmd+"\n");
dosD.close();
}
} catch (IOException ex) {
Logger.getLogger(ProcessRenderer.class.getName()).log(Level.SEVERE, null, ex);
}
fileD.setExecutable(true);
String batchDurationComm = userHomeDir+"/.webcamstudio/"+"DCalc.sh";
try {
Process duration = rt.exec(batchDurationComm);
boolean audiofind = false;
Tools.sleep(10);
duration.waitFor(); //Author spoonybard896
InputStream lsOut = duration.getErrorStream();
InputStreamReader isr = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(isr);
String lineR;
while ((lineR = in.readLine()) != null) {
if(lineR.contains("Duration:")) {
lineR = lineR.replaceFirst("Duration: ", "");
lineR = lineR.trim();
String resu = lineR.substring(0, 8);
String[] temp;
temp = resu.split(":");
int hours = Integer.parseInt(temp[0]);
int minutes = Integer.parseInt(temp[1]);
int seconds = Integer.parseInt(temp[2]);
int totalTime = hours*3600 + minutes*60 + seconds;
String strDuration = Integer.toString(totalTime);
stream.setStreamTime(strDuration+"s");
}
if (lineR.contains("Audio:")) {
if (lineR.contains("0 channels")) {
audiofind = false;
} else {
audiofind = true;
}
}
if (autoAR) {
if (lineR.contains("Video:")) {
String [] lineRParts = lineR.split(",");
String [] tempNativeSize = lineRParts[2].split(" ");
String [] videoNativeSize = tempNativeSize[1].split("x");
int w = Integer.parseInt(videoNativeSize[0]);
int h = Integer.parseInt(videoNativeSize[1]);
int mixerW = MasterMixer.getInstance().getWidth();
int mixerH = MasterMixer.getInstance().getHeight();
int hAR = (mixerW*h)/w;
int wAR = (mixerH*w)/h;
if (hAR > mixerH) {
hAR = mixerH;
int xPos = (mixerW - wAR)/2;
stream.setX(xPos);
stream.setWidth(wAR);
}
if (w > mixerW) {
int yPos = (mixerH- hAR)/2;
stream.setY(yPos);
stream.setHeight(hAR);
} else {
if (h < mixerH) {
int yPos = (mixerH- hAR)/2;
stream.setY(yPos);
} else {
hAR = mixerH;
}
}
stream.setHeight(hAR);
}
}
}
// System.out.println(audiofind);
stream.setOnlyVideo(!audiofind);
stream.setAudio(audiofind);
} catch (IOException | InterruptedException | NumberFormatException e) {
}
}
}
public static String wsDistroWatch() {
String distro = null;
Runtime rt = Runtime.getRuntime();
String distroCmd = "uname -a";
try {
Process distroProc = rt.exec(distroCmd);
Tools.sleep(10);
distroProc.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(
distroProc.getInputStream()));
String lineR;
while ((lineR = buf.readLine()) != null) {
if(lineR.toLowerCase().contains("ubuntu")) {
distro = "ubuntu";
} else {
distro = "others";
}
}
} catch (IOException | InterruptedException | NumberFormatException e) {
}
return distro;
}
@SuppressWarnings("unchecked")
private void btnLoadStudioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadStudioActionPerformed
final java.awt.event.ActionEvent fEvt = evt;
ArrayList<Stream> streamzI = MasterChannels.getInstance().getStreams();
ArrayList<String> sourceChI = MasterChannels.getInstance().getChannels();
int sinkStream = 0;
for (Stream s : streamzI) {
if (s.getClass().toString().contains("Sink")) {
sinkStream ++;
}
}
if (streamzI.size() - sinkStream > 0 || sourceChI.size() > 0) {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(this,
"Current Studio will be closed !!!","Attention",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]);
}
JFileChooser chooser = new JFileChooser(lastFolder);
FileNameExtensionFilter studioFilter = new FileNameExtensionFilter("Studio files (*.studio)", "studio");
chooser.setFileFilter(studioFilter);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("Load a Studio ...");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int retval = chooser.showOpenDialog(this);
final File file = chooser.getSelectedFile();
if (retval == JFileChooser.APPROVE_OPTION) {
final WaitingDialog waitingD = new WaitingDialog(this);
waitingD.setModal(true);
SwingWorker<?,?> worker = new SwingWorker<Void,Integer>(){
@Override
protected Void doInBackground() throws InterruptedException{
if (file != null) {
lastFolder = file.getParentFile();
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
for (Stream s : MasterChannels.getInstance().getStreams()){
s.updateStatus();
}
ArrayList<Stream> streamz = MasterChannels.getInstance().getStreams();
ArrayList<String> sourceCh = MasterChannels.getInstance().getChannels();
do {
for (int l=0; l< streamz.size(); l++) {
Stream removeS = streamz.get(l);
Tools.sleep(20);
removeS.destroy();
removeS = null;
}
for (int a=0; a< sourceCh.size(); a++) {
String removeSc = sourceCh.get(a);
MasterChannels.getInstance().removeChannel(removeSc);
Tools.sleep(20);
listenerCP.removeChannels(removeSc, a);
}
} while (streamz.size()>0 || sourceCh.size()>0);
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
listenerCP.stopChTime(fEvt);
listenerCP.resetBtnStates(fEvt);
listenerOP.resetBtnStates(fEvt);
tabControls.removeAll();
lblSourceSelected.setText("");
tabControls.repaint();
Tools.sleep(300);
desktop.removeAll();
desktop.repaint();
Tools.sleep(50);
try {
Studio.LText = new ArrayList<>();
Studio.extstream = new ArrayList<>();
Studio.ImgMovMus = new ArrayList<>();
Studio.load(file, "load");
Studio.main();
spinWidth.setValue(MasterMixer.getInstance().getWidth());
spinHeight.setValue(MasterMixer.getInstance().getHeight());
spinFPS.setValue(MasterMixer.getInstance().getRate());
int mW = (Integer) spinWidth.getValue();
int mH = (Integer) spinHeight.getValue();
MasterMixer.getInstance().stop();
MasterMixer.getInstance().setWidth(mW);
MasterMixer.getInstance().setHeight(mH);
MasterMixer.getInstance().setRate((Integer) spinFPS.getValue());
MasterMixer.getInstance().start();
PreviewMixer.getInstance().stop();
PreviewMixer.getInstance().setWidth(mW);
PreviewMixer.getInstance().setHeight(mH);
// PreviewMixer.getInstance().setRate((Integer) spinFPS.getValue());
PreviewMixer.getInstance().start();
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
// loading studio streams
for (int u = 0; u < Studio.ImgMovMus.size(); u++) {
Stream s = Studio.extstream.get(u);
if (s != null) {
StreamDesktop frame = new StreamDesktop(s, WebcamStudio.this);
frame.setLocation(s.getPanelX(), s.getPanelY());
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
s.setLoaded(false);
}
System.out.println("Adding Source: "+s.getName());
}
Studio.extstream.clear();
Studio.extstream = null;
Studio.ImgMovMus.clear();
Studio.ImgMovMus = null;
for (SourceText text : Studio.LText) {
if (text != null) {
StreamDesktop frame = new StreamDesktop(text, WebcamStudio.this);
frame.setLocation(text.getPanelX(), text.getPanelY());
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
text.setLoaded(false);
}
System.out.println("Adding Source: "+text.getName());
}
Studio.LText.clear();
Studio.LText = null;
Tools.sleep(300);
// loading studio channels
for (String chsc : MasterChannels.getInstance().getChannels()) {
Tools.sleep(10);
listenerCP.addLoadingChannel(chsc);
}
Studio.chanLoad.clear();
listenerOP.resetSinks(fEvt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Studio is loaded!");
ResourceMonitor.getInstance().addMessage(label);
setTitle("WebcamStudio " + Version.version + " ("+file.getName()+")");
}
return null;
}
@Override
protected void done(){
waitingD.dispose();
}
};
worker.execute();
waitingD.toFront();
waitingD.setVisible(true);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Loading Cancelled!");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_btnLoadStudioActionPerformed
private void WCSAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WCSAboutActionPerformed
About TAbout = new About(about, true);
TAbout.setLocationRelativeTo(WebcamStudio.cboAnimations);
TAbout.setVisible(true);
}//GEN-LAST:event_WCSAboutActionPerformed
private void btnAddWebcamsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddWebcamsActionPerformed
final String wCam = cboWebcam.getSelectedItem().toString();
if (Tools.getOS() == OS.LINUX) {
for (VideoDevice d : VideoDevice.getOutputDevices()) {
if (d.getName().equals(wCam)){
Stream webcam = new SourceWebcam(d.getFile());
webcam.setName(d.getName());
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
webcam.addChannel(SourceChannel.getChannel(sc, webcam));
}
getWebcamParams(webcam, d);
StreamDesktop frame = new StreamDesktop(webcam, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}//GEN-LAST:event_btnAddWebcamsActionPerformed
private void btnNewStudioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewStudioActionPerformed
boolean doNew = true;
ArrayList<Stream> streamzI = MasterChannels.getInstance().getStreams();
int sinkStream = 0;
for (Stream s : streamzI) {
// System.out.println("Stream: "+s);
if (s.getClass().toString().contains("Sink")) {
sinkStream ++;
}
}
ArrayList<String> sourceChI = MasterChannels.getInstance().getChannels();
if (streamzI.size() - sinkStream > 0 || sourceChI.size() > 0) {
int result = JOptionPane.showConfirmDialog(this,"Current Studio will be closed !!!","Attention",JOptionPane.YES_NO_CANCEL_OPTION);
switch(result){
case JOptionPane.YES_OPTION:
doNew = true;
break;
case JOptionPane.NO_OPTION:
doNew = false;
break;
case JOptionPane.CANCEL_OPTION:
doNew = false;
break;
case JOptionPane.CLOSED_OPTION:
doNew = false;
break;
}
}
if (doNew) {
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
for (Stream s : MasterChannels.getInstance().getStreams()){
s.updateStatus();
}
ArrayList<Stream> streamz = MasterChannels.getInstance().getStreams();
ArrayList<String> sourceCh = MasterChannels.getInstance().getChannels();
do {
for (int l=0; l< streamz.size(); l++) {
Stream removeS = streamz.get(l);
removeS.destroy();
removeS = null;
}
for (int a=0; a< sourceCh.size(); a++) {
String removeSc = sourceCh.get(a);
MasterChannels.getInstance().removeChannel(removeSc);
listenerCP.removeChannels(removeSc, a);
}
} while (streamz.size()>0 || sourceCh.size()>0);
listenerCP.stopChTime(evt);
listenerCP.resetBtnStates(evt);
listenerOP.resetBtnStates(evt);
listenerOP.resetSinks(evt);
tabControls.removeAll();
lblSourceSelected.setText("");
tabControls.repaint();
Tools.sleep(300);
desktop.removeAll();
desktop.repaint();
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "New Studio Created.");
ResourceMonitor.getInstance().addMessage(label);
setTitle("WebcamStudio " + Version.version);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "New Studio Action Cancelled.");
ResourceMonitor.getInstance().addMessage(label);
}
System.gc();
}//GEN-LAST:event_btnNewStudioActionPerformed
private void btnAddDVBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddDVBActionPerformed
SourceDVB streamDVB;
streamDVB = new SourceDVB();
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamDVB.addChannel(SourceChannel.getChannel(sc, streamDVB));
}
StreamDesktop frame = new StreamDesktop(streamDVB, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddDVBActionPerformed
private void btnAddURLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddURLActionPerformed
SourceURL streamURL;
streamURL = new SourceURL();
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamURL.addChannel(SourceChannel.getChannel(sc, streamURL));
}
StreamDesktop frame = new StreamDesktop(streamURL, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddURLActionPerformed
private void btnVideoDevInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVideoDevInfoActionPerformed
VideoDeviceInfo vDevsI = new VideoDeviceInfo(vDevInfo, true);
vDevsI.setLocationRelativeTo(WebcamStudio.cboAnimations);
vDevsI.setVisible(true);
}//GEN-LAST:event_btnVideoDevInfoActionPerformed
private void btnRefreshWebcamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshWebcamActionPerformed
initWebcam();
}//GEN-LAST:event_btnRefreshWebcamActionPerformed
private void btnAddAudioSrcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddAudioSrcActionPerformed
SourceAudioSource source = new SourceAudioSource();
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
source.addChannel(SourceChannel.getChannel(sc, source));
}
StreamDesktop frame = new StreamDesktop(source, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddAudioSrcActionPerformed
private void cboAudioHzActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboAudioHzActionPerformed
final String audioHz = cboAudioHz.getSelectedItem().toString();
if (audioHz.equals("22050Hz")) {
audioFreq = 22050;
} else {
audioFreq = 44100;
}
MasterMixer.getInstance().stop();
PreviewMixer.getInstance().stop();
Tools.sleep(100);
SystemPlayer.getInstance(null).stop();
Tools.sleep(30);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(30);
MasterChannels.getInstance().stopAllStream();
for (Stream s : streamS){
s.updateStatus();
}
MasterMixer.getInstance().start();
PreviewMixer.getInstance().start();
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Overall Audio Output set to: "+audioFreq+"Hz");
ResourceMonitor.getInstance().addMessage(label);
}//GEN-LAST:event_cboAudioHzActionPerformed
@SuppressWarnings("unchecked")
private void btnImportStudioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportStudioActionPerformed
JFileChooser chooser = new JFileChooser(lastFolder);
FileNameExtensionFilter studioFilter = new FileNameExtensionFilter("Studio files (*.studio)", "studio");
chooser.setFileFilter(studioFilter);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("Import a Studio ...");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int retval = chooser.showOpenDialog(this);
final File file = chooser.getSelectedFile();
if (retval == JFileChooser.APPROVE_OPTION) {
final WaitingDialog waitingD = new WaitingDialog(this);
waitingD.setModal(true);
SwingWorker<?,?> worker = new SwingWorker<Void,Integer>(){
@Override
protected Void doInBackground() throws InterruptedException{
if (file != null) {
lastFolder = file.getParentFile();
try {
Studio.LText = new ArrayList<>();
Studio.extstream = new ArrayList<>();
Studio.ImgMovMus = new ArrayList<>();
Studio.load(file, "add");
Studio.main();
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
for (int u = 0; u < Studio.ImgMovMus.size(); u++) {
Tools.sleep(10);
Stream s = Studio.extstream.get(u);
if (s != null) {
// System.out.println("Stream Ch: "+s.getChannels());
// to fix 0 channels .studio import
if (s.getChannels().isEmpty()) {
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
// System.out.println("Current Studio Ch: "+scn+" added.");
}
for (String sc : allChan){
s.addChannel(SourceChannel.getChannel(sc, s));
}
}
StreamDesktop frame = new StreamDesktop(s, WebcamStudio.this);
frame.setLocation(s.getPanelX(), s.getPanelY());
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
}
}
Studio.extstream.clear();
Studio.extstream = null;
Studio.ImgMovMus.clear();
Studio.ImgMovMus = null;
for (int t = 0; t < Studio.LText.size(); t++) {
SourceText text = Studio.LText.get(t);
// to fix 0 channels .studio import
if (text.getChannels().isEmpty()) {
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
// System.out.println("Current Studio Ch: "+scn+" added.");
}
for (String sc : allChan){
text.addChannel(SourceChannel.getChannel(sc, text));
}
}
StreamDesktop frame = new StreamDesktop(text, WebcamStudio.this);
frame.setLocation(text.getPanelX(), text.getPanelY());
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
}
Studio.LText.clear();
Studio.LText = null;
Tools.sleep(300);
MasterChannels master = MasterChannels.getInstance(); //
ArrayList<String> chNameL = new ArrayList<>();
for (SourceChannel chsct : Studio.chanLoad) {
chNameL.add(chsct.getName());
}
LinkedHashSet<String> hs = new LinkedHashSet<>(chNameL);
chNameL.clear();
chNameL.addAll(hs);
for (String chsct : chNameL) {
listenerCP.addLoadingChannel(chsct);
master.insertStudio(chsct);
}
Studio.chanLoad.clear();
}
return null;
}
@Override
protected void done(){
waitingD.dispose();
}
};
worker.execute();
waitingD.toFront();
waitingD.setVisible(true);
if (file!=null){
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Studio is Imported!");
ResourceMonitor.getInstance().addMessage(label);
}
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Studio Import Cancelled!");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_btnImportStudioActionPerformed
private void btnAddIPCamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddIPCamActionPerformed
SourceIPCam streamIPCam;
streamIPCam = new SourceIPCam();
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamIPCam.addChannel(SourceChannel.getChannel(sc, streamIPCam));
}
StreamDesktop frame = new StreamDesktop(streamIPCam, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddIPCamActionPerformed
private void tglFFmpegActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tglFFmpegActionPerformed
if (tglFFmpeg.isSelected()){
tglAVconv.setSelected(false);
tglGst.setSelected(false);
outFMEbe = 0;
listenerOP.resetSinks(evt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to FFmpeg.");
ResourceMonitor.getInstance().addMessage(label);
} else {
outFMEbe = 2;
tglAVconv.setEnabled(avconv);
tglGst.setEnabled(true);
tglGst.setSelected(true);
listenerOP.resetSinks(evt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to GStreamer.");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_tglFFmpegActionPerformed
private void btnAddFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFolderActionPerformed
final java.awt.event.ActionEvent fEvt = evt;
JFileChooser chooser = new JFileChooser(lastFolder);
FileNameExtensionFilter mediaFilter = new FileNameExtensionFilter("Supported Media files", "avi", "ogg", "jpeg", "ogv", "mp4", "m4v", "mpg", "divx", "wmv", "flv", "mov", "mkv", "vob", "jpg", "bmp", "png", "gif", "mp3", "wav", "wma", "m4a", ".mp2");
chooser.setFileFilter(mediaFilter);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("Add Media Folder ...");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int retVal = chooser.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
final File dir = chooser.getSelectedFile();
// System.out.println("Dir: "+dir);
final WaitingDialog waitingD = new WaitingDialog(this);
waitingD.setModal(true);
SwingWorker<?,?> worker = new SwingWorker<Void,Integer>(){
@Override
protected Void doInBackground() throws InterruptedException {
boolean noStreams = false;
ArrayList<Stream> allStreams = MasterChannels.getInstance().getStreams();
for (Stream str : allStreams) {
// System.out.println("NoStreams Check: "+str.getClass().toString());
if (!str.getClass().toString().contains("Sink")) {
noStreams = false;
break;
} else {
noStreams = true;
}
}
File[] contents = null;
if (dir != null) {
lastFolder = dir.getAbsoluteFile();
contents = dir.listFiles();
// for ( File f : contents) {
// String fileName = f.getName();
// System.out.println("Name: " + fileName);
// }
}
if (dir != null) {
for ( File file : contents) {
Stream s = Stream.getInstance(file);
if (s != null) {
if (s instanceof SourceMovie || s instanceof SourceMusic || s instanceof SourceImage || s instanceof SourceImageU || stream instanceof SourceImageGif) {
getVideoParams(s, file, null);
}
StreamDesktop frame = new StreamDesktop(s, WebcamStudio.this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
}
}
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Media Folder Imported!");
ResourceMonitor.getInstance().addMessage(label);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "No Directory Selected!");
ResourceMonitor.getInstance().addMessage(label);
}
if (noStreams) {
listenerCP.resetAutoPLBtnState(fEvt);
}
return null;
}
@Override
protected void done(){
waitingD.dispose();
}
};
worker.execute();
waitingD.toFront();
waitingD.setVisible(true);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Loading Cancelled!");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_btnAddFolderActionPerformed
private void btnAddDVCamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddDVCamActionPerformed
SourceDV streamDV;
streamDV = new SourceDV();
ArrayList<String> allChan = new ArrayList<>();
for (String scn : MasterChannels.getInstance().getChannels()){
allChan.add(scn);
}
for (String sc : allChan){
streamDV.addChannel(SourceChannel.getChannel(sc, streamDV));
}
StreamDesktop frame = new StreamDesktop(streamDV, this);
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnAddDVCamActionPerformed
private void tglAVconvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tglAVconvActionPerformed
if (tglAVconv.isSelected()){
tglFFmpeg.setSelected(false);
tglGst.setSelected(false);
outFMEbe = 1;
listenerOP.resetSinks(evt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to Libav.");
ResourceMonitor.getInstance().addMessage(label);
} else {
outFMEbe = 2;
tglFFmpeg.setEnabled(ffmpeg);
tglGst.setEnabled(true);
tglGst.setSelected(true);
listenerOP.resetSinks(evt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to Gstreamer.");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_tglAVconvActionPerformed
private void tglGstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tglGstActionPerformed
if (tglGst.isSelected()){
tglFFmpeg.setSelected(false);
tglAVconv.setSelected(false);
outFMEbe = 2;
listenerOP.resetSinks(evt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to GStreamer.");
ResourceMonitor.getInstance().addMessage(label);
} else {
if (ffmpeg && !avconv){
outFMEbe = 0;
tglFFmpeg.setSelected(true);
tglAVconv.setEnabled(false);
tglGst.setEnabled(true);
} else if (ffmpeg && avconv) {
outFMEbe = 1;
tglFFmpeg.setEnabled(true);
tglAVconv.setSelected(true);
tglGst.setEnabled(true);
} else {
outFMEbe = 1;
tglFFmpeg.setEnabled(false);
tglAVconv.setSelected(true);
tglGst.setEnabled(true);
}
listenerOP.resetSinks(evt);
if (outFMEbe == 1) {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to Libav.");
ResourceMonitor.getInstance().addMessage(label);
} else {
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Output Backend Switched to FFmpeg.");
ResourceMonitor.getInstance().addMessage(label);
}
}
}//GEN-LAST:event_tglGstActionPerformed
private void btnSysGCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSysGCActionPerformed
System.gc();
}//GEN-LAST:event_btnSysGCActionPerformed
private void cboThemeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboThemeActionPerformed
final String themeSW = cboTheme.getSelectedItem().toString();
if (themeSW.equals("Classic")) {
theme = "Classic";
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Master Theme set to \""+theme+"\"");
ResourceMonitor.getInstance().addMessage(label);
} else {
theme = "Dark";
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Master Theme set to \""+theme+"\"");
ResourceMonitor.getInstance().addMessage(label);
}
Thread wsRestart = new Thread(new Runnable() {
@Override
public void run() {
restartDialog();
}
});
if (!firstRun) {
wsRestart.start();
}
}//GEN-LAST:event_cboThemeActionPerformed
private void tglAutoARActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tglAutoARActionPerformed
if (tglAutoAR.isSelected()) {
autoAR = true;
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Automatic Aspect Ratio detection \"On\"");
ResourceMonitor.getInstance().addMessage(label);
} else {
autoAR = false;
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Automatic Aspect Ratio detection \"Off\"");
ResourceMonitor.getInstance().addMessage(label);
}
}//GEN-LAST:event_tglAutoARActionPerformed
/**
*
*/
public void restartDialog(){
Object[] options = {"OK"};
JOptionPane.showOptionDialog(this,
"You need to restart WebcamStudio for the changes to take effect.","Information",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]);
}
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
if (System.getProperty("jna.nosys") == null) {
System.setProperty("jna.nosys", "true");
}
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); // Java 8 Drag'n'Drop Fix
File dir = new File(userHomeDir, ".webcamstudio");
if (!dir.exists()) {
dir.mkdir();
}
System.out.println("Welcome to WebcamStudio "+Version.version + " build "+ new Version().getBuild()+" ...");
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
new WebcamStudio().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
if (args != null){
int c = 0;
for (String arg : args){
System.out.println("Argument: "+arg);
if (arg.endsWith("studio")){
cmdFile = new File(arg);
}
if (arg.equals("-o")) {
cmdOut = args[c+1];
}
if (arg.equals("-autoplay")) {
cmdAutoStart = true;
}
if (arg.equals("-remote")) {
cmdRemote = true;
}
c++;
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton WCSAbout;
private javax.swing.JButton btnAddAnimation;
private javax.swing.JButton btnAddAudioSrc;
private javax.swing.JButton btnAddDVB;
private javax.swing.JButton btnAddDVCam;
private javax.swing.JButton btnAddDesktop;
private javax.swing.JButton btnAddFile;
private javax.swing.JButton btnAddFolder;
private javax.swing.JButton btnAddIPCam;
private javax.swing.JButton btnAddText;
private javax.swing.JButton btnAddURL;
private javax.swing.JButton btnAddWebcams;
private javax.swing.JButton btnImportStudio;
private final javax.swing.JButton btnLoadStudio = new javax.swing.JButton();
private javax.swing.JButton btnMinimizeAll;
private javax.swing.JButton btnNewStudio;
private javax.swing.JButton btnRefreshWebcam;
private javax.swing.JButton btnSaveStudio;
private javax.swing.JButton btnSysGC;
private javax.swing.JButton btnVideoDevInfo;
public static javax.swing.JComboBox cboAnimations;
private javax.swing.JComboBox cboAudioHz;
private javax.swing.JComboBox cboTheme;
private javax.swing.JComboBox cboWebcam;
private javax.swing.JDesktopPane desktop;
private javax.swing.Box.Filler filler1;
private javax.swing.Box.Filler filler2;
private javax.swing.Box.Filler filler3;
private javax.swing.Box.Filler filler4;
private javax.swing.Box.Filler filler5;
private javax.swing.Box.Filler filler6;
private javax.swing.Box.Filler filler7;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JToolBar.Separator jSeparator1;
private javax.swing.JToolBar.Separator jSeparator10;
private javax.swing.JToolBar.Separator jSeparator12;
private javax.swing.JToolBar.Separator jSeparator13;
private javax.swing.JToolBar.Separator jSeparator16;
private javax.swing.JToolBar.Separator jSeparator17;
private javax.swing.JToolBar.Separator jSeparator2;
private javax.swing.JToolBar.Separator jSeparator3;
private javax.swing.JToolBar.Separator jSeparator7;
private javax.swing.JLabel lblAVconv;
private javax.swing.JLabel lblClrRam;
private javax.swing.JLabel lblFFmpeg;
private javax.swing.JLabel lblFFmpeg3;
private javax.swing.JLabel lblGst;
private javax.swing.JLabel lblSourceSelected;
private javax.swing.JSplitPane mainSplit;
private javax.swing.JToolBar mainToolbar;
private javax.swing.JPanel panControls;
private javax.swing.JPanel panSources;
public static javax.swing.JTabbedPane tabControls;
private javax.swing.JToggleButton tglAVconv;
private javax.swing.JToggleButton tglAutoAR;
private javax.swing.JToggleButton tglFFmpeg;
private javax.swing.JToggleButton tglGst;
private javax.swing.JToolBar toolbar;
// End of variables declaration//GEN-END:variables
@Override
public void selectedSource(Stream source) {
String sourceName = source.getName();
String shortName = "";
if (sourceName.length() > 30) {
shortName = source.getName().substring(0, 30)+" ...";
} else {
shortName = sourceName;
}
lblSourceSelected.setText(shortName);
lblSourceSelected.setToolTipText(source.getName());
tabControls.removeAll();
tabControls.repaint();
ArrayList<Component> comps = SourceControls.getControls(source);
for (Component c : comps) {
String cName = c.getName();
tabControls.add(cName, c);
}
}
public void loadAtStart(final File file, final java.awt.event.ActionEvent fEvt){
final WaitingDialog waitingD = new WaitingDialog(this);
waitingD.setModal(true);
SwingWorker<?,?> worker = new SwingWorker<Void,Integer>(){
@Override
protected Void doInBackground() throws InterruptedException{
if (file != null) {
lastFolder = file.getParentFile();
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
for (Stream s : MasterChannels.getInstance().getStreams()){
s.updateStatus();
}
ArrayList<Stream> streamz = MasterChannels.getInstance().getStreams();
ArrayList<String> sourceCh = MasterChannels.getInstance().getChannels();
do {
for (int l=0; l< streamz.size(); l++) {
Stream removeS = streamz.get(l);
Tools.sleep(20);
removeS.destroy();
removeS = null;
}
for (int a=0; a< sourceCh.size(); a++) {
String removeSc = sourceCh.get(a);
MasterChannels.getInstance().removeChannel(removeSc);
Tools.sleep(20);
listenerCP.removeChannels(removeSc, a);
}
} while (streamz.size()>0 || sourceCh.size()>0);
SystemPlayer.getInstance(null).stop();
Tools.sleep(10);
PrePlayer.getPreInstance(null).stop();
Tools.sleep(10);
MasterChannels.getInstance().endAllStream();
listenerCP.stopChTime(fEvt);
listenerCP.resetBtnStates(fEvt);
listenerOP.resetBtnStates(fEvt);
tabControls.removeAll();
tabControls.repaint();
Tools.sleep(300);
desktop.removeAll();
desktop.repaint();
Tools.sleep(50);
try {
Studio.LText = new ArrayList<>();
Studio.extstream = new ArrayList<>();
Studio.ImgMovMus = new ArrayList<>();
Studio.load(file, "load");
Studio.main();
spinWidth.setValue(MasterMixer.getInstance().getWidth());
spinHeight.setValue(MasterMixer.getInstance().getHeight());
spinFPS.setValue(MasterMixer.getInstance().getRate());
int mW = (Integer) spinWidth.getValue();
int mH = (Integer) spinHeight.getValue();
MasterMixer.getInstance().stop();
MasterMixer.getInstance().setWidth(mW);
MasterMixer.getInstance().setHeight(mH);
MasterMixer.getInstance().setRate((Integer) spinFPS.getValue());
MasterMixer.getInstance().start();
PreviewMixer.getInstance().stop();
PreviewMixer.getInstance().setWidth(mW);
PreviewMixer.getInstance().setHeight(mH);
// PreviewMixer.getInstance().setRate((Integer) spinFPS.getValue());
PreviewMixer.getInstance().start();
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
Logger.getLogger(WebcamStudio.class.getName()).log(Level.SEVERE, null, ex);
}
// loading studio streams
for (int u = 0; u < Studio.ImgMovMus.size(); u++) {
Stream s = Studio.extstream.get(u);
if (s != null) {
StreamDesktop frame = new StreamDesktop(s, WebcamStudio.this);
frame.setLocation(s.getPanelX(), s.getPanelY());
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
}
System.out.println("Adding Source: "+s.getName());
}
Studio.extstream.clear();
Studio.extstream = null;
Studio.ImgMovMus.clear();
Studio.ImgMovMus = null;
for (SourceText text : Studio.LText) {
if (text != null) {
StreamDesktop frame = new StreamDesktop(text, WebcamStudio.this);
frame.setLocation(text.getPanelX(), text.getPanelY());
desktop.add(frame, javax.swing.JLayeredPane.DEFAULT_LAYER);
}
System.out.println("Adding Source: "+text.getName());
}
Studio.LText.clear();
Studio.LText = null;
Tools.sleep(300);
// loading studio channels
for (String chsc : MasterChannels.getInstance().getChannels()) {
Tools.sleep(10);
listenerCP.addLoadingChannel(chsc);
}
Studio.chanLoad.clear();
listenerOP.resetSinks(fEvt);
ResourceMonitorLabel label = new ResourceMonitorLabel(System.currentTimeMillis()+10000, "Studio is loaded!");
ResourceMonitor.getInstance().addMessage(label);
setTitle("WebcamStudio " + Version.version + " ("+file.getName()+")");
}
return null;
}
@Override
protected void done(){
waitingD.dispose();
}
};
worker.execute();
waitingD.toFront();
waitingD.setVisible(true);
}
}
| gpl-3.0 |
kleinl/BarcodeScannerWidget_addOn-master | app/src/main/java/com/google/zxing/pdf417/decoder/BarcodeValue.java | 1983 | /*
* Copyright 2013 ZXing 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 com.google.zxing.pdf417.decoder;
import com.google.zxing.pdf417.PDF417Common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author Guenther Grau
*/
final class BarcodeValue {
private final Map<Integer,Integer> values = new HashMap<Integer,Integer>();
/**
* Add an occurrence of a value
*/
void setValue(int value) {
Integer confidence = values.get(value);
if (confidence == null) {
confidence = 0;
}
confidence++;
values.put(value, confidence);
}
/**
* Determines the maximum occurrence of a set value and returns all values which were set with this occurrence.
* @return an array of int, containing the values with the highest occurrence, or null, if no value was set
*/
int[] getValue() {
int maxConfidence = -1;
Collection<Integer> result = new ArrayList<Integer>();
for (Entry<Integer,Integer> entry : values.entrySet()) {
if (entry.getValue() > maxConfidence) {
maxConfidence = entry.getValue();
result.clear();
result.add(entry.getKey());
} else if (entry.getValue() == maxConfidence) {
result.add(entry.getKey());
}
}
return PDF417Common.toIntArray(result);
}
public Integer getConfidence(int value) {
return values.get(value);
}
}
| gpl-3.0 |
maran/omniwallet | old-www/bower_components/sjcl/core/sjcl.js | 2172 | /** @fileOverview Javascript cryptography implementation.
*
* Crush to remove comments, shorten variable names and
* generally reduce transmission size.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
"use strict";
/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
/*global document, window, escape, unescape, module, require, Uint32Array */
/** @namespace The Stanford Javascript Crypto Library, top-level namespace. */
var sjcl = {
/** @namespace Symmetric ciphers. */
cipher: {},
/** @namespace Hash functions. Right now only SHA256 is implemented. */
hash: {},
/** @namespace Key exchange functions. Right now only SRP is implemented. */
keyexchange: {},
/** @namespace Block cipher modes of operation. */
mode: {},
/** @namespace Miscellaneous. HMAC and PBKDF2. */
misc: {},
/**
* @namespace Bit array encoders and decoders.
*
* @description
* The members of this namespace are functions which translate between
* SJCL's bitArrays and other objects (usually strings). Because it
* isn't always clear which direction is encoding and which is decoding,
* the method names are "fromBits" and "toBits".
*/
codec: {},
/** @namespace Exceptions. */
exception: {
/** @constructor Ciphertext is corrupt. */
corrupt: function(message) {
this.toString = function() { return "CORRUPT: "+this.message; };
this.message = message;
},
/** @constructor Invalid parameter. */
invalid: function(message) {
this.toString = function() { return "INVALID: "+this.message; };
this.message = message;
},
/** @constructor Bug or missing feature in SJCL. @constructor */
bug: function(message) {
this.toString = function() { return "BUG: "+this.message; };
this.message = message;
},
/** @constructor Something isn't ready. */
notReady: function(message) {
this.toString = function() { return "NOT READY: "+this.message; };
this.message = message;
}
}
};
if(typeof module !== 'undefined' && module.exports){
module.exports = sjcl;
}
| agpl-3.0 |
stvstnfrd/edx-platform | lms/static/js/i18n/kk-kz/djangojs.js | 7028 |
(function(globals) {
var django = globals.django || (globals.django = {});
django.pluralidx = function(n) {
var v=(n!=1);
if (typeof(v) == 'boolean') {
return v ? 1 : 0;
} else {
return v;
}
};
/* gettext library */
django.catalog = django.catalog || {};
var newcatalog = {
"%(sel)s of %(cnt)s selected": [
"%(cnt)s-\u04a3 %(sel)s-\u044b(\u0456) \u0442\u0430\u04a3\u0434\u0430\u043b\u0434\u044b",
"%(cnt)s-\u04a3 %(sel)s-\u044b(\u0456) \u0442\u0430\u04a3\u0434\u0430\u043b\u0434\u044b"
],
"6 a.m.": "06",
"Available %s": "%s \u0431\u0430\u0440",
"Cancel": "\u0411\u043e\u043b\u0434\u044b\u0440\u043c\u0430\u0443",
"Choose a time": "\u0423\u0430\u049b\u044b\u0442\u0442\u044b \u0442\u0430\u04a3\u0434\u0430",
"Filter": "\u0421\u04af\u0437\u0433\u0456\u0448",
"Hide": "\u0416\u0430\u0441\u044b\u0440\u0443",
"Midnight": "\u0422\u04af\u043d \u0436\u0430\u0440\u044b\u043c",
"Noon": "\u0422\u0430\u043b\u0442\u04af\u0441",
"Now": "\u049a\u0430\u0437\u0456\u0440",
"Remove": "\u04e8\u0448\u0456\u0440\u0443(\u0436\u043e\u044e)",
"Show": "\u041a\u04e9\u0440\u0441\u0435\u0442\u0443",
"Today": "\u0411\u04af\u0433\u0456\u043d",
"Tomorrow": "\u0415\u0440\u0442\u0435\u04a3",
"Yesterday": "\u041a\u0435\u0448\u0435",
"You have selected an action, and you haven't made any changes on individual fields. You're probably looking for the Go button rather than the Save button.": "\u0421\u0456\u0437 \u0421\u0430\u049b\u0442\u0430\u0443 \u0431\u0430\u0442\u044b\u0440\u043c\u0430\u0441\u044b\u043d\u0430 \u049b\u0430\u0440\u0430\u0493\u0430\u043d\u0434\u0430, Go(\u0410\u043b\u0493\u0430) \u0431\u0430\u0442\u044b\u0440\u043c\u0430\u0441\u044b\u043d \u0456\u0437\u0434\u0435\u043f \u043e\u0442\u044b\u0440\u0493\u0430\u043d \u0431\u043e\u043b\u0430\u0440\u0441\u044b\u0437, \u0441\u0435\u0431\u0435\u0431\u0456 \u0435\u0448\u049b\u0430\u043d\u0434\u0430\u0439 \u04e9\u0437\u0433\u0435\u0440\u0456\u0441 \u0436\u0430\u0441\u0430\u043c\u0430\u0439, \u04d9\u0440\u0435\u043a\u0435\u0442 \u0436\u0430\u0441\u0430\u0434\u044b\u04a3\u044b\u0437.",
"You have selected an action, but you haven't saved your changes to individual fields yet. Please click OK to save. You'll need to re-run the action.": "\u0421\u0456\u0437 \u04e9\u0437 \u04e9\u0437\u0433\u0435\u0440\u0456\u0441\u0442\u0435\u0440\u0456\u04a3\u0456\u0437\u0434\u0456 \u0441\u0430\u049b\u0442\u0430\u043c\u0430\u0439, \u04d9\u0440\u0435\u043a\u0435\u0442 \u0436\u0430\u0441\u0430\u0434\u044b\u04a3\u044b\u0437. \u04e8\u0442\u0456\u043d\u0456\u0448, \u0441\u0430\u049b\u0442\u0430\u0443 \u04af\u0448\u0456\u043d \u041e\u041a \u0431\u0430\u0442\u044b\u0440\u043c\u0430\u0441\u044b\u043d \u0431\u0430\u0441\u044b\u04a3\u044b\u0437 \u0436\u04d9\u043d\u0435 \u04e9\u0437 \u04d9\u0440\u0435\u043a\u0435\u0442\u0456\u04a3\u0456\u0437\u0434\u0456 \u049b\u0430\u0439\u0442\u0430 \u0436\u0430\u0441\u0430\u043f \u043a\u04e9\u0440\u0456\u04a3\u0456\u0437. ",
"You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost.": "\u0421\u0456\u0437\u0434\u0456\u04a3 \u0442\u04e9\u043c\u0435\u043d\u0434\u0435\u0433\u0456 \u04e9\u0437\u0433\u0435\u0440\u043c\u0435\u043b\u0456 \u0430\u043b\u0430\u04a3\u0434\u0430\u0440\u0434\u0430(fields) \u04e9\u0437\u0433\u0435\u0440\u0456\u0441\u0442\u0435\u0440\u0456\u04a3\u0456\u0437 \u0431\u0430\u0440. \u0415\u0433\u0435\u0440 \u0430\u0440\u0442\u044b\u049b \u04d9\u0440\u0435\u043a\u0435\u0442 \u0436\u0430\u0441\u0430\u0441\u0430\u04a3\u044b\u0437\u0431 \u0441\u0456\u0437 \u04e9\u0437\u0433\u0435\u0440\u0456\u0441\u0442\u0435\u0440\u0456\u04a3\u0456\u0437\u0434\u0456 \u0436\u043e\u0493\u0430\u043b\u0442\u0430\u0441\u044b\u0437."
};
for (var key in newcatalog) {
django.catalog[key] = newcatalog[key];
}
if (!django.jsi18n_initialized) {
django.gettext = function(msgid) {
var value = django.catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
};
django.ngettext = function(singular, plural, count) {
var value = django.catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value.constructor === Array ? value[django.pluralidx(count)] : value;
}
};
django.gettext_noop = function(msgid) { return msgid; };
django.pgettext = function(context, msgid) {
var value = django.gettext(context + '\x04' + msgid);
if (value.indexOf('\x04') != -1) {
value = msgid;
}
return value;
};
django.npgettext = function(context, singular, plural, count) {
var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
if (value.indexOf('\x04') != -1) {
value = django.ngettext(singular, plural, count);
}
return value;
};
django.interpolate = function(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
};
/* formatting library */
django.formats = {
"DATETIME_FORMAT": "N j, Y, P",
"DATETIME_INPUT_FORMATS": [
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%m/%d/%Y %H:%M:%S",
"%m/%d/%Y %H:%M:%S.%f",
"%m/%d/%Y %H:%M",
"%m/%d/%Y",
"%m/%d/%y %H:%M:%S",
"%m/%d/%y %H:%M:%S.%f",
"%m/%d/%y %H:%M",
"%m/%d/%y"
],
"DATE_FORMAT": "N j, Y",
"DATE_INPUT_FORMATS": [
"%Y-%m-%d",
"%m/%d/%Y",
"%m/%d/%y",
"%b %d %Y",
"%b %d, %Y",
"%d %b %Y",
"%d %b, %Y",
"%B %d %Y",
"%B %d, %Y",
"%d %B %Y",
"%d %B, %Y"
],
"DECIMAL_SEPARATOR": ".",
"FIRST_DAY_OF_WEEK": 0,
"MONTH_DAY_FORMAT": "F j",
"NUMBER_GROUPING": 0,
"SHORT_DATETIME_FORMAT": "m/d/Y P",
"SHORT_DATE_FORMAT": "m/d/Y",
"THOUSAND_SEPARATOR": ",",
"TIME_FORMAT": "P",
"TIME_INPUT_FORMATS": [
"%H:%M:%S",
"%H:%M:%S.%f",
"%H:%M"
],
"YEAR_MONTH_FORMAT": "F Y"
};
django.get_format = function(format_type) {
var value = django.formats[format_type];
if (typeof(value) == 'undefined') {
return format_type;
} else {
return value;
}
};
/* add to global namespace */
globals.pluralidx = django.pluralidx;
globals.gettext = django.gettext;
globals.ngettext = django.ngettext;
globals.gettext_noop = django.gettext_noop;
globals.pgettext = django.pgettext;
globals.npgettext = django.npgettext;
globals.interpolate = django.interpolate;
globals.get_format = django.get_format;
django.jsi18n_initialized = true;
}
}(this));
| agpl-3.0 |